]> rtime.felk.cvut.cz Git - l4.git/blob - l4/pkg/sqlite/lib/contrib/sqlite3.c
925c15ad247d05ac1bfa4f9ba4bfd4b8dea4644d
[l4.git] / l4 / pkg / sqlite / lib / contrib / sqlite3.c
1 /******************************************************************************
2 ** This file is an amalgamation of many separate C source files from SQLite
3 ** version 3.7.0.  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 default number of frames to accumulate in the log file before
195 ** checkpointing the database in WAL mode.
196 */
197 #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
198 # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT  1000
199 #endif
200
201 /*
202 ** The maximum number of attached databases.  This must be between 0
203 ** and 30.  The upper bound on 30 is because a 32-bit integer bitmap
204 ** is used internally to track attached databases.
205 */
206 #ifndef SQLITE_MAX_ATTACHED
207 # define SQLITE_MAX_ATTACHED 10
208 #endif
209
210
211 /*
212 ** The maximum value of a ?nnn wildcard that the parser will accept.
213 */
214 #ifndef SQLITE_MAX_VARIABLE_NUMBER
215 # define SQLITE_MAX_VARIABLE_NUMBER 999
216 #endif
217
218 /* Maximum page size.  The upper bound on this value is 32768.  This a limit
219 ** imposed by the necessity of storing the value in a 2-byte unsigned integer
220 ** and the fact that the page size must be a power of 2.
221 **
222 ** If this limit is changed, then the compiled library is technically
223 ** incompatible with an SQLite library compiled with a different limit. If
224 ** a process operating on a database with a page-size of 65536 bytes 
225 ** crashes, then an instance of SQLite compiled with the default page-size 
226 ** limit will not be able to rollback the aborted transaction. This could
227 ** lead to database corruption.
228 */
229 #ifndef SQLITE_MAX_PAGE_SIZE
230 # define SQLITE_MAX_PAGE_SIZE 32768
231 #endif
232
233
234 /*
235 ** The default size of a database page.
236 */
237 #ifndef SQLITE_DEFAULT_PAGE_SIZE
238 # define SQLITE_DEFAULT_PAGE_SIZE 1024
239 #endif
240 #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
241 # undef SQLITE_DEFAULT_PAGE_SIZE
242 # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
243 #endif
244
245 /*
246 ** Ordinarily, if no value is explicitly provided, SQLite creates databases
247 ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
248 ** device characteristics (sector-size and atomic write() support),
249 ** SQLite may choose a larger value. This constant is the maximum value
250 ** SQLite will choose on its own.
251 */
252 #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
253 # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
254 #endif
255 #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
256 # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
257 # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
258 #endif
259
260
261 /*
262 ** Maximum number of pages in one database file.
263 **
264 ** This is really just the default value for the max_page_count pragma.
265 ** This value can be lowered (or raised) at run-time using that the
266 ** max_page_count macro.
267 */
268 #ifndef SQLITE_MAX_PAGE_COUNT
269 # define SQLITE_MAX_PAGE_COUNT 1073741823
270 #endif
271
272 /*
273 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
274 ** operator.
275 */
276 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
277 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
278 #endif
279
280 /*
281 ** Maximum depth of recursion for triggers.
282 **
283 ** A value of 1 means that a trigger program will not be able to itself
284 ** fire any triggers. A value of 0 means that no trigger programs at all 
285 ** may be executed.
286 */
287 #ifndef SQLITE_MAX_TRIGGER_DEPTH
288 # define SQLITE_MAX_TRIGGER_DEPTH 1000
289 #endif
290
291 /************** End of sqliteLimit.h *****************************************/
292 /************** Continuing where we left off in sqliteInt.h ******************/
293
294 /* Disable nuisance warnings on Borland compilers */
295 #if defined(__BORLANDC__)
296 #pragma warn -rch /* unreachable code */
297 #pragma warn -ccc /* Condition is always true or false */
298 #pragma warn -aus /* Assigned value is never used */
299 #pragma warn -csu /* Comparing signed and unsigned */
300 #pragma warn -spa /* Suspicious pointer arithmetic */
301 #endif
302
303 /* Needed for various definitions... */
304 #ifndef _GNU_SOURCE
305 # define _GNU_SOURCE
306 #endif
307
308 /*
309 ** Include standard header files as necessary
310 */
311 #ifdef HAVE_STDINT_H
312 #include <stdint.h>
313 #endif
314 #ifdef HAVE_INTTYPES_H
315 #include <inttypes.h>
316 #endif
317
318 /*
319 ** The number of samples of an index that SQLite takes in order to 
320 ** construct a histogram of the table content when running ANALYZE
321 ** and with SQLITE_ENABLE_STAT2
322 */
323 #define SQLITE_INDEX_SAMPLES 10
324
325 /*
326 ** The following macros are used to cast pointers to integers and
327 ** integers to pointers.  The way you do this varies from one compiler
328 ** to the next, so we have developed the following set of #if statements
329 ** to generate appropriate macros for a wide range of compilers.
330 **
331 ** The correct "ANSI" way to do this is to use the intptr_t type. 
332 ** Unfortunately, that typedef is not available on all compilers, or
333 ** if it is available, it requires an #include of specific headers
334 ** that vary from one machine to the next.
335 **
336 ** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
337 ** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
338 ** So we have to define the macros in different ways depending on the
339 ** compiler.
340 */
341 #if defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */
342 # define SQLITE_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))
343 # define SQLITE_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))
344 #elif !defined(__GNUC__)       /* Works for compilers other than LLVM */
345 # define SQLITE_INT_TO_PTR(X)  ((void*)&((char*)0)[X])
346 # define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))
347 #elif defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */
348 # define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
349 # define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
350 #else                          /* Generates a warning - but it always works */
351 # define SQLITE_INT_TO_PTR(X)  ((void*)(X))
352 # define SQLITE_PTR_TO_INT(X)  ((int)(X))
353 #endif
354
355 /*
356 ** The SQLITE_THREADSAFE macro must be defined as either 0 or 1.
357 ** Older versions of SQLite used an optional THREADSAFE macro.
358 ** We support that for legacy
359 */
360 #if !defined(SQLITE_THREADSAFE)
361 #if defined(THREADSAFE)
362 # define SQLITE_THREADSAFE THREADSAFE
363 #else
364 # define SQLITE_THREADSAFE 1
365 #endif
366 #endif
367
368 /*
369 ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
370 ** It determines whether or not the features related to 
371 ** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
372 ** be overridden at runtime using the sqlite3_config() API.
373 */
374 #if !defined(SQLITE_DEFAULT_MEMSTATUS)
375 # define SQLITE_DEFAULT_MEMSTATUS 1
376 #endif
377
378 /*
379 ** Exactly one of the following macros must be defined in order to
380 ** specify which memory allocation subsystem to use.
381 **
382 **     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
383 **     SQLITE_MEMDEBUG               // Debugging version of system malloc()
384 **
385 ** (Historical note:  There used to be several other options, but we've
386 ** pared it down to just these two.)
387 **
388 ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
389 ** the default.
390 */
391 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)>1
392 # error "At most one of the following compile-time configuration options\
393  is allows: SQLITE_SYSTEM_MALLOC, SQLITE_MEMDEBUG"
394 #endif
395 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)==0
396 # define SQLITE_SYSTEM_MALLOC 1
397 #endif
398
399 /*
400 ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
401 ** sizes of memory allocations below this value where possible.
402 */
403 #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
404 # define SQLITE_MALLOC_SOFT_LIMIT 1024
405 #endif
406
407 /*
408 ** We need to define _XOPEN_SOURCE as follows in order to enable
409 ** recursive mutexes on most Unix systems.  But Mac OS X is different.
410 ** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
411 ** so it is omitted there.  See ticket #2673.
412 **
413 ** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
414 ** implemented on some systems.  So we avoid defining it at all
415 ** if it is already defined or if it is unneeded because we are
416 ** not doing a threadsafe build.  Ticket #2681.
417 **
418 ** See also ticket #2741.
419 */
420 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLITE_THREADSAFE
421 #  define _XOPEN_SOURCE 500  /* Needed to enable pthread recursive mutexes */
422 #endif
423
424 /*
425 ** The TCL headers are only needed when compiling the TCL bindings.
426 */
427 #if defined(SQLITE_TCL) || defined(TCLSH)
428 # include <tcl.h>
429 #endif
430
431 /*
432 ** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
433 ** Setting NDEBUG makes the code smaller and run faster.  So the following
434 ** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1
435 ** option is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
436 ** feature.
437 */
438 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
439 # define NDEBUG 1
440 #endif
441
442 /*
443 ** The testcase() macro is used to aid in coverage testing.  When 
444 ** doing coverage testing, the condition inside the argument to
445 ** testcase() must be evaluated both true and false in order to
446 ** get full branch coverage.  The testcase() macro is inserted
447 ** to help ensure adequate test coverage in places where simple
448 ** condition/decision coverage is inadequate.  For example, testcase()
449 ** can be used to make sure boundary values are tested.  For
450 ** bitmask tests, testcase() can be used to make sure each bit
451 ** is significant and used at least once.  On switch statements
452 ** where multiple cases go to the same block of code, testcase()
453 ** can insure that all cases are evaluated.
454 **
455 */
456 #ifdef SQLITE_COVERAGE_TEST
457 SQLITE_PRIVATE   void sqlite3Coverage(int);
458 # define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
459 #else
460 # define testcase(X)
461 #endif
462
463 /*
464 ** The TESTONLY macro is used to enclose variable declarations or
465 ** other bits of code that are needed to support the arguments
466 ** within testcase() and assert() macros.
467 */
468 #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
469 # define TESTONLY(X)  X
470 #else
471 # define TESTONLY(X)
472 #endif
473
474 /*
475 ** Sometimes we need a small amount of code such as a variable initialization
476 ** to setup for a later assert() statement.  We do not want this code to
477 ** appear when assert() is disabled.  The following macro is therefore
478 ** used to contain that setup code.  The "VVA" acronym stands for
479 ** "Verification, Validation, and Accreditation".  In other words, the
480 ** code within VVA_ONLY() will only run during verification processes.
481 */
482 #ifndef NDEBUG
483 # define VVA_ONLY(X)  X
484 #else
485 # define VVA_ONLY(X)
486 #endif
487
488 /*
489 ** The ALWAYS and NEVER macros surround boolean expressions which 
490 ** are intended to always be true or false, respectively.  Such
491 ** expressions could be omitted from the code completely.  But they
492 ** are included in a few cases in order to enhance the resilience
493 ** of SQLite to unexpected behavior - to make the code "self-healing"
494 ** or "ductile" rather than being "brittle" and crashing at the first
495 ** hint of unplanned behavior.
496 **
497 ** In other words, ALWAYS and NEVER are added for defensive code.
498 **
499 ** When doing coverage testing ALWAYS and NEVER are hard-coded to
500 ** be true and false so that the unreachable code then specify will
501 ** not be counted as untested code.
502 */
503 #if defined(SQLITE_COVERAGE_TEST)
504 # define ALWAYS(X)      (1)
505 # define NEVER(X)       (0)
506 #elif !defined(NDEBUG)
507 # define ALWAYS(X)      ((X)?1:(assert(0),0))
508 # define NEVER(X)       ((X)?(assert(0),1):0)
509 #else
510 # define ALWAYS(X)      (X)
511 # define NEVER(X)       (X)
512 #endif
513
514 /*
515 ** Return true (non-zero) if the input is a integer that is too large
516 ** to fit in 32-bits.  This macro is used inside of various testcase()
517 ** macros to verify that we have tested SQLite for large-file support.
518 */
519 #define IS_BIG_INT(X)  (((X)&~(i64)0xffffffff)!=0)
520
521 /*
522 ** The macro unlikely() is a hint that surrounds a boolean
523 ** expression that is usually false.  Macro likely() surrounds
524 ** a boolean expression that is usually true.  GCC is able to
525 ** use these hints to generate better code, sometimes.
526 */
527 #if defined(__GNUC__) && 0
528 # define likely(X)    __builtin_expect((X),1)
529 # define unlikely(X)  __builtin_expect((X),0)
530 #else
531 # define likely(X)    !!(X)
532 # define unlikely(X)  !!(X)
533 #endif
534
535 /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
536 /************** Begin file sqlite3.h *****************************************/
537 /*
538 ** 2001 September 15
539 **
540 ** The author disclaims copyright to this source code.  In place of
541 ** a legal notice, here is a blessing:
542 **
543 **    May you do good and not evil.
544 **    May you find forgiveness for yourself and forgive others.
545 **    May you share freely, never taking more than you give.
546 **
547 *************************************************************************
548 ** This header file defines the interface that the SQLite library
549 ** presents to client programs.  If a C-function, structure, datatype,
550 ** or constant definition does not appear in this file, then it is
551 ** not a published API of SQLite, is subject to change without
552 ** notice, and should not be referenced by programs that use SQLite.
553 **
554 ** Some of the definitions that are in this file are marked as
555 ** "experimental".  Experimental interfaces are normally new
556 ** features recently added to SQLite.  We do not anticipate changes
557 ** to experimental interfaces but reserve the right to make minor changes
558 ** if experience from use "in the wild" suggest such changes are prudent.
559 **
560 ** The official C-language API documentation for SQLite is derived
561 ** from comments in this file.  This file is the authoritative source
562 ** on how SQLite interfaces are suppose to operate.
563 **
564 ** The name of this file under configuration management is "sqlite.h.in".
565 ** The makefile makes some minor changes to this file (such as inserting
566 ** the version number) and changes its name to "sqlite3.h" as
567 ** part of the build process.
568 */
569 #ifndef _SQLITE3_H_
570 #define _SQLITE3_H_
571 #include <stdarg.h>     /* Needed for the definition of va_list */
572
573 /*
574 ** Make sure we can call this stuff from C++.
575 */
576 #if 0
577 extern "C" {
578 #endif
579
580
581 /*
582 ** Add the ability to override 'extern'
583 */
584 #ifndef SQLITE_EXTERN
585 # define SQLITE_EXTERN extern
586 #endif
587
588 #ifndef SQLITE_API
589 # define SQLITE_API
590 #endif
591
592
593 /*
594 ** These no-op macros are used in front of interfaces to mark those
595 ** interfaces as either deprecated or experimental.  New applications
596 ** should not use deprecated interfaces - they are support for backwards
597 ** compatibility only.  Application writers should be aware that
598 ** experimental interfaces are subject to change in point releases.
599 **
600 ** These macros used to resolve to various kinds of compiler magic that
601 ** would generate warning messages when they were used.  But that
602 ** compiler magic ended up generating such a flurry of bug reports
603 ** that we have taken it all out and gone back to using simple
604 ** noop macros.
605 */
606 #define SQLITE_DEPRECATED
607 #define SQLITE_EXPERIMENTAL
608
609 /*
610 ** Ensure these symbols were not defined by some previous header file.
611 */
612 #ifdef SQLITE_VERSION
613 # undef SQLITE_VERSION
614 #endif
615 #ifdef SQLITE_VERSION_NUMBER
616 # undef SQLITE_VERSION_NUMBER
617 #endif
618
619 /*
620 ** CAPI3REF: Compile-Time Library Version Numbers
621 **
622 ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
623 ** evaluates to a string literal that is the SQLite version in the
624 ** format "X.Y.Z" where X is the major version number (always 3 for
625 ** SQLite3) and Y is the minor version number and Z is the release number.)^
626 ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
627 ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
628 ** numbers used in [SQLITE_VERSION].)^
629 ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
630 ** be larger than the release from which it is derived.  Either Y will
631 ** be held constant and Z will be incremented or else Y will be incremented
632 ** and Z will be reset to zero.
633 **
634 ** Since version 3.6.18, SQLite source code has been stored in the
635 ** <a href="http://www.fossil-scm.org/">Fossil configuration management
636 ** system</a>.  ^The SQLITE_SOURCE_ID macro evalutes to
637 ** a string which identifies a particular check-in of SQLite
638 ** within its configuration management system.  ^The SQLITE_SOURCE_ID
639 ** string contains the date and time of the check-in (UTC) and an SHA1
640 ** hash of the entire source tree.
641 **
642 ** See also: [sqlite3_libversion()],
643 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
644 ** [sqlite_version()] and [sqlite_source_id()].
645 */
646 #define SQLITE_VERSION        "3.7.0"
647 #define SQLITE_VERSION_NUMBER 3007000
648 #define SQLITE_SOURCE_ID      "2010-07-20 20:23:38 13ed106c8c279422a6159e28c6887d13a88b7b8b"
649
650 /*
651 ** CAPI3REF: Run-Time Library Version Numbers
652 ** KEYWORDS: sqlite3_version, sqlite3_sourceid
653 **
654 ** These interfaces provide the same information as the [SQLITE_VERSION],
655 ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
656 ** but are associated with the library instead of the header file.  ^(Cautious
657 ** programmers might include assert() statements in their application to
658 ** verify that values returned by these interfaces match the macros in
659 ** the header, and thus insure that the application is
660 ** compiled with matching library and header files.
661 **
662 ** <blockquote><pre>
663 ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
664 ** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
665 ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
666 ** </pre></blockquote>)^
667 **
668 ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
669 ** macro.  ^The sqlite3_libversion() function returns a pointer to the
670 ** to the sqlite3_version[] string constant.  The sqlite3_libversion()
671 ** function is provided for use in DLLs since DLL users usually do not have
672 ** direct access to string constants within the DLL.  ^The
673 ** sqlite3_libversion_number() function returns an integer equal to
674 ** [SQLITE_VERSION_NUMBER].  ^The sqlite3_sourceid() function returns 
675 ** a pointer to a string constant whose value is the same as the 
676 ** [SQLITE_SOURCE_ID] C preprocessor macro.
677 **
678 ** See also: [sqlite_version()] and [sqlite_source_id()].
679 */
680 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
681 SQLITE_API const char *sqlite3_libversion(void);
682 SQLITE_API const char *sqlite3_sourceid(void);
683 SQLITE_API int sqlite3_libversion_number(void);
684
685 /*
686 ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
687 **
688 ** ^The sqlite3_compileoption_used() function returns 0 or 1 
689 ** indicating whether the specified option was defined at 
690 ** compile time.  ^The SQLITE_ prefix may be omitted from the 
691 ** option name passed to sqlite3_compileoption_used().  
692 **
693 ** ^The sqlite3_compileoption_get() function allows interating
694 ** over the list of options that were defined at compile time by
695 ** returning the N-th compile time option string.  ^If N is out of range,
696 ** sqlite3_compileoption_get() returns a NULL pointer.  ^The SQLITE_ 
697 ** prefix is omitted from any strings returned by 
698 ** sqlite3_compileoption_get().
699 **
700 ** ^Support for the diagnostic functions sqlite3_compileoption_used()
701 ** and sqlite3_compileoption_get() may be omitted by specifing the 
702 ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
703 **
704 ** See also: SQL functions [sqlite_compileoption_used()] and
705 ** [sqlite_compileoption_get()] and the [compile_options pragma].
706 */
707 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
708 SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
709 SQLITE_API const char *sqlite3_compileoption_get(int N);
710 #endif
711
712 /*
713 ** CAPI3REF: Test To See If The Library Is Threadsafe
714 **
715 ** ^The sqlite3_threadsafe() function returns zero if and only if
716 ** SQLite was compiled mutexing code omitted due to the
717 ** [SQLITE_THREADSAFE] compile-time option being set to 0.
718 **
719 ** SQLite can be compiled with or without mutexes.  When
720 ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
721 ** are enabled and SQLite is threadsafe.  When the
722 ** [SQLITE_THREADSAFE] macro is 0, 
723 ** the mutexes are omitted.  Without the mutexes, it is not safe
724 ** to use SQLite concurrently from more than one thread.
725 **
726 ** Enabling mutexes incurs a measurable performance penalty.
727 ** So if speed is of utmost importance, it makes sense to disable
728 ** the mutexes.  But for maximum safety, mutexes should be enabled.
729 ** ^The default behavior is for mutexes to be enabled.
730 **
731 ** This interface can be used by an application to make sure that the
732 ** version of SQLite that it is linking against was compiled with
733 ** the desired setting of the [SQLITE_THREADSAFE] macro.
734 **
735 ** This interface only reports on the compile-time mutex setting
736 ** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with
737 ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
738 ** can be fully or partially disabled using a call to [sqlite3_config()]
739 ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
740 ** or [SQLITE_CONFIG_MUTEX].  ^(The return value of the
741 ** sqlite3_threadsafe() function shows only the compile-time setting of
742 ** thread safety, not any run-time changes to that setting made by
743 ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
744 ** is unchanged by calls to sqlite3_config().)^
745 **
746 ** See the [threading mode] documentation for additional information.
747 */
748 SQLITE_API int sqlite3_threadsafe(void);
749
750 /*
751 ** CAPI3REF: Database Connection Handle
752 ** KEYWORDS: {database connection} {database connections}
753 **
754 ** Each open SQLite database is represented by a pointer to an instance of
755 ** the opaque structure named "sqlite3".  It is useful to think of an sqlite3
756 ** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
757 ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
758 ** is its destructor.  There are many other interfaces (such as
759 ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
760 ** [sqlite3_busy_timeout()] to name but three) that are methods on an
761 ** sqlite3 object.
762 */
763 typedef struct sqlite3 sqlite3;
764
765 /*
766 ** CAPI3REF: 64-Bit Integer Types
767 ** KEYWORDS: sqlite_int64 sqlite_uint64
768 **
769 ** Because there is no cross-platform way to specify 64-bit integer types
770 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
771 **
772 ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
773 ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
774 ** compatibility only.
775 **
776 ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
777 ** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The
778 ** sqlite3_uint64 and sqlite_uint64 types can store integer values 
779 ** between 0 and +18446744073709551615 inclusive.
780 */
781 #ifdef SQLITE_INT64_TYPE
782   typedef SQLITE_INT64_TYPE sqlite_int64;
783   typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
784 #elif defined(_MSC_VER) || defined(__BORLANDC__)
785   typedef __int64 sqlite_int64;
786   typedef unsigned __int64 sqlite_uint64;
787 #else
788   typedef long long int sqlite_int64;
789   typedef unsigned long long int sqlite_uint64;
790 #endif
791 typedef sqlite_int64 sqlite3_int64;
792 typedef sqlite_uint64 sqlite3_uint64;
793
794 /*
795 ** If compiling for a processor that lacks floating point support,
796 ** substitute integer for floating-point.
797 */
798 #ifdef SQLITE_OMIT_FLOATING_POINT
799 # define double sqlite3_int64
800 #endif
801
802 /*
803 ** CAPI3REF: Closing A Database Connection
804 **
805 ** ^The sqlite3_close() routine is the destructor for the [sqlite3] object.
806 ** ^Calls to sqlite3_close() return SQLITE_OK if the [sqlite3] object is
807 ** successfullly destroyed and all associated resources are deallocated.
808 **
809 ** Applications must [sqlite3_finalize | finalize] all [prepared statements]
810 ** and [sqlite3_blob_close | close] all [BLOB handles] associated with
811 ** the [sqlite3] object prior to attempting to close the object.  ^If
812 ** sqlite3_close() is called on a [database connection] that still has
813 ** outstanding [prepared statements] or [BLOB handles], then it returns
814 ** SQLITE_BUSY.
815 **
816 ** ^If [sqlite3_close()] is invoked while a transaction is open,
817 ** the transaction is automatically rolled back.
818 **
819 ** The C parameter to [sqlite3_close(C)] must be either a NULL
820 ** pointer or an [sqlite3] object pointer obtained
821 ** from [sqlite3_open()], [sqlite3_open16()], or
822 ** [sqlite3_open_v2()], and not previously closed.
823 ** ^Calling sqlite3_close() with a NULL pointer argument is a 
824 ** harmless no-op.
825 */
826 SQLITE_API int sqlite3_close(sqlite3 *);
827
828 /*
829 ** The type for a callback function.
830 ** This is legacy and deprecated.  It is included for historical
831 ** compatibility and is not documented.
832 */
833 typedef int (*sqlite3_callback)(void*,int,char**, char**);
834
835 /*
836 ** CAPI3REF: One-Step Query Execution Interface
837 **
838 ** The sqlite3_exec() interface is a convenience wrapper around
839 ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
840 ** that allows an application to run multiple statements of SQL
841 ** without having to use a lot of C code. 
842 **
843 ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
844 ** semicolon-separate SQL statements passed into its 2nd argument,
845 ** in the context of the [database connection] passed in as its 1st
846 ** argument.  ^If the callback function of the 3rd argument to
847 ** sqlite3_exec() is not NULL, then it is invoked for each result row
848 ** coming out of the evaluated SQL statements.  ^The 4th argument to
849 ** to sqlite3_exec() is relayed through to the 1st argument of each
850 ** callback invocation.  ^If the callback pointer to sqlite3_exec()
851 ** is NULL, then no callback is ever invoked and result rows are
852 ** ignored.
853 **
854 ** ^If an error occurs while evaluating the SQL statements passed into
855 ** sqlite3_exec(), then execution of the current statement stops and
856 ** subsequent statements are skipped.  ^If the 5th parameter to sqlite3_exec()
857 ** is not NULL then any error message is written into memory obtained
858 ** from [sqlite3_malloc()] and passed back through the 5th parameter.
859 ** To avoid memory leaks, the application should invoke [sqlite3_free()]
860 ** on error message strings returned through the 5th parameter of
861 ** of sqlite3_exec() after the error message string is no longer needed.
862 ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
863 ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
864 ** NULL before returning.
865 **
866 ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
867 ** routine returns SQLITE_ABORT without invoking the callback again and
868 ** without running any subsequent SQL statements.
869 **
870 ** ^The 2nd argument to the sqlite3_exec() callback function is the
871 ** number of columns in the result.  ^The 3rd argument to the sqlite3_exec()
872 ** callback is an array of pointers to strings obtained as if from
873 ** [sqlite3_column_text()], one for each column.  ^If an element of a
874 ** result row is NULL then the corresponding string pointer for the
875 ** sqlite3_exec() callback is a NULL pointer.  ^The 4th argument to the
876 ** sqlite3_exec() callback is an array of pointers to strings where each
877 ** entry represents the name of corresponding result column as obtained
878 ** from [sqlite3_column_name()].
879 **
880 ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
881 ** to an empty string, or a pointer that contains only whitespace and/or 
882 ** SQL comments, then no SQL statements are evaluated and the database
883 ** is not changed.
884 **
885 ** Restrictions:
886 **
887 ** <ul>
888 ** <li> The application must insure that the 1st parameter to sqlite3_exec()
889 **      is a valid and open [database connection].
890 ** <li> The application must not close [database connection] specified by
891 **      the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
892 ** <li> The application must not modify the SQL statement text passed into
893 **      the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
894 ** </ul>
895 */
896 SQLITE_API int sqlite3_exec(
897   sqlite3*,                                  /* An open database */
898   const char *sql,                           /* SQL to be evaluated */
899   int (*callback)(void*,int,char**,char**),  /* Callback function */
900   void *,                                    /* 1st argument to callback */
901   char **errmsg                              /* Error msg written here */
902 );
903
904 /*
905 ** CAPI3REF: Result Codes
906 ** KEYWORDS: SQLITE_OK {error code} {error codes}
907 ** KEYWORDS: {result code} {result codes}
908 **
909 ** Many SQLite functions return an integer result code from the set shown
910 ** here in order to indicates success or failure.
911 **
912 ** New error codes may be added in future versions of SQLite.
913 **
914 ** See also: [SQLITE_IOERR_READ | extended result codes]
915 */
916 #define SQLITE_OK           0   /* Successful result */
917 /* beginning-of-error-codes */
918 #define SQLITE_ERROR        1   /* SQL error or missing database */
919 #define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
920 #define SQLITE_PERM         3   /* Access permission denied */
921 #define SQLITE_ABORT        4   /* Callback routine requested an abort */
922 #define SQLITE_BUSY         5   /* The database file is locked */
923 #define SQLITE_LOCKED       6   /* A table in the database is locked */
924 #define SQLITE_NOMEM        7   /* A malloc() failed */
925 #define SQLITE_READONLY     8   /* Attempt to write a readonly database */
926 #define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
927 #define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
928 #define SQLITE_CORRUPT     11   /* The database disk image is malformed */
929 #define SQLITE_NOTFOUND    12   /* NOT USED. Table or record not found */
930 #define SQLITE_FULL        13   /* Insertion failed because database is full */
931 #define SQLITE_CANTOPEN    14   /* Unable to open the database file */
932 #define SQLITE_PROTOCOL    15   /* Database lock protocol error */
933 #define SQLITE_EMPTY       16   /* Database is empty */
934 #define SQLITE_SCHEMA      17   /* The database schema changed */
935 #define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
936 #define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
937 #define SQLITE_MISMATCH    20   /* Data type mismatch */
938 #define SQLITE_MISUSE      21   /* Library used incorrectly */
939 #define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
940 #define SQLITE_AUTH        23   /* Authorization denied */
941 #define SQLITE_FORMAT      24   /* Auxiliary database format error */
942 #define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
943 #define SQLITE_NOTADB      26   /* File opened that is not a database file */
944 #define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
945 #define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
946 /* end-of-error-codes */
947
948 /*
949 ** CAPI3REF: Extended Result Codes
950 ** KEYWORDS: {extended error code} {extended error codes}
951 ** KEYWORDS: {extended result code} {extended result codes}
952 **
953 ** In its default configuration, SQLite API routines return one of 26 integer
954 ** [SQLITE_OK | result codes].  However, experience has shown that many of
955 ** these result codes are too coarse-grained.  They do not provide as
956 ** much information about problems as programmers might like.  In an effort to
957 ** address this, newer versions of SQLite (version 3.3.8 and later) include
958 ** support for additional result codes that provide more detailed information
959 ** about errors. The extended result codes are enabled or disabled
960 ** on a per database connection basis using the
961 ** [sqlite3_extended_result_codes()] API.
962 **
963 ** Some of the available extended result codes are listed here.
964 ** One may expect the number of extended result codes will be expand
965 ** over time.  Software that uses extended result codes should expect
966 ** to see new result codes in future releases of SQLite.
967 **
968 ** The SQLITE_OK result code will never be extended.  It will always
969 ** be exactly zero.
970 */
971 #define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
972 #define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
973 #define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
974 #define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
975 #define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
976 #define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
977 #define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
978 #define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
979 #define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
980 #define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
981 #define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
982 #define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
983 #define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
984 #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
985 #define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
986 #define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
987 #define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
988 #define SQLITE_IOERR_SHMOPEN           (SQLITE_IOERR | (18<<8))
989 #define SQLITE_IOERR_SHMSIZE           (SQLITE_IOERR | (19<<8))
990 #define SQLITE_IOERR_SHMLOCK           (SQLITE_IOERR | (20<<8))
991 #define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))
992 #define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))
993 #define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))
994
995 /*
996 ** CAPI3REF: Flags For File Open Operations
997 **
998 ** These bit values are intended for use in the
999 ** 3rd parameter to the [sqlite3_open_v2()] interface and
1000 ** in the 4th parameter to the xOpen method of the
1001 ** [sqlite3_vfs] object.
1002 */
1003 #define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
1004 #define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
1005 #define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */
1006 #define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
1007 #define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
1008 #define SQLITE_OPEN_AUTOPROXY        0x00000020  /* VFS only */
1009 #define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */
1010 #define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */
1011 #define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */
1012 #define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
1013 #define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
1014 #define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
1015 #define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
1016 #define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
1017 #define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
1018 #define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
1019 #define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
1020 #define SQLITE_OPEN_WAL              0x00080000  /* VFS only */
1021
1022 /*
1023 ** CAPI3REF: Device Characteristics
1024 **
1025 ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
1026 ** object returns an integer which is a vector of the these
1027 ** bit values expressing I/O characteristics of the mass storage
1028 ** device that holds the file that the [sqlite3_io_methods]
1029 ** refers to.
1030 **
1031 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1032 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1033 ** mean that writes of blocks that are nnn bytes in size and
1034 ** are aligned to an address which is an integer multiple of
1035 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1036 ** that when data is appended to a file, the data is appended
1037 ** first then the size of the file is extended, never the other
1038 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1039 ** information is written to disk in the same order as calls
1040 ** to xWrite().
1041 */
1042 #define SQLITE_IOCAP_ATOMIC                 0x00000001
1043 #define SQLITE_IOCAP_ATOMIC512              0x00000002
1044 #define SQLITE_IOCAP_ATOMIC1K               0x00000004
1045 #define SQLITE_IOCAP_ATOMIC2K               0x00000008
1046 #define SQLITE_IOCAP_ATOMIC4K               0x00000010
1047 #define SQLITE_IOCAP_ATOMIC8K               0x00000020
1048 #define SQLITE_IOCAP_ATOMIC16K              0x00000040
1049 #define SQLITE_IOCAP_ATOMIC32K              0x00000080
1050 #define SQLITE_IOCAP_ATOMIC64K              0x00000100
1051 #define SQLITE_IOCAP_SAFE_APPEND            0x00000200
1052 #define SQLITE_IOCAP_SEQUENTIAL             0x00000400
1053 #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN  0x00000800
1054
1055 /*
1056 ** CAPI3REF: File Locking Levels
1057 **
1058 ** SQLite uses one of these integer values as the second
1059 ** argument to calls it makes to the xLock() and xUnlock() methods
1060 ** of an [sqlite3_io_methods] object.
1061 */
1062 #define SQLITE_LOCK_NONE          0
1063 #define SQLITE_LOCK_SHARED        1
1064 #define SQLITE_LOCK_RESERVED      2
1065 #define SQLITE_LOCK_PENDING       3
1066 #define SQLITE_LOCK_EXCLUSIVE     4
1067
1068 /*
1069 ** CAPI3REF: Synchronization Type Flags
1070 **
1071 ** When SQLite invokes the xSync() method of an
1072 ** [sqlite3_io_methods] object it uses a combination of
1073 ** these integer values as the second argument.
1074 **
1075 ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
1076 ** sync operation only needs to flush data to mass storage.  Inode
1077 ** information need not be flushed. If the lower four bits of the flag
1078 ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
1079 ** If the lower four bits equal SQLITE_SYNC_FULL, that means
1080 ** to use Mac OS X style fullsync instead of fsync().
1081 */
1082 #define SQLITE_SYNC_NORMAL        0x00002
1083 #define SQLITE_SYNC_FULL          0x00003
1084 #define SQLITE_SYNC_DATAONLY      0x00010
1085
1086 /*
1087 ** CAPI3REF: OS Interface Open File Handle
1088 **
1089 ** An [sqlite3_file] object represents an open file in the 
1090 ** [sqlite3_vfs | OS interface layer].  Individual OS interface
1091 ** implementations will
1092 ** want to subclass this object by appending additional fields
1093 ** for their own use.  The pMethods entry is a pointer to an
1094 ** [sqlite3_io_methods] object that defines methods for performing
1095 ** I/O operations on the open file.
1096 */
1097 typedef struct sqlite3_file sqlite3_file;
1098 struct sqlite3_file {
1099   const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
1100 };
1101
1102 /*
1103 ** CAPI3REF: OS Interface File Virtual Methods Object
1104 **
1105 ** Every file opened by the [sqlite3_vfs] xOpen method populates an
1106 ** [sqlite3_file] object (or, more commonly, a subclass of the
1107 ** [sqlite3_file] object) with a pointer to an instance of this object.
1108 ** This object defines the methods used to perform various operations
1109 ** against the open file represented by the [sqlite3_file] object.
1110 **
1111 ** If the xOpen method sets the sqlite3_file.pMethods element 
1112 ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
1113 ** may be invoked even if the xOpen reported that it failed.  The
1114 ** only way to prevent a call to xClose following a failed xOpen
1115 ** is for the xOpen to set the sqlite3_file.pMethods element to NULL.
1116 **
1117 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
1118 ** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
1119 ** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]
1120 ** flag may be ORed in to indicate that only the data of the file
1121 ** and not its inode needs to be synced.
1122 **
1123 ** The integer values to xLock() and xUnlock() are one of
1124 ** <ul>
1125 ** <li> [SQLITE_LOCK_NONE],
1126 ** <li> [SQLITE_LOCK_SHARED],
1127 ** <li> [SQLITE_LOCK_RESERVED],
1128 ** <li> [SQLITE_LOCK_PENDING], or
1129 ** <li> [SQLITE_LOCK_EXCLUSIVE].
1130 ** </ul>
1131 ** xLock() increases the lock. xUnlock() decreases the lock.
1132 ** The xCheckReservedLock() method checks whether any database connection,
1133 ** either in this process or in some other process, is holding a RESERVED,
1134 ** PENDING, or EXCLUSIVE lock on the file.  It returns true
1135 ** if such a lock exists and false otherwise.
1136 **
1137 ** The xFileControl() method is a generic interface that allows custom
1138 ** VFS implementations to directly control an open file using the
1139 ** [sqlite3_file_control()] interface.  The second "op" argument is an
1140 ** integer opcode.  The third argument is a generic pointer intended to
1141 ** point to a structure that may contain arguments or space in which to
1142 ** write return values.  Potential uses for xFileControl() might be
1143 ** functions to enable blocking locks with timeouts, to change the
1144 ** locking strategy (for example to use dot-file locks), to inquire
1145 ** about the status of a lock, or to break stale locks.  The SQLite
1146 ** core reserves all opcodes less than 100 for its own use.
1147 ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
1148 ** Applications that define a custom xFileControl method should use opcodes
1149 ** greater than 100 to avoid conflicts.
1150 **
1151 ** The xSectorSize() method returns the sector size of the
1152 ** device that underlies the file.  The sector size is the
1153 ** minimum write that can be performed without disturbing
1154 ** other bytes in the file.  The xDeviceCharacteristics()
1155 ** method returns a bit vector describing behaviors of the
1156 ** underlying device:
1157 **
1158 ** <ul>
1159 ** <li> [SQLITE_IOCAP_ATOMIC]
1160 ** <li> [SQLITE_IOCAP_ATOMIC512]
1161 ** <li> [SQLITE_IOCAP_ATOMIC1K]
1162 ** <li> [SQLITE_IOCAP_ATOMIC2K]
1163 ** <li> [SQLITE_IOCAP_ATOMIC4K]
1164 ** <li> [SQLITE_IOCAP_ATOMIC8K]
1165 ** <li> [SQLITE_IOCAP_ATOMIC16K]
1166 ** <li> [SQLITE_IOCAP_ATOMIC32K]
1167 ** <li> [SQLITE_IOCAP_ATOMIC64K]
1168 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
1169 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
1170 ** </ul>
1171 **
1172 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1173 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1174 ** mean that writes of blocks that are nnn bytes in size and
1175 ** are aligned to an address which is an integer multiple of
1176 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1177 ** that when data is appended to a file, the data is appended
1178 ** first then the size of the file is extended, never the other
1179 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1180 ** information is written to disk in the same order as calls
1181 ** to xWrite().
1182 **
1183 ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
1184 ** in the unread portions of the buffer with zeros.  A VFS that
1185 ** fails to zero-fill short reads might seem to work.  However,
1186 ** failure to zero-fill short reads will eventually lead to
1187 ** database corruption.
1188 */
1189 typedef struct sqlite3_io_methods sqlite3_io_methods;
1190 struct sqlite3_io_methods {
1191   int iVersion;
1192   int (*xClose)(sqlite3_file*);
1193   int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
1194   int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
1195   int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
1196   int (*xSync)(sqlite3_file*, int flags);
1197   int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
1198   int (*xLock)(sqlite3_file*, int);
1199   int (*xUnlock)(sqlite3_file*, int);
1200   int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
1201   int (*xFileControl)(sqlite3_file*, int op, void *pArg);
1202   int (*xSectorSize)(sqlite3_file*);
1203   int (*xDeviceCharacteristics)(sqlite3_file*);
1204   /* Methods above are valid for version 1 */
1205   int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
1206   int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
1207   void (*xShmBarrier)(sqlite3_file*);
1208   int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
1209   /* Methods above are valid for version 2 */
1210   /* Additional methods may be added in future releases */
1211 };
1212
1213 /*
1214 ** CAPI3REF: Standard File Control Opcodes
1215 **
1216 ** These integer constants are opcodes for the xFileControl method
1217 ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
1218 ** interface.
1219 **
1220 ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
1221 ** opcode causes the xFileControl method to write the current state of
1222 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
1223 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
1224 ** into an integer that the pArg argument points to. This capability
1225 ** is used during testing and only needs to be supported when SQLITE_TEST
1226 ** is defined.
1227 **
1228 ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
1229 ** layer a hint of how large the database file will grow to be during the
1230 ** current transaction.  This hint is not guaranteed to be accurate but it
1231 ** is often close.  The underlying VFS might choose to preallocate database
1232 ** file space based on this hint in order to help writes to the database
1233 ** file run faster.
1234 */
1235 #define SQLITE_FCNTL_LOCKSTATE        1
1236 #define SQLITE_GET_LOCKPROXYFILE      2
1237 #define SQLITE_SET_LOCKPROXYFILE      3
1238 #define SQLITE_LAST_ERRNO             4
1239 #define SQLITE_FCNTL_SIZE_HINT        5
1240
1241 /*
1242 ** CAPI3REF: Mutex Handle
1243 **
1244 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
1245 ** abstract type for a mutex object.  The SQLite core never looks
1246 ** at the internal representation of an [sqlite3_mutex].  It only
1247 ** deals with pointers to the [sqlite3_mutex] object.
1248 **
1249 ** Mutexes are created using [sqlite3_mutex_alloc()].
1250 */
1251 typedef struct sqlite3_mutex sqlite3_mutex;
1252
1253 /*
1254 ** CAPI3REF: OS Interface Object
1255 **
1256 ** An instance of the sqlite3_vfs object defines the interface between
1257 ** the SQLite core and the underlying operating system.  The "vfs"
1258 ** in the name of the object stands for "virtual file system".
1259 **
1260 ** The value of the iVersion field is initially 1 but may be larger in
1261 ** future versions of SQLite.  Additional fields may be appended to this
1262 ** object when the iVersion value is increased.  Note that the structure
1263 ** of the sqlite3_vfs object changes in the transaction between
1264 ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
1265 ** modified.
1266 **
1267 ** The szOsFile field is the size of the subclassed [sqlite3_file]
1268 ** structure used by this VFS.  mxPathname is the maximum length of
1269 ** a pathname in this VFS.
1270 **
1271 ** Registered sqlite3_vfs objects are kept on a linked list formed by
1272 ** the pNext pointer.  The [sqlite3_vfs_register()]
1273 ** and [sqlite3_vfs_unregister()] interfaces manage this list
1274 ** in a thread-safe way.  The [sqlite3_vfs_find()] interface
1275 ** searches the list.  Neither the application code nor the VFS
1276 ** implementation should use the pNext pointer.
1277 **
1278 ** The pNext field is the only field in the sqlite3_vfs
1279 ** structure that SQLite will ever modify.  SQLite will only access
1280 ** or modify this field while holding a particular static mutex.
1281 ** The application should never modify anything within the sqlite3_vfs
1282 ** object once the object has been registered.
1283 **
1284 ** The zName field holds the name of the VFS module.  The name must
1285 ** be unique across all VFS modules.
1286 **
1287 ** SQLite will guarantee that the zFilename parameter to xOpen
1288 ** is either a NULL pointer or string obtained
1289 ** from xFullPathname().  SQLite further guarantees that
1290 ** the string will be valid and unchanged until xClose() is
1291 ** called. Because of the previous sentence,
1292 ** the [sqlite3_file] can safely store a pointer to the
1293 ** filename if it needs to remember the filename for some reason.
1294 ** If the zFilename parameter is xOpen is a NULL pointer then xOpen
1295 ** must invent its own temporary name for the file.  Whenever the 
1296 ** xFilename parameter is NULL it will also be the case that the
1297 ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1298 **
1299 ** The flags argument to xOpen() includes all bits set in
1300 ** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
1301 ** or [sqlite3_open16()] is used, then flags includes at least
1302 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. 
1303 ** If xOpen() opens a file read-only then it sets *pOutFlags to
1304 ** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
1305 **
1306 ** SQLite will also add one of the following flags to the xOpen()
1307 ** call, depending on the object being opened:
1308 **
1309 ** <ul>
1310 ** <li>  [SQLITE_OPEN_MAIN_DB]
1311 ** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
1312 ** <li>  [SQLITE_OPEN_TEMP_DB]
1313 ** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
1314 ** <li>  [SQLITE_OPEN_TRANSIENT_DB]
1315 ** <li>  [SQLITE_OPEN_SUBJOURNAL]
1316 ** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
1317 ** </ul>
1318 **
1319 ** The file I/O implementation can use the object type flags to
1320 ** change the way it deals with files.  For example, an application
1321 ** that does not care about crash recovery or rollback might make
1322 ** the open of a journal file a no-op.  Writes to this journal would
1323 ** also be no-ops, and any attempt to read the journal would return
1324 ** SQLITE_IOERR.  Or the implementation might recognize that a database
1325 ** file will be doing page-aligned sector reads and writes in a random
1326 ** order and set up its I/O subsystem accordingly.
1327 **
1328 ** SQLite might also add one of the following flags to the xOpen method:
1329 **
1330 ** <ul>
1331 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
1332 ** <li> [SQLITE_OPEN_EXCLUSIVE]
1333 ** </ul>
1334 **
1335 ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1336 ** deleted when it is closed.  The [SQLITE_OPEN_DELETEONCLOSE]
1337 ** will be set for TEMP  databases, journals and for subjournals.
1338 **
1339 ** The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
1340 ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
1341 ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
1342 ** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the 
1343 ** SQLITE_OPEN_CREATE, is used to indicate that file should always
1344 ** be created, and that it is an error if it already exists.
1345 ** It is <i>not</i> used to indicate the file should be opened 
1346 ** for exclusive access.
1347 **
1348 ** At least szOsFile bytes of memory are allocated by SQLite
1349 ** to hold the  [sqlite3_file] structure passed as the third
1350 ** argument to xOpen.  The xOpen method does not have to
1351 ** allocate the structure; it should just fill it in.  Note that
1352 ** the xOpen method must set the sqlite3_file.pMethods to either
1353 ** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do
1354 ** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods
1355 ** element will be valid after xOpen returns regardless of the success
1356 ** or failure of the xOpen call.
1357 **
1358 ** The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1359 ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1360 ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1361 ** to test whether a file is at least readable.   The file can be a
1362 ** directory.
1363 **
1364 ** SQLite will always allocate at least mxPathname+1 bytes for the
1365 ** output buffer xFullPathname.  The exact size of the output buffer
1366 ** is also passed as a parameter to both  methods. If the output buffer
1367 ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1368 ** handled as a fatal error by SQLite, vfs implementations should endeavor
1369 ** to prevent this by setting mxPathname to a sufficiently large value.
1370 **
1371 ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
1372 ** interfaces are not strictly a part of the filesystem, but they are
1373 ** included in the VFS structure for completeness.
1374 ** The xRandomness() function attempts to return nBytes bytes
1375 ** of good-quality randomness into zOut.  The return value is
1376 ** the actual number of bytes of randomness obtained.
1377 ** The xSleep() method causes the calling thread to sleep for at
1378 ** least the number of microseconds given.  The xCurrentTime()
1379 ** method returns a Julian Day Number for the current date and time as
1380 ** a floating point value.
1381 ** The xCurrentTimeInt64() method returns, as an integer, the Julian
1382 ** Day Number multipled by 86400000 (the number of milliseconds in 
1383 ** a 24-hour day).  
1384 ** ^SQLite will use the xCurrentTimeInt64() method to get the current
1385 ** date and time if that method is available (if iVersion is 2 or 
1386 ** greater and the function pointer is not NULL) and will fall back
1387 ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
1388 */
1389 typedef struct sqlite3_vfs sqlite3_vfs;
1390 struct sqlite3_vfs {
1391   int iVersion;            /* Structure version number (currently 2) */
1392   int szOsFile;            /* Size of subclassed sqlite3_file */
1393   int mxPathname;          /* Maximum file pathname length */
1394   sqlite3_vfs *pNext;      /* Next registered VFS */
1395   const char *zName;       /* Name of this virtual file system */
1396   void *pAppData;          /* Pointer to application-specific data */
1397   int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1398                int flags, int *pOutFlags);
1399   int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1400   int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1401   int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1402   void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1403   void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1404   void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
1405   void (*xDlClose)(sqlite3_vfs*, void*);
1406   int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1407   int (*xSleep)(sqlite3_vfs*, int microseconds);
1408   int (*xCurrentTime)(sqlite3_vfs*, double*);
1409   int (*xGetLastError)(sqlite3_vfs*, int, char *);
1410   /*
1411   ** The methods above are in version 1 of the sqlite_vfs object
1412   ** definition.  Those that follow are added in version 2 or later
1413   */
1414   int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
1415   /*
1416   ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
1417   ** New fields may be appended in figure versions.  The iVersion
1418   ** value will increment whenever this happens. 
1419   */
1420 };
1421
1422 /*
1423 ** CAPI3REF: Flags for the xAccess VFS method
1424 **
1425 ** These integer constants can be used as the third parameter to
1426 ** the xAccess method of an [sqlite3_vfs] object.  They determine
1427 ** what kind of permissions the xAccess method is looking for.
1428 ** With SQLITE_ACCESS_EXISTS, the xAccess method
1429 ** simply checks whether the file exists.
1430 ** With SQLITE_ACCESS_READWRITE, the xAccess method
1431 ** checks whether the named directory is both readable and writable
1432 ** (in other words, if files can be added, removed, and renamed within
1433 ** the directory).
1434 ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
1435 ** [temp_store_directory pragma], though this could change in a future
1436 ** release of SQLite.
1437 ** With SQLITE_ACCESS_READ, the xAccess method
1438 ** checks whether the file is readable.  The SQLITE_ACCESS_READ constant is
1439 ** currently unused, though it might be used in a future release of
1440 ** SQLite.
1441 */
1442 #define SQLITE_ACCESS_EXISTS    0
1443 #define SQLITE_ACCESS_READWRITE 1   /* Used by PRAGMA temp_store_directory */
1444 #define SQLITE_ACCESS_READ      2   /* Unused */
1445
1446 /*
1447 ** CAPI3REF: Flags for the xShmLock VFS method
1448 **
1449 ** These integer constants define the various locking operations
1450 ** allowed by the xShmLock method of [sqlite3_io_methods].  The
1451 ** following are the only legal combinations of flags to the
1452 ** xShmLock method:
1453 **
1454 ** <ul>
1455 ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
1456 ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
1457 ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
1458 ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
1459 ** </ul>
1460 **
1461 ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
1462 ** was given no the corresponding lock.  
1463 **
1464 ** The xShmLock method can transition between unlocked and SHARED or
1465 ** between unlocked and EXCLUSIVE.  It cannot transition between SHARED
1466 ** and EXCLUSIVE.
1467 */
1468 #define SQLITE_SHM_UNLOCK       1
1469 #define SQLITE_SHM_LOCK         2
1470 #define SQLITE_SHM_SHARED       4
1471 #define SQLITE_SHM_EXCLUSIVE    8
1472
1473 /*
1474 ** CAPI3REF: Maximum xShmLock index
1475 **
1476 ** The xShmLock method on [sqlite3_io_methods] may use values
1477 ** between 0 and this upper bound as its "offset" argument.
1478 ** The SQLite core will never attempt to acquire or release a
1479 ** lock outside of this range
1480 */
1481 #define SQLITE_SHM_NLOCK        8
1482
1483
1484 /*
1485 ** CAPI3REF: Initialize The SQLite Library
1486 **
1487 ** ^The sqlite3_initialize() routine initializes the
1488 ** SQLite library.  ^The sqlite3_shutdown() routine
1489 ** deallocates any resources that were allocated by sqlite3_initialize().
1490 ** These routines are designed to aid in process initialization and
1491 ** shutdown on embedded systems.  Workstation applications using
1492 ** SQLite normally do not need to invoke either of these routines.
1493 **
1494 ** A call to sqlite3_initialize() is an "effective" call if it is
1495 ** the first time sqlite3_initialize() is invoked during the lifetime of
1496 ** the process, or if it is the first time sqlite3_initialize() is invoked
1497 ** following a call to sqlite3_shutdown().  ^(Only an effective call
1498 ** of sqlite3_initialize() does any initialization.  All other calls
1499 ** are harmless no-ops.)^
1500 **
1501 ** A call to sqlite3_shutdown() is an "effective" call if it is the first
1502 ** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only
1503 ** an effective call to sqlite3_shutdown() does any deinitialization.
1504 ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
1505 **
1506 ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
1507 ** is not.  The sqlite3_shutdown() interface must only be called from a
1508 ** single thread.  All open [database connections] must be closed and all
1509 ** other SQLite resources must be deallocated prior to invoking
1510 ** sqlite3_shutdown().
1511 **
1512 ** Among other things, ^sqlite3_initialize() will invoke
1513 ** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()
1514 ** will invoke sqlite3_os_end().
1515 **
1516 ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
1517 ** ^If for some reason, sqlite3_initialize() is unable to initialize
1518 ** the library (perhaps it is unable to allocate a needed resource such
1519 ** as a mutex) it returns an [error code] other than [SQLITE_OK].
1520 **
1521 ** ^The sqlite3_initialize() routine is called internally by many other
1522 ** SQLite interfaces so that an application usually does not need to
1523 ** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
1524 ** calls sqlite3_initialize() so the SQLite library will be automatically
1525 ** initialized when [sqlite3_open()] is called if it has not be initialized
1526 ** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
1527 ** compile-time option, then the automatic calls to sqlite3_initialize()
1528 ** are omitted and the application must call sqlite3_initialize() directly
1529 ** prior to using any other SQLite interface.  For maximum portability,
1530 ** it is recommended that applications always invoke sqlite3_initialize()
1531 ** directly prior to using any other SQLite interface.  Future releases
1532 ** of SQLite may require this.  In other words, the behavior exhibited
1533 ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
1534 ** default behavior in some future release of SQLite.
1535 **
1536 ** The sqlite3_os_init() routine does operating-system specific
1537 ** initialization of the SQLite library.  The sqlite3_os_end()
1538 ** routine undoes the effect of sqlite3_os_init().  Typical tasks
1539 ** performed by these routines include allocation or deallocation
1540 ** of static resources, initialization of global variables,
1541 ** setting up a default [sqlite3_vfs] module, or setting up
1542 ** a default configuration using [sqlite3_config()].
1543 **
1544 ** The application should never invoke either sqlite3_os_init()
1545 ** or sqlite3_os_end() directly.  The application should only invoke
1546 ** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
1547 ** interface is called automatically by sqlite3_initialize() and
1548 ** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
1549 ** implementations for sqlite3_os_init() and sqlite3_os_end()
1550 ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
1551 ** When [custom builds | built for other platforms]
1552 ** (using the [SQLITE_OS_OTHER=1] compile-time
1553 ** option) the application must supply a suitable implementation for
1554 ** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
1555 ** implementation of sqlite3_os_init() or sqlite3_os_end()
1556 ** must return [SQLITE_OK] on success and some other [error code] upon
1557 ** failure.
1558 */
1559 SQLITE_API int sqlite3_initialize(void);
1560 SQLITE_API int sqlite3_shutdown(void);
1561 SQLITE_API int sqlite3_os_init(void);
1562 SQLITE_API int sqlite3_os_end(void);
1563
1564 /*
1565 ** CAPI3REF: Configuring The SQLite Library
1566 **
1567 ** The sqlite3_config() interface is used to make global configuration
1568 ** changes to SQLite in order to tune SQLite to the specific needs of
1569 ** the application.  The default configuration is recommended for most
1570 ** applications and so this routine is usually not necessary.  It is
1571 ** provided to support rare applications with unusual needs.
1572 **
1573 ** The sqlite3_config() interface is not threadsafe.  The application
1574 ** must insure that no other SQLite interfaces are invoked by other
1575 ** threads while sqlite3_config() is running.  Furthermore, sqlite3_config()
1576 ** may only be invoked prior to library initialization using
1577 ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1578 ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
1579 ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
1580 ** Note, however, that ^sqlite3_config() can be called as part of the
1581 ** implementation of an application-defined [sqlite3_os_init()].
1582 **
1583 ** The first argument to sqlite3_config() is an integer
1584 ** [SQLITE_CONFIG_SINGLETHREAD | configuration option] that determines
1585 ** what property of SQLite is to be configured.  Subsequent arguments
1586 ** vary depending on the [SQLITE_CONFIG_SINGLETHREAD | configuration option]
1587 ** in the first argument.
1588 **
1589 ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
1590 ** ^If the option is unknown or SQLite is unable to set the option
1591 ** then this routine returns a non-zero [error code].
1592 */
1593 SQLITE_API int sqlite3_config(int, ...);
1594
1595 /*
1596 ** CAPI3REF: Configure database connections
1597 **
1598 ** The sqlite3_db_config() interface is used to make configuration
1599 ** changes to a [database connection].  The interface is similar to
1600 ** [sqlite3_config()] except that the changes apply to a single
1601 ** [database connection] (specified in the first argument).  The
1602 ** sqlite3_db_config() interface should only be used immediately after
1603 ** the database connection is created using [sqlite3_open()],
1604 ** [sqlite3_open16()], or [sqlite3_open_v2()].  
1605 **
1606 ** The second argument to sqlite3_db_config(D,V,...)  is the
1607 ** configuration verb - an integer code that indicates what
1608 ** aspect of the [database connection] is being configured.
1609 ** The only choice for this value is [SQLITE_DBCONFIG_LOOKASIDE].
1610 ** New verbs are likely to be added in future releases of SQLite.
1611 ** Additional arguments depend on the verb.
1612 **
1613 ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
1614 ** the call is considered successful.
1615 */
1616 SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
1617
1618 /*
1619 ** CAPI3REF: Memory Allocation Routines
1620 **
1621 ** An instance of this object defines the interface between SQLite
1622 ** and low-level memory allocation routines.
1623 **
1624 ** This object is used in only one place in the SQLite interface.
1625 ** A pointer to an instance of this object is the argument to
1626 ** [sqlite3_config()] when the configuration option is
1627 ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].  
1628 ** By creating an instance of this object
1629 ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
1630 ** during configuration, an application can specify an alternative
1631 ** memory allocation subsystem for SQLite to use for all of its
1632 ** dynamic memory needs.
1633 **
1634 ** Note that SQLite comes with several [built-in memory allocators]
1635 ** that are perfectly adequate for the overwhelming majority of applications
1636 ** and that this object is only useful to a tiny minority of applications
1637 ** with specialized memory allocation requirements.  This object is
1638 ** also used during testing of SQLite in order to specify an alternative
1639 ** memory allocator that simulates memory out-of-memory conditions in
1640 ** order to verify that SQLite recovers gracefully from such
1641 ** conditions.
1642 **
1643 ** The xMalloc and xFree methods must work like the
1644 ** malloc() and free() functions from the standard C library.
1645 ** The xRealloc method must work like realloc() from the standard C library
1646 ** with the exception that if the second argument to xRealloc is zero,
1647 ** xRealloc must be a no-op - it must not perform any allocation or
1648 ** deallocation.  ^SQLite guarantees that the second argument to
1649 ** xRealloc is always a value returned by a prior call to xRoundup.
1650 ** And so in cases where xRoundup always returns a positive number,
1651 ** xRealloc can perform exactly as the standard library realloc() and
1652 ** still be in compliance with this specification.
1653 **
1654 ** xSize should return the allocated size of a memory allocation
1655 ** previously obtained from xMalloc or xRealloc.  The allocated size
1656 ** is always at least as big as the requested size but may be larger.
1657 **
1658 ** The xRoundup method returns what would be the allocated size of
1659 ** a memory allocation given a particular requested size.  Most memory
1660 ** allocators round up memory allocations at least to the next multiple
1661 ** of 8.  Some allocators round up to a larger multiple or to a power of 2.
1662 ** Every memory allocation request coming in through [sqlite3_malloc()]
1663 ** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0, 
1664 ** that causes the corresponding memory allocation to fail.
1665 **
1666 ** The xInit method initializes the memory allocator.  (For example,
1667 ** it might allocate any require mutexes or initialize internal data
1668 ** structures.  The xShutdown method is invoked (indirectly) by
1669 ** [sqlite3_shutdown()] and should deallocate any resources acquired
1670 ** by xInit.  The pAppData pointer is used as the only parameter to
1671 ** xInit and xShutdown.
1672 **
1673 ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
1674 ** the xInit method, so the xInit method need not be threadsafe.  The
1675 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
1676 ** not need to be threadsafe either.  For all other methods, SQLite
1677 ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
1678 ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
1679 ** it is by default) and so the methods are automatically serialized.
1680 ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
1681 ** methods must be threadsafe or else make their own arrangements for
1682 ** serialization.
1683 **
1684 ** SQLite will never invoke xInit() more than once without an intervening
1685 ** call to xShutdown().
1686 */
1687 typedef struct sqlite3_mem_methods sqlite3_mem_methods;
1688 struct sqlite3_mem_methods {
1689   void *(*xMalloc)(int);         /* Memory allocation function */
1690   void (*xFree)(void*);          /* Free a prior allocation */
1691   void *(*xRealloc)(void*,int);  /* Resize an allocation */
1692   int (*xSize)(void*);           /* Return the size of an allocation */
1693   int (*xRoundup)(int);          /* Round up request size to allocation size */
1694   int (*xInit)(void*);           /* Initialize the memory allocator */
1695   void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
1696   void *pAppData;                /* Argument to xInit() and xShutdown() */
1697 };
1698
1699 /*
1700 ** CAPI3REF: Configuration Options
1701 **
1702 ** These constants are the available integer configuration options that
1703 ** can be passed as the first argument to the [sqlite3_config()] interface.
1704 **
1705 ** New configuration options may be added in future releases of SQLite.
1706 ** Existing configuration options might be discontinued.  Applications
1707 ** should check the return code from [sqlite3_config()] to make sure that
1708 ** the call worked.  The [sqlite3_config()] interface will return a
1709 ** non-zero [error code] if a discontinued or unsupported configuration option
1710 ** is invoked.
1711 **
1712 ** <dl>
1713 ** <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
1714 ** <dd>There are no arguments to this option.  ^This option sets the
1715 ** [threading mode] to Single-thread.  In other words, it disables
1716 ** all mutexing and puts SQLite into a mode where it can only be used
1717 ** by a single thread.   ^If SQLite is compiled with
1718 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1719 ** it is not possible to change the [threading mode] from its default
1720 ** value of Single-thread and so [sqlite3_config()] will return 
1721 ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
1722 ** configuration option.</dd>
1723 **
1724 ** <dt>SQLITE_CONFIG_MULTITHREAD</dt>
1725 ** <dd>There are no arguments to this option.  ^This option sets the
1726 ** [threading mode] to Multi-thread.  In other words, it disables
1727 ** mutexing on [database connection] and [prepared statement] objects.
1728 ** The application is responsible for serializing access to
1729 ** [database connections] and [prepared statements].  But other mutexes
1730 ** are enabled so that SQLite will be safe to use in a multi-threaded
1731 ** environment as long as no two threads attempt to use the same
1732 ** [database connection] at the same time.  ^If SQLite is compiled with
1733 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1734 ** it is not possible to set the Multi-thread [threading mode] and
1735 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1736 ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
1737 **
1738 ** <dt>SQLITE_CONFIG_SERIALIZED</dt>
1739 ** <dd>There are no arguments to this option.  ^This option sets the
1740 ** [threading mode] to Serialized. In other words, this option enables
1741 ** all mutexes including the recursive
1742 ** mutexes on [database connection] and [prepared statement] objects.
1743 ** In this mode (which is the default when SQLite is compiled with
1744 ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
1745 ** to [database connections] and [prepared statements] so that the
1746 ** application is free to use the same [database connection] or the
1747 ** same [prepared statement] in different threads at the same time.
1748 ** ^If SQLite is compiled with
1749 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1750 ** it is not possible to set the Serialized [threading mode] and
1751 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1752 ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
1753 **
1754 ** <dt>SQLITE_CONFIG_MALLOC</dt>
1755 ** <dd> ^(This option takes a single argument which is a pointer to an
1756 ** instance of the [sqlite3_mem_methods] structure.  The argument specifies
1757 ** alternative low-level memory allocation routines to be used in place of
1758 ** the memory allocation routines built into SQLite.)^ ^SQLite makes
1759 ** its own private copy of the content of the [sqlite3_mem_methods] structure
1760 ** before the [sqlite3_config()] call returns.</dd>
1761 **
1762 ** <dt>SQLITE_CONFIG_GETMALLOC</dt>
1763 ** <dd> ^(This option takes a single argument which is a pointer to an
1764 ** instance of the [sqlite3_mem_methods] structure.  The [sqlite3_mem_methods]
1765 ** structure is filled with the currently defined memory allocation routines.)^
1766 ** This option can be used to overload the default memory allocation
1767 ** routines with a wrapper that simulations memory allocation failure or
1768 ** tracks memory usage, for example. </dd>
1769 **
1770 ** <dt>SQLITE_CONFIG_MEMSTATUS</dt>
1771 ** <dd> ^This option takes single argument of type int, interpreted as a 
1772 ** boolean, which enables or disables the collection of memory allocation 
1773 ** statistics. ^(When memory allocation statistics are disabled, the 
1774 ** following SQLite interfaces become non-operational:
1775 **   <ul>
1776 **   <li> [sqlite3_memory_used()]
1777 **   <li> [sqlite3_memory_highwater()]
1778 **   <li> [sqlite3_soft_heap_limit()]
1779 **   <li> [sqlite3_status()]
1780 **   </ul>)^
1781 ** ^Memory allocation statistics are enabled by default unless SQLite is
1782 ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
1783 ** allocation statistics are disabled by default.
1784 ** </dd>
1785 **
1786 ** <dt>SQLITE_CONFIG_SCRATCH</dt>
1787 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
1788 ** scratch memory.  There are three arguments:  A pointer an 8-byte
1789 ** aligned memory buffer from which the scrach allocations will be
1790 ** drawn, the size of each scratch allocation (sz),
1791 ** and the maximum number of scratch allocations (N).  The sz
1792 ** argument must be a multiple of 16. The sz parameter should be a few bytes
1793 ** larger than the actual scratch space required due to internal overhead.
1794 ** The first argument must be a pointer to an 8-byte aligned buffer
1795 ** of at least sz*N bytes of memory.
1796 ** ^SQLite will use no more than one scratch buffer per thread.  So
1797 ** N should be set to the expected maximum number of threads.  ^SQLite will
1798 ** never require a scratch buffer that is more than 6 times the database
1799 ** page size. ^If SQLite needs needs additional scratch memory beyond 
1800 ** what is provided by this configuration option, then 
1801 ** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
1802 **
1803 ** <dt>SQLITE_CONFIG_PAGECACHE</dt>
1804 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
1805 ** the database page cache with the default page cache implemenation.  
1806 ** This configuration should not be used if an application-define page
1807 ** cache implementation is loaded using the SQLITE_CONFIG_PCACHE option.
1808 ** There are three arguments to this option: A pointer to 8-byte aligned
1809 ** memory, the size of each page buffer (sz), and the number of pages (N).
1810 ** The sz argument should be the size of the largest database page
1811 ** (a power of two between 512 and 32768) plus a little extra for each
1812 ** page header.  ^The page header size is 20 to 40 bytes depending on
1813 ** the host architecture.  ^It is harmless, apart from the wasted memory,
1814 ** to make sz a little too large.  The first
1815 ** argument should point to an allocation of at least sz*N bytes of memory.
1816 ** ^SQLite will use the memory provided by the first argument to satisfy its
1817 ** memory needs for the first N pages that it adds to cache.  ^If additional
1818 ** page cache memory is needed beyond what is provided by this option, then
1819 ** SQLite goes to [sqlite3_malloc()] for the additional storage space.
1820 ** ^The implementation might use one or more of the N buffers to hold 
1821 ** memory accounting information. The pointer in the first argument must
1822 ** be aligned to an 8-byte boundary or subsequent behavior of SQLite
1823 ** will be undefined.</dd>
1824 **
1825 ** <dt>SQLITE_CONFIG_HEAP</dt>
1826 ** <dd> ^This option specifies a static memory buffer that SQLite will use
1827 ** for all of its dynamic memory allocation needs beyond those provided
1828 ** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
1829 ** There are three arguments: An 8-byte aligned pointer to the memory,
1830 ** the number of bytes in the memory buffer, and the minimum allocation size.
1831 ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
1832 ** to using its default memory allocator (the system malloc() implementation),
1833 ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the
1834 ** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
1835 ** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
1836 ** allocator is engaged to handle all of SQLites memory allocation needs.
1837 ** The first pointer (the memory pointer) must be aligned to an 8-byte
1838 ** boundary or subsequent behavior of SQLite will be undefined.</dd>
1839 **
1840 ** <dt>SQLITE_CONFIG_MUTEX</dt>
1841 ** <dd> ^(This option takes a single argument which is a pointer to an
1842 ** instance of the [sqlite3_mutex_methods] structure.  The argument specifies
1843 ** alternative low-level mutex routines to be used in place
1844 ** the mutex routines built into SQLite.)^  ^SQLite makes a copy of the
1845 ** content of the [sqlite3_mutex_methods] structure before the call to
1846 ** [sqlite3_config()] returns. ^If SQLite is compiled with
1847 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1848 ** the entire mutexing subsystem is omitted from the build and hence calls to
1849 ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
1850 ** return [SQLITE_ERROR].</dd>
1851 **
1852 ** <dt>SQLITE_CONFIG_GETMUTEX</dt>
1853 ** <dd> ^(This option takes a single argument which is a pointer to an
1854 ** instance of the [sqlite3_mutex_methods] structure.  The
1855 ** [sqlite3_mutex_methods]
1856 ** structure is filled with the currently defined mutex routines.)^
1857 ** This option can be used to overload the default mutex allocation
1858 ** routines with a wrapper used to track mutex usage for performance
1859 ** profiling or testing, for example.   ^If SQLite is compiled with
1860 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1861 ** the entire mutexing subsystem is omitted from the build and hence calls to
1862 ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
1863 ** return [SQLITE_ERROR].</dd>
1864 **
1865 ** <dt>SQLITE_CONFIG_LOOKASIDE</dt>
1866 ** <dd> ^(This option takes two arguments that determine the default
1867 ** memory allocation for the lookaside memory allocator on each
1868 ** [database connection].  The first argument is the
1869 ** size of each lookaside buffer slot and the second is the number of
1870 ** slots allocated to each database connection.)^  ^(This option sets the
1871 ** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
1872 ** verb to [sqlite3_db_config()] can be used to change the lookaside
1873 ** configuration on individual connections.)^ </dd>
1874 **
1875 ** <dt>SQLITE_CONFIG_PCACHE</dt>
1876 ** <dd> ^(This option takes a single argument which is a pointer to
1877 ** an [sqlite3_pcache_methods] object.  This object specifies the interface
1878 ** to a custom page cache implementation.)^  ^SQLite makes a copy of the
1879 ** object and uses it for page cache memory allocations.</dd>
1880 **
1881 ** <dt>SQLITE_CONFIG_GETPCACHE</dt>
1882 ** <dd> ^(This option takes a single argument which is a pointer to an
1883 ** [sqlite3_pcache_methods] object.  SQLite copies of the current
1884 ** page cache implementation into that object.)^ </dd>
1885 **
1886 ** <dt>SQLITE_CONFIG_LOG</dt>
1887 ** <dd> ^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
1888 ** function with a call signature of void(*)(void*,int,const char*), 
1889 ** and a pointer to void. ^If the function pointer is not NULL, it is
1890 ** invoked by [sqlite3_log()] to process each logging event.  ^If the
1891 ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
1892 ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
1893 ** passed through as the first parameter to the application-defined logger
1894 ** function whenever that function is invoked.  ^The second parameter to
1895 ** the logger function is a copy of the first parameter to the corresponding
1896 ** [sqlite3_log()] call and is intended to be a [result code] or an
1897 ** [extended result code].  ^The third parameter passed to the logger is
1898 ** log message after formatting via [sqlite3_snprintf()].
1899 ** The SQLite logging interface is not reentrant; the logger function
1900 ** supplied by the application must not invoke any SQLite interface.
1901 ** In a multi-threaded application, the application-defined logger
1902 ** function must be threadsafe. </dd>
1903 **
1904 ** </dl>
1905 */
1906 #define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
1907 #define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
1908 #define SQLITE_CONFIG_SERIALIZED    3  /* nil */
1909 #define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
1910 #define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
1911 #define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */
1912 #define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
1913 #define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
1914 #define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
1915 #define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
1916 #define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
1917 /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ 
1918 #define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
1919 #define SQLITE_CONFIG_PCACHE       14  /* sqlite3_pcache_methods* */
1920 #define SQLITE_CONFIG_GETPCACHE    15  /* sqlite3_pcache_methods* */
1921 #define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
1922
1923 /*
1924 ** CAPI3REF: Database Connection Configuration Options
1925 **
1926 ** These constants are the available integer configuration options that
1927 ** can be passed as the second argument to the [sqlite3_db_config()] interface.
1928 **
1929 ** New configuration options may be added in future releases of SQLite.
1930 ** Existing configuration options might be discontinued.  Applications
1931 ** should check the return code from [sqlite3_db_config()] to make sure that
1932 ** the call worked.  ^The [sqlite3_db_config()] interface will return a
1933 ** non-zero [error code] if a discontinued or unsupported configuration option
1934 ** is invoked.
1935 **
1936 ** <dl>
1937 ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
1938 ** <dd> ^This option takes three additional arguments that determine the 
1939 ** [lookaside memory allocator] configuration for the [database connection].
1940 ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
1941 ** pointer to an memory buffer to use for lookaside memory.
1942 ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
1943 ** may be NULL in which case SQLite will allocate the
1944 ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
1945 ** size of each lookaside buffer slot.  ^The third argument is the number of
1946 ** slots.  The size of the buffer in the first argument must be greater than
1947 ** or equal to the product of the second and third arguments.  The buffer
1948 ** must be aligned to an 8-byte boundary.  ^If the second argument to
1949 ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
1950 ** rounded down to the next smaller
1951 ** multiple of 8.  See also: [SQLITE_CONFIG_LOOKASIDE]</dd>
1952 **
1953 ** </dl>
1954 */
1955 #define SQLITE_DBCONFIG_LOOKASIDE    1001  /* void* int int */
1956
1957
1958 /*
1959 ** CAPI3REF: Enable Or Disable Extended Result Codes
1960 **
1961 ** ^The sqlite3_extended_result_codes() routine enables or disables the
1962 ** [extended result codes] feature of SQLite. ^The extended result
1963 ** codes are disabled by default for historical compatibility.
1964 */
1965 SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
1966
1967 /*
1968 ** CAPI3REF: Last Insert Rowid
1969 **
1970 ** ^Each entry in an SQLite table has a unique 64-bit signed
1971 ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
1972 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
1973 ** names are not also used by explicitly declared columns. ^If
1974 ** the table has a column of type [INTEGER PRIMARY KEY] then that column
1975 ** is another alias for the rowid.
1976 **
1977 ** ^This routine returns the [rowid] of the most recent
1978 ** successful [INSERT] into the database from the [database connection]
1979 ** in the first argument.  ^If no successful [INSERT]s
1980 ** have ever occurred on that database connection, zero is returned.
1981 **
1982 ** ^(If an [INSERT] occurs within a trigger, then the [rowid] of the inserted
1983 ** row is returned by this routine as long as the trigger is running.
1984 ** But once the trigger terminates, the value returned by this routine
1985 ** reverts to the last value inserted before the trigger fired.)^
1986 **
1987 ** ^An [INSERT] that fails due to a constraint violation is not a
1988 ** successful [INSERT] and does not change the value returned by this
1989 ** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
1990 ** and INSERT OR ABORT make no changes to the return value of this
1991 ** routine when their insertion fails.  ^(When INSERT OR REPLACE
1992 ** encounters a constraint violation, it does not fail.  The
1993 ** INSERT continues to completion after deleting rows that caused
1994 ** the constraint problem so INSERT OR REPLACE will always change
1995 ** the return value of this interface.)^
1996 **
1997 ** ^For the purposes of this routine, an [INSERT] is considered to
1998 ** be successful even if it is subsequently rolled back.
1999 **
2000 ** This function is accessible to SQL statements via the
2001 ** [last_insert_rowid() SQL function].
2002 **
2003 ** If a separate thread performs a new [INSERT] on the same
2004 ** database connection while the [sqlite3_last_insert_rowid()]
2005 ** function is running and thus changes the last insert [rowid],
2006 ** then the value returned by [sqlite3_last_insert_rowid()] is
2007 ** unpredictable and might not equal either the old or the new
2008 ** last insert [rowid].
2009 */
2010 SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
2011
2012 /*
2013 ** CAPI3REF: Count The Number Of Rows Modified
2014 **
2015 ** ^This function returns the number of database rows that were changed
2016 ** or inserted or deleted by the most recently completed SQL statement
2017 ** on the [database connection] specified by the first parameter.
2018 ** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
2019 ** or [DELETE] statement are counted.  Auxiliary changes caused by
2020 ** triggers or [foreign key actions] are not counted.)^ Use the
2021 ** [sqlite3_total_changes()] function to find the total number of changes
2022 ** including changes caused by triggers and foreign key actions.
2023 **
2024 ** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
2025 ** are not counted.  Only real table changes are counted.
2026 **
2027 ** ^(A "row change" is a change to a single row of a single table
2028 ** caused by an INSERT, DELETE, or UPDATE statement.  Rows that
2029 ** are changed as side effects of [REPLACE] constraint resolution,
2030 ** rollback, ABORT processing, [DROP TABLE], or by any other
2031 ** mechanisms do not count as direct row changes.)^
2032 **
2033 ** A "trigger context" is a scope of execution that begins and
2034 ** ends with the script of a [CREATE TRIGGER | trigger]. 
2035 ** Most SQL statements are
2036 ** evaluated outside of any trigger.  This is the "top level"
2037 ** trigger context.  If a trigger fires from the top level, a
2038 ** new trigger context is entered for the duration of that one
2039 ** trigger.  Subtriggers create subcontexts for their duration.
2040 **
2041 ** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
2042 ** not create a new trigger context.
2043 **
2044 ** ^This function returns the number of direct row changes in the
2045 ** most recent INSERT, UPDATE, or DELETE statement within the same
2046 ** trigger context.
2047 **
2048 ** ^Thus, when called from the top level, this function returns the
2049 ** number of changes in the most recent INSERT, UPDATE, or DELETE
2050 ** that also occurred at the top level.  ^(Within the body of a trigger,
2051 ** the sqlite3_changes() interface can be called to find the number of
2052 ** changes in the most recently completed INSERT, UPDATE, or DELETE
2053 ** statement within the body of the same trigger.
2054 ** However, the number returned does not include changes
2055 ** caused by subtriggers since those have their own context.)^
2056 **
2057 ** See also the [sqlite3_total_changes()] interface, the
2058 ** [count_changes pragma], and the [changes() SQL function].
2059 **
2060 ** If a separate thread makes changes on the same database connection
2061 ** while [sqlite3_changes()] is running then the value returned
2062 ** is unpredictable and not meaningful.
2063 */
2064 SQLITE_API int sqlite3_changes(sqlite3*);
2065
2066 /*
2067 ** CAPI3REF: Total Number Of Rows Modified
2068 **
2069 ** ^This function returns the number of row changes caused by [INSERT],
2070 ** [UPDATE] or [DELETE] statements since the [database connection] was opened.
2071 ** ^(The count returned by sqlite3_total_changes() includes all changes
2072 ** from all [CREATE TRIGGER | trigger] contexts and changes made by
2073 ** [foreign key actions]. However,
2074 ** the count does not include changes used to implement [REPLACE] constraints,
2075 ** do rollbacks or ABORT processing, or [DROP TABLE] processing.  The
2076 ** count does not include rows of views that fire an [INSTEAD OF trigger],
2077 ** though if the INSTEAD OF trigger makes changes of its own, those changes 
2078 ** are counted.)^
2079 ** ^The sqlite3_total_changes() function counts the changes as soon as
2080 ** the statement that makes them is completed (when the statement handle
2081 ** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
2082 **
2083 ** See also the [sqlite3_changes()] interface, the
2084 ** [count_changes pragma], and the [total_changes() SQL function].
2085 **
2086 ** If a separate thread makes changes on the same database connection
2087 ** while [sqlite3_total_changes()] is running then the value
2088 ** returned is unpredictable and not meaningful.
2089 */
2090 SQLITE_API int sqlite3_total_changes(sqlite3*);
2091
2092 /*
2093 ** CAPI3REF: Interrupt A Long-Running Query
2094 **
2095 ** ^This function causes any pending database operation to abort and
2096 ** return at its earliest opportunity. This routine is typically
2097 ** called in response to a user action such as pressing "Cancel"
2098 ** or Ctrl-C where the user wants a long query operation to halt
2099 ** immediately.
2100 **
2101 ** ^It is safe to call this routine from a thread different from the
2102 ** thread that is currently running the database operation.  But it
2103 ** is not safe to call this routine with a [database connection] that
2104 ** is closed or might close before sqlite3_interrupt() returns.
2105 **
2106 ** ^If an SQL operation is very nearly finished at the time when
2107 ** sqlite3_interrupt() is called, then it might not have an opportunity
2108 ** to be interrupted and might continue to completion.
2109 **
2110 ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
2111 ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
2112 ** that is inside an explicit transaction, then the entire transaction
2113 ** will be rolled back automatically.
2114 **
2115 ** ^The sqlite3_interrupt(D) call is in effect until all currently running
2116 ** SQL statements on [database connection] D complete.  ^Any new SQL statements
2117 ** that are started after the sqlite3_interrupt() call and before the 
2118 ** running statements reaches zero are interrupted as if they had been
2119 ** running prior to the sqlite3_interrupt() call.  ^New SQL statements
2120 ** that are started after the running statement count reaches zero are
2121 ** not effected by the sqlite3_interrupt().
2122 ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
2123 ** SQL statements is a no-op and has no effect on SQL statements
2124 ** that are started after the sqlite3_interrupt() call returns.
2125 **
2126 ** If the database connection closes while [sqlite3_interrupt()]
2127 ** is running then bad things will likely happen.
2128 */
2129 SQLITE_API void sqlite3_interrupt(sqlite3*);
2130
2131 /*
2132 ** CAPI3REF: Determine If An SQL Statement Is Complete
2133 **
2134 ** These routines are useful during command-line input to determine if the
2135 ** currently entered text seems to form a complete SQL statement or
2136 ** if additional input is needed before sending the text into
2137 ** SQLite for parsing.  ^These routines return 1 if the input string
2138 ** appears to be a complete SQL statement.  ^A statement is judged to be
2139 ** complete if it ends with a semicolon token and is not a prefix of a
2140 ** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within
2141 ** string literals or quoted identifier names or comments are not
2142 ** independent tokens (they are part of the token in which they are
2143 ** embedded) and thus do not count as a statement terminator.  ^Whitespace
2144 ** and comments that follow the final semicolon are ignored.
2145 **
2146 ** ^These routines return 0 if the statement is incomplete.  ^If a
2147 ** memory allocation fails, then SQLITE_NOMEM is returned.
2148 **
2149 ** ^These routines do not parse the SQL statements thus
2150 ** will not detect syntactically incorrect SQL.
2151 **
2152 ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior 
2153 ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
2154 ** automatically by sqlite3_complete16().  If that initialization fails,
2155 ** then the return value from sqlite3_complete16() will be non-zero
2156 ** regardless of whether or not the input SQL is complete.)^
2157 **
2158 ** The input to [sqlite3_complete()] must be a zero-terminated
2159 ** UTF-8 string.
2160 **
2161 ** The input to [sqlite3_complete16()] must be a zero-terminated
2162 ** UTF-16 string in native byte order.
2163 */
2164 SQLITE_API int sqlite3_complete(const char *sql);
2165 SQLITE_API int sqlite3_complete16(const void *sql);
2166
2167 /*
2168 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
2169 **
2170 ** ^This routine sets a callback function that might be invoked whenever
2171 ** an attempt is made to open a database table that another thread
2172 ** or process has locked.
2173 **
2174 ** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
2175 ** is returned immediately upon encountering the lock.  ^If the busy callback
2176 ** is not NULL, then the callback might be invoked with two arguments.
2177 **
2178 ** ^The first argument to the busy handler is a copy of the void* pointer which
2179 ** is the third argument to sqlite3_busy_handler().  ^The second argument to
2180 ** the busy handler callback is the number of times that the busy handler has
2181 ** been invoked for this locking event.  ^If the
2182 ** busy callback returns 0, then no additional attempts are made to
2183 ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
2184 ** ^If the callback returns non-zero, then another attempt
2185 ** is made to open the database for reading and the cycle repeats.
2186 **
2187 ** The presence of a busy handler does not guarantee that it will be invoked
2188 ** when there is lock contention. ^If SQLite determines that invoking the busy
2189 ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
2190 ** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
2191 ** Consider a scenario where one process is holding a read lock that
2192 ** it is trying to promote to a reserved lock and
2193 ** a second process is holding a reserved lock that it is trying
2194 ** to promote to an exclusive lock.  The first process cannot proceed
2195 ** because it is blocked by the second and the second process cannot
2196 ** proceed because it is blocked by the first.  If both processes
2197 ** invoke the busy handlers, neither will make any progress.  Therefore,
2198 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
2199 ** will induce the first process to release its read lock and allow
2200 ** the second process to proceed.
2201 **
2202 ** ^The default busy callback is NULL.
2203 **
2204 ** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
2205 ** when SQLite is in the middle of a large transaction where all the
2206 ** changes will not fit into the in-memory cache.  SQLite will
2207 ** already hold a RESERVED lock on the database file, but it needs
2208 ** to promote this lock to EXCLUSIVE so that it can spill cache
2209 ** pages into the database file without harm to concurrent
2210 ** readers.  ^If it is unable to promote the lock, then the in-memory
2211 ** cache will be left in an inconsistent state and so the error
2212 ** code is promoted from the relatively benign [SQLITE_BUSY] to
2213 ** the more severe [SQLITE_IOERR_BLOCKED].  ^This error code promotion
2214 ** forces an automatic rollback of the changes.  See the
2215 ** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
2216 ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
2217 ** this is important.
2218 **
2219 ** ^(There can only be a single busy handler defined for each
2220 ** [database connection].  Setting a new busy handler clears any
2221 ** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]
2222 ** will also set or clear the busy handler.
2223 **
2224 ** The busy callback should not take any actions which modify the
2225 ** database connection that invoked the busy handler.  Any such actions
2226 ** result in undefined behavior.
2227 ** 
2228 ** A busy handler must not close the database connection
2229 ** or [prepared statement] that invoked the busy handler.
2230 */
2231 SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
2232
2233 /*
2234 ** CAPI3REF: Set A Busy Timeout
2235 **
2236 ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
2237 ** for a specified amount of time when a table is locked.  ^The handler
2238 ** will sleep multiple times until at least "ms" milliseconds of sleeping
2239 ** have accumulated.  ^After at least "ms" milliseconds of sleeping,
2240 ** the handler returns 0 which causes [sqlite3_step()] to return
2241 ** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
2242 **
2243 ** ^Calling this routine with an argument less than or equal to zero
2244 ** turns off all busy handlers.
2245 **
2246 ** ^(There can only be a single busy handler for a particular
2247 ** [database connection] any any given moment.  If another busy handler
2248 ** was defined  (using [sqlite3_busy_handler()]) prior to calling
2249 ** this routine, that other busy handler is cleared.)^
2250 */
2251 SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
2252
2253 /*
2254 ** CAPI3REF: Convenience Routines For Running Queries
2255 **
2256 ** Definition: A <b>result table</b> is memory data structure created by the
2257 ** [sqlite3_get_table()] interface.  A result table records the
2258 ** complete query results from one or more queries.
2259 **
2260 ** The table conceptually has a number of rows and columns.  But
2261 ** these numbers are not part of the result table itself.  These
2262 ** numbers are obtained separately.  Let N be the number of rows
2263 ** and M be the number of columns.
2264 **
2265 ** A result table is an array of pointers to zero-terminated UTF-8 strings.
2266 ** There are (N+1)*M elements in the array.  The first M pointers point
2267 ** to zero-terminated strings that  contain the names of the columns.
2268 ** The remaining entries all point to query results.  NULL values result
2269 ** in NULL pointers.  All other values are in their UTF-8 zero-terminated
2270 ** string representation as returned by [sqlite3_column_text()].
2271 **
2272 ** A result table might consist of one or more memory allocations.
2273 ** It is not safe to pass a result table directly to [sqlite3_free()].
2274 ** A result table should be deallocated using [sqlite3_free_table()].
2275 **
2276 ** As an example of the result table format, suppose a query result
2277 ** is as follows:
2278 **
2279 ** <blockquote><pre>
2280 **        Name        | Age
2281 **        -----------------------
2282 **        Alice       | 43
2283 **        Bob         | 28
2284 **        Cindy       | 21
2285 ** </pre></blockquote>
2286 **
2287 ** There are two column (M==2) and three rows (N==3).  Thus the
2288 ** result table has 8 entries.  Suppose the result table is stored
2289 ** in an array names azResult.  Then azResult holds this content:
2290 **
2291 ** <blockquote><pre>
2292 **        azResult&#91;0] = "Name";
2293 **        azResult&#91;1] = "Age";
2294 **        azResult&#91;2] = "Alice";
2295 **        azResult&#91;3] = "43";
2296 **        azResult&#91;4] = "Bob";
2297 **        azResult&#91;5] = "28";
2298 **        azResult&#91;6] = "Cindy";
2299 **        azResult&#91;7] = "21";
2300 ** </pre></blockquote>
2301 **
2302 ** ^The sqlite3_get_table() function evaluates one or more
2303 ** semicolon-separated SQL statements in the zero-terminated UTF-8
2304 ** string of its 2nd parameter and returns a result table to the
2305 ** pointer given in its 3rd parameter.
2306 **
2307 ** After the application has finished with the result from sqlite3_get_table(),
2308 ** it should pass the result table pointer to sqlite3_free_table() in order to
2309 ** release the memory that was malloced.  Because of the way the
2310 ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
2311 ** function must not try to call [sqlite3_free()] directly.  Only
2312 ** [sqlite3_free_table()] is able to release the memory properly and safely.
2313 **
2314 ** ^(The sqlite3_get_table() interface is implemented as a wrapper around
2315 ** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
2316 ** to any internal data structures of SQLite.  It uses only the public
2317 ** interface defined here.  As a consequence, errors that occur in the
2318 ** wrapper layer outside of the internal [sqlite3_exec()] call are not
2319 ** reflected in subsequent calls to [sqlite3_errcode()] or
2320 ** [sqlite3_errmsg()].)^
2321 */
2322 SQLITE_API int sqlite3_get_table(
2323   sqlite3 *db,          /* An open database */
2324   const char *zSql,     /* SQL to be evaluated */
2325   char ***pazResult,    /* Results of the query */
2326   int *pnRow,           /* Number of result rows written here */
2327   int *pnColumn,        /* Number of result columns written here */
2328   char **pzErrmsg       /* Error msg written here */
2329 );
2330 SQLITE_API void sqlite3_free_table(char **result);
2331
2332 /*
2333 ** CAPI3REF: Formatted String Printing Functions
2334 **
2335 ** These routines are work-alikes of the "printf()" family of functions
2336 ** from the standard C library.
2337 **
2338 ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
2339 ** results into memory obtained from [sqlite3_malloc()].
2340 ** The strings returned by these two routines should be
2341 ** released by [sqlite3_free()].  ^Both routines return a
2342 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
2343 ** memory to hold the resulting string.
2344 **
2345 ** ^(In sqlite3_snprintf() routine is similar to "snprintf()" from
2346 ** the standard C library.  The result is written into the
2347 ** buffer supplied as the second parameter whose size is given by
2348 ** the first parameter. Note that the order of the
2349 ** first two parameters is reversed from snprintf().)^  This is an
2350 ** historical accident that cannot be fixed without breaking
2351 ** backwards compatibility.  ^(Note also that sqlite3_snprintf()
2352 ** returns a pointer to its buffer instead of the number of
2353 ** characters actually written into the buffer.)^  We admit that
2354 ** the number of characters written would be a more useful return
2355 ** value but we cannot change the implementation of sqlite3_snprintf()
2356 ** now without breaking compatibility.
2357 **
2358 ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
2359 ** guarantees that the buffer is always zero-terminated.  ^The first
2360 ** parameter "n" is the total size of the buffer, including space for
2361 ** the zero terminator.  So the longest string that can be completely
2362 ** written will be n-1 characters.
2363 **
2364 ** These routines all implement some additional formatting
2365 ** options that are useful for constructing SQL statements.
2366 ** All of the usual printf() formatting options apply.  In addition, there
2367 ** is are "%q", "%Q", and "%z" options.
2368 **
2369 ** ^(The %q option works like %s in that it substitutes a null-terminated
2370 ** string from the argument list.  But %q also doubles every '\'' character.
2371 ** %q is designed for use inside a string literal.)^  By doubling each '\''
2372 ** character it escapes that character and allows it to be inserted into
2373 ** the string.
2374 **
2375 ** For example, assume the string variable zText contains text as follows:
2376 **
2377 ** <blockquote><pre>
2378 **  char *zText = "It's a happy day!";
2379 ** </pre></blockquote>
2380 **
2381 ** One can use this text in an SQL statement as follows:
2382 **
2383 ** <blockquote><pre>
2384 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
2385 **  sqlite3_exec(db, zSQL, 0, 0, 0);
2386 **  sqlite3_free(zSQL);
2387 ** </pre></blockquote>
2388 **
2389 ** Because the %q format string is used, the '\'' character in zText
2390 ** is escaped and the SQL generated is as follows:
2391 **
2392 ** <blockquote><pre>
2393 **  INSERT INTO table1 VALUES('It''s a happy day!')
2394 ** </pre></blockquote>
2395 **
2396 ** This is correct.  Had we used %s instead of %q, the generated SQL
2397 ** would have looked like this:
2398 **
2399 ** <blockquote><pre>
2400 **  INSERT INTO table1 VALUES('It's a happy day!');
2401 ** </pre></blockquote>
2402 **
2403 ** This second example is an SQL syntax error.  As a general rule you should
2404 ** always use %q instead of %s when inserting text into a string literal.
2405 **
2406 ** ^(The %Q option works like %q except it also adds single quotes around
2407 ** the outside of the total string.  Additionally, if the parameter in the
2408 ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
2409 ** single quotes).)^  So, for example, one could say:
2410 **
2411 ** <blockquote><pre>
2412 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
2413 **  sqlite3_exec(db, zSQL, 0, 0, 0);
2414 **  sqlite3_free(zSQL);
2415 ** </pre></blockquote>
2416 **
2417 ** The code above will render a correct SQL statement in the zSQL
2418 ** variable even if the zText variable is a NULL pointer.
2419 **
2420 ** ^(The "%z" formatting option works like "%s" but with the
2421 ** addition that after the string has been read and copied into
2422 ** the result, [sqlite3_free()] is called on the input string.)^
2423 */
2424 SQLITE_API char *sqlite3_mprintf(const char*,...);
2425 SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
2426 SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
2427
2428 /*
2429 ** CAPI3REF: Memory Allocation Subsystem
2430 **
2431 ** The SQLite core uses these three routines for all of its own
2432 ** internal memory allocation needs. "Core" in the previous sentence
2433 ** does not include operating-system specific VFS implementation.  The
2434 ** Windows VFS uses native malloc() and free() for some operations.
2435 **
2436 ** ^The sqlite3_malloc() routine returns a pointer to a block
2437 ** of memory at least N bytes in length, where N is the parameter.
2438 ** ^If sqlite3_malloc() is unable to obtain sufficient free
2439 ** memory, it returns a NULL pointer.  ^If the parameter N to
2440 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
2441 ** a NULL pointer.
2442 **
2443 ** ^Calling sqlite3_free() with a pointer previously returned
2444 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
2445 ** that it might be reused.  ^The sqlite3_free() routine is
2446 ** a no-op if is called with a NULL pointer.  Passing a NULL pointer
2447 ** to sqlite3_free() is harmless.  After being freed, memory
2448 ** should neither be read nor written.  Even reading previously freed
2449 ** memory might result in a segmentation fault or other severe error.
2450 ** Memory corruption, a segmentation fault, or other severe error
2451 ** might result if sqlite3_free() is called with a non-NULL pointer that
2452 ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
2453 **
2454 ** ^(The sqlite3_realloc() interface attempts to resize a
2455 ** prior memory allocation to be at least N bytes, where N is the
2456 ** second parameter.  The memory allocation to be resized is the first
2457 ** parameter.)^ ^ If the first parameter to sqlite3_realloc()
2458 ** is a NULL pointer then its behavior is identical to calling
2459 ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
2460 ** ^If the second parameter to sqlite3_realloc() is zero or
2461 ** negative then the behavior is exactly the same as calling
2462 ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
2463 ** ^sqlite3_realloc() returns a pointer to a memory allocation
2464 ** of at least N bytes in size or NULL if sufficient memory is unavailable.
2465 ** ^If M is the size of the prior allocation, then min(N,M) bytes
2466 ** of the prior allocation are copied into the beginning of buffer returned
2467 ** by sqlite3_realloc() and the prior allocation is freed.
2468 ** ^If sqlite3_realloc() returns NULL, then the prior allocation
2469 ** is not freed.
2470 **
2471 ** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
2472 ** is always aligned to at least an 8 byte boundary.
2473 **
2474 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2475 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
2476 ** implementation of these routines to be omitted.  That capability
2477 ** is no longer provided.  Only built-in memory allocators can be used.
2478 **
2479 ** The Windows OS interface layer calls
2480 ** the system malloc() and free() directly when converting
2481 ** filenames between the UTF-8 encoding used by SQLite
2482 ** and whatever filename encoding is used by the particular Windows
2483 ** installation.  Memory allocation errors are detected, but
2484 ** they are reported back as [SQLITE_CANTOPEN] or
2485 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
2486 **
2487 ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
2488 ** must be either NULL or else pointers obtained from a prior
2489 ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
2490 ** not yet been released.
2491 **
2492 ** The application must not read or write any part of
2493 ** a block of memory after it has been released using
2494 ** [sqlite3_free()] or [sqlite3_realloc()].
2495 */
2496 SQLITE_API void *sqlite3_malloc(int);
2497 SQLITE_API void *sqlite3_realloc(void*, int);
2498 SQLITE_API void sqlite3_free(void*);
2499
2500 /*
2501 ** CAPI3REF: Memory Allocator Statistics
2502 **
2503 ** SQLite provides these two interfaces for reporting on the status
2504 ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
2505 ** routines, which form the built-in memory allocation subsystem.
2506 **
2507 ** ^The [sqlite3_memory_used()] routine returns the number of bytes
2508 ** of memory currently outstanding (malloced but not freed).
2509 ** ^The [sqlite3_memory_highwater()] routine returns the maximum
2510 ** value of [sqlite3_memory_used()] since the high-water mark
2511 ** was last reset.  ^The values returned by [sqlite3_memory_used()] and
2512 ** [sqlite3_memory_highwater()] include any overhead
2513 ** added by SQLite in its implementation of [sqlite3_malloc()],
2514 ** but not overhead added by the any underlying system library
2515 ** routines that [sqlite3_malloc()] may call.
2516 **
2517 ** ^The memory high-water mark is reset to the current value of
2518 ** [sqlite3_memory_used()] if and only if the parameter to
2519 ** [sqlite3_memory_highwater()] is true.  ^The value returned
2520 ** by [sqlite3_memory_highwater(1)] is the high-water mark
2521 ** prior to the reset.
2522 */
2523 SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
2524 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
2525
2526 /*
2527 ** CAPI3REF: Pseudo-Random Number Generator
2528 **
2529 ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2530 ** select random [ROWID | ROWIDs] when inserting new records into a table that
2531 ** already uses the largest possible [ROWID].  The PRNG is also used for
2532 ** the build-in random() and randomblob() SQL functions.  This interface allows
2533 ** applications to access the same PRNG for other purposes.
2534 **
2535 ** ^A call to this routine stores N bytes of randomness into buffer P.
2536 **
2537 ** ^The first time this routine is invoked (either internally or by
2538 ** the application) the PRNG is seeded using randomness obtained
2539 ** from the xRandomness method of the default [sqlite3_vfs] object.
2540 ** ^On all subsequent invocations, the pseudo-randomness is generated
2541 ** internally and without recourse to the [sqlite3_vfs] xRandomness
2542 ** method.
2543 */
2544 SQLITE_API void sqlite3_randomness(int N, void *P);
2545
2546 /*
2547 ** CAPI3REF: Compile-Time Authorization Callbacks
2548 **
2549 ** ^This routine registers a authorizer callback with a particular
2550 ** [database connection], supplied in the first argument.
2551 ** ^The authorizer callback is invoked as SQL statements are being compiled
2552 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
2553 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  ^At various
2554 ** points during the compilation process, as logic is being created
2555 ** to perform various actions, the authorizer callback is invoked to
2556 ** see if those actions are allowed.  ^The authorizer callback should
2557 ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
2558 ** specific action but allow the SQL statement to continue to be
2559 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
2560 ** rejected with an error.  ^If the authorizer callback returns
2561 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
2562 ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
2563 ** the authorizer will fail with an error message.
2564 **
2565 ** When the callback returns [SQLITE_OK], that means the operation
2566 ** requested is ok.  ^When the callback returns [SQLITE_DENY], the
2567 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
2568 ** authorizer will fail with an error message explaining that
2569 ** access is denied. 
2570 **
2571 ** ^The first parameter to the authorizer callback is a copy of the third
2572 ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
2573 ** to the callback is an integer [SQLITE_COPY | action code] that specifies
2574 ** the particular action to be authorized. ^The third through sixth parameters
2575 ** to the callback are zero-terminated strings that contain additional
2576 ** details about the action to be authorized.
2577 **
2578 ** ^If the action code is [SQLITE_READ]
2579 ** and the callback returns [SQLITE_IGNORE] then the
2580 ** [prepared statement] statement is constructed to substitute
2581 ** a NULL value in place of the table column that would have
2582 ** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
2583 ** return can be used to deny an untrusted user access to individual
2584 ** columns of a table.
2585 ** ^If the action code is [SQLITE_DELETE] and the callback returns
2586 ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
2587 ** [truncate optimization] is disabled and all rows are deleted individually.
2588 **
2589 ** An authorizer is used when [sqlite3_prepare | preparing]
2590 ** SQL statements from an untrusted source, to ensure that the SQL statements
2591 ** do not try to access data they are not allowed to see, or that they do not
2592 ** try to execute malicious statements that damage the database.  For
2593 ** example, an application may allow a user to enter arbitrary
2594 ** SQL queries for evaluation by a database.  But the application does
2595 ** not want the user to be able to make arbitrary changes to the
2596 ** database.  An authorizer could then be put in place while the
2597 ** user-entered SQL is being [sqlite3_prepare | prepared] that
2598 ** disallows everything except [SELECT] statements.
2599 **
2600 ** Applications that need to process SQL from untrusted sources
2601 ** might also consider lowering resource limits using [sqlite3_limit()]
2602 ** and limiting database size using the [max_page_count] [PRAGMA]
2603 ** in addition to using an authorizer.
2604 **
2605 ** ^(Only a single authorizer can be in place on a database connection
2606 ** at a time.  Each call to sqlite3_set_authorizer overrides the
2607 ** previous call.)^  ^Disable the authorizer by installing a NULL callback.
2608 ** The authorizer is disabled by default.
2609 **
2610 ** The authorizer callback must not do anything that will modify
2611 ** the database connection that invoked the authorizer callback.
2612 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2613 ** database connections for the meaning of "modify" in this paragraph.
2614 **
2615 ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
2616 ** statement might be re-prepared during [sqlite3_step()] due to a 
2617 ** schema change.  Hence, the application should ensure that the
2618 ** correct authorizer callback remains in place during the [sqlite3_step()].
2619 **
2620 ** ^Note that the authorizer callback is invoked only during
2621 ** [sqlite3_prepare()] or its variants.  Authorization is not
2622 ** performed during statement evaluation in [sqlite3_step()], unless
2623 ** as stated in the previous paragraph, sqlite3_step() invokes
2624 ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
2625 */
2626 SQLITE_API int sqlite3_set_authorizer(
2627   sqlite3*,
2628   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
2629   void *pUserData
2630 );
2631
2632 /*
2633 ** CAPI3REF: Authorizer Return Codes
2634 **
2635 ** The [sqlite3_set_authorizer | authorizer callback function] must
2636 ** return either [SQLITE_OK] or one of these two constants in order
2637 ** to signal SQLite whether or not the action is permitted.  See the
2638 ** [sqlite3_set_authorizer | authorizer documentation] for additional
2639 ** information.
2640 */
2641 #define SQLITE_DENY   1   /* Abort the SQL statement with an error */
2642 #define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
2643
2644 /*
2645 ** CAPI3REF: Authorizer Action Codes
2646 **
2647 ** The [sqlite3_set_authorizer()] interface registers a callback function
2648 ** that is invoked to authorize certain SQL statement actions.  The
2649 ** second parameter to the callback is an integer code that specifies
2650 ** what action is being authorized.  These are the integer action codes that
2651 ** the authorizer callback may be passed.
2652 **
2653 ** These action code values signify what kind of operation is to be
2654 ** authorized.  The 3rd and 4th parameters to the authorization
2655 ** callback function will be parameters or NULL depending on which of these
2656 ** codes is used as the second parameter.  ^(The 5th parameter to the
2657 ** authorizer callback is the name of the database ("main", "temp",
2658 ** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback
2659 ** is the name of the inner-most trigger or view that is responsible for
2660 ** the access attempt or NULL if this access attempt is directly from
2661 ** top-level SQL code.
2662 */
2663 /******************************************* 3rd ************ 4th ***********/
2664 #define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
2665 #define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
2666 #define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
2667 #define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
2668 #define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
2669 #define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
2670 #define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
2671 #define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
2672 #define SQLITE_DELETE                9   /* Table Name      NULL            */
2673 #define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
2674 #define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
2675 #define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
2676 #define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
2677 #define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
2678 #define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
2679 #define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
2680 #define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
2681 #define SQLITE_INSERT               18   /* Table Name      NULL            */
2682 #define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
2683 #define SQLITE_READ                 20   /* Table Name      Column Name     */
2684 #define SQLITE_SELECT               21   /* NULL            NULL            */
2685 #define SQLITE_TRANSACTION          22   /* Operation       NULL            */
2686 #define SQLITE_UPDATE               23   /* Table Name      Column Name     */
2687 #define SQLITE_ATTACH               24   /* Filename        NULL            */
2688 #define SQLITE_DETACH               25   /* Database Name   NULL            */
2689 #define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
2690 #define SQLITE_REINDEX              27   /* Index Name      NULL            */
2691 #define SQLITE_ANALYZE              28   /* Table Name      NULL            */
2692 #define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
2693 #define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
2694 #define SQLITE_FUNCTION             31   /* NULL            Function Name   */
2695 #define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */
2696 #define SQLITE_COPY                  0   /* No longer used */
2697
2698 /*
2699 ** CAPI3REF: Tracing And Profiling Functions
2700 **
2701 ** These routines register callback functions that can be used for
2702 ** tracing and profiling the execution of SQL statements.
2703 **
2704 ** ^The callback function registered by sqlite3_trace() is invoked at
2705 ** various times when an SQL statement is being run by [sqlite3_step()].
2706 ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
2707 ** SQL statement text as the statement first begins executing.
2708 ** ^(Additional sqlite3_trace() callbacks might occur
2709 ** as each triggered subprogram is entered.  The callbacks for triggers
2710 ** contain a UTF-8 SQL comment that identifies the trigger.)^
2711 **
2712 ** ^The callback function registered by sqlite3_profile() is invoked
2713 ** as each SQL statement finishes.  ^The profile callback contains
2714 ** the original statement text and an estimate of wall-clock time
2715 ** of how long that statement took to run.
2716 */
2717 SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
2718 SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
2719    void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
2720
2721 /*
2722 ** CAPI3REF: Query Progress Callbacks
2723 **
2724 ** ^This routine configures a callback function - the
2725 ** progress callback - that is invoked periodically during long
2726 ** running calls to [sqlite3_exec()], [sqlite3_step()] and
2727 ** [sqlite3_get_table()].  An example use for this
2728 ** interface is to keep a GUI updated during a large query.
2729 **
2730 ** ^If the progress callback returns non-zero, the operation is
2731 ** interrupted.  This feature can be used to implement a
2732 ** "Cancel" button on a GUI progress dialog box.
2733 **
2734 ** The progress handler must not do anything that will modify
2735 ** the database connection that invoked the progress handler.
2736 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2737 ** database connections for the meaning of "modify" in this paragraph.
2738 **
2739 */
2740 SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
2741
2742 /*
2743 ** CAPI3REF: Opening A New Database Connection
2744 **
2745 ** ^These routines open an SQLite database file whose name is given by the
2746 ** filename argument. ^The filename argument is interpreted as UTF-8 for
2747 ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
2748 ** order for sqlite3_open16(). ^(A [database connection] handle is usually
2749 ** returned in *ppDb, even if an error occurs.  The only exception is that
2750 ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
2751 ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
2752 ** object.)^ ^(If the database is opened (and/or created) successfully, then
2753 ** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The
2754 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
2755 ** an English language description of the error following a failure of any
2756 ** of the sqlite3_open() routines.
2757 **
2758 ** ^The default encoding for the database will be UTF-8 if
2759 ** sqlite3_open() or sqlite3_open_v2() is called and
2760 ** UTF-16 in the native byte order if sqlite3_open16() is used.
2761 **
2762 ** Whether or not an error occurs when it is opened, resources
2763 ** associated with the [database connection] handle should be released by
2764 ** passing it to [sqlite3_close()] when it is no longer required.
2765 **
2766 ** The sqlite3_open_v2() interface works like sqlite3_open()
2767 ** except that it accepts two additional parameters for additional control
2768 ** over the new database connection.  ^(The flags parameter to
2769 ** sqlite3_open_v2() can take one of
2770 ** the following three values, optionally combined with the 
2771 ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
2772 ** and/or [SQLITE_OPEN_PRIVATECACHE] flags:)^
2773 **
2774 ** <dl>
2775 ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
2776 ** <dd>The database is opened in read-only mode.  If the database does not
2777 ** already exist, an error is returned.</dd>)^
2778 **
2779 ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
2780 ** <dd>The database is opened for reading and writing if possible, or reading
2781 ** only if the file is write protected by the operating system.  In either
2782 ** case the database must already exist, otherwise an error is returned.</dd>)^
2783 **
2784 ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
2785 ** <dd>The database is opened for reading and writing, and is creates it if
2786 ** it does not already exist. This is the behavior that is always used for
2787 ** sqlite3_open() and sqlite3_open16().</dd>)^
2788 ** </dl>
2789 **
2790 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
2791 ** combinations shown above or one of the combinations shown above combined
2792 ** with the [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX],
2793 ** [SQLITE_OPEN_SHAREDCACHE] and/or [SQLITE_OPEN_SHAREDCACHE] flags,
2794 ** then the behavior is undefined.
2795 **
2796 ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
2797 ** opens in the multi-thread [threading mode] as long as the single-thread
2798 ** mode has not been set at compile-time or start-time.  ^If the
2799 ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
2800 ** in the serialized [threading mode] unless single-thread was
2801 ** previously selected at compile-time or start-time.
2802 ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
2803 ** eligible to use [shared cache mode], regardless of whether or not shared
2804 ** cache is enabled using [sqlite3_enable_shared_cache()].  ^The
2805 ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
2806 ** participate in [shared cache mode] even if it is enabled.
2807 **
2808 ** ^If the filename is ":memory:", then a private, temporary in-memory database
2809 ** is created for the connection.  ^This in-memory database will vanish when
2810 ** the database connection is closed.  Future versions of SQLite might
2811 ** make use of additional special filenames that begin with the ":" character.
2812 ** It is recommended that when a database filename actually does begin with
2813 ** a ":" character you should prefix the filename with a pathname such as
2814 ** "./" to avoid ambiguity.
2815 **
2816 ** ^If the filename is an empty string, then a private, temporary
2817 ** on-disk database will be created.  ^This private database will be
2818 ** automatically deleted as soon as the database connection is closed.
2819 **
2820 ** ^The fourth parameter to sqlite3_open_v2() is the name of the
2821 ** [sqlite3_vfs] object that defines the operating system interface that
2822 ** the new database connection should use.  ^If the fourth parameter is
2823 ** a NULL pointer then the default [sqlite3_vfs] object is used.
2824 **
2825 ** <b>Note to Windows users:</b>  The encoding used for the filename argument
2826 ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
2827 ** codepage is currently defined.  Filenames containing international
2828 ** characters must be converted to UTF-8 prior to passing them into
2829 ** sqlite3_open() or sqlite3_open_v2().
2830 */
2831 SQLITE_API int sqlite3_open(
2832   const char *filename,   /* Database filename (UTF-8) */
2833   sqlite3 **ppDb          /* OUT: SQLite db handle */
2834 );
2835 SQLITE_API int sqlite3_open16(
2836   const void *filename,   /* Database filename (UTF-16) */
2837   sqlite3 **ppDb          /* OUT: SQLite db handle */
2838 );
2839 SQLITE_API int sqlite3_open_v2(
2840   const char *filename,   /* Database filename (UTF-8) */
2841   sqlite3 **ppDb,         /* OUT: SQLite db handle */
2842   int flags,              /* Flags */
2843   const char *zVfs        /* Name of VFS module to use */
2844 );
2845
2846 /*
2847 ** CAPI3REF: Error Codes And Messages
2848 **
2849 ** ^The sqlite3_errcode() interface returns the numeric [result code] or
2850 ** [extended result code] for the most recent failed sqlite3_* API call
2851 ** associated with a [database connection]. If a prior API call failed
2852 ** but the most recent API call succeeded, the return value from
2853 ** sqlite3_errcode() is undefined.  ^The sqlite3_extended_errcode()
2854 ** interface is the same except that it always returns the 
2855 ** [extended result code] even when extended result codes are
2856 ** disabled.
2857 **
2858 ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
2859 ** text that describes the error, as either UTF-8 or UTF-16 respectively.
2860 ** ^(Memory to hold the error message string is managed internally.
2861 ** The application does not need to worry about freeing the result.
2862 ** However, the error string might be overwritten or deallocated by
2863 ** subsequent calls to other SQLite interface functions.)^
2864 **
2865 ** When the serialized [threading mode] is in use, it might be the
2866 ** case that a second error occurs on a separate thread in between
2867 ** the time of the first error and the call to these interfaces.
2868 ** When that happens, the second error will be reported since these
2869 ** interfaces always report the most recent result.  To avoid
2870 ** this, each thread can obtain exclusive use of the [database connection] D
2871 ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
2872 ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
2873 ** all calls to the interfaces listed here are completed.
2874 **
2875 ** If an interface fails with SQLITE_MISUSE, that means the interface
2876 ** was invoked incorrectly by the application.  In that case, the
2877 ** error code and message may or may not be set.
2878 */
2879 SQLITE_API int sqlite3_errcode(sqlite3 *db);
2880 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
2881 SQLITE_API const char *sqlite3_errmsg(sqlite3*);
2882 SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
2883
2884 /*
2885 ** CAPI3REF: SQL Statement Object
2886 ** KEYWORDS: {prepared statement} {prepared statements}
2887 **
2888 ** An instance of this object represents a single SQL statement.
2889 ** This object is variously known as a "prepared statement" or a
2890 ** "compiled SQL statement" or simply as a "statement".
2891 **
2892 ** The life of a statement object goes something like this:
2893 **
2894 ** <ol>
2895 ** <li> Create the object using [sqlite3_prepare_v2()] or a related
2896 **      function.
2897 ** <li> Bind values to [host parameters] using the sqlite3_bind_*()
2898 **      interfaces.
2899 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
2900 ** <li> Reset the statement using [sqlite3_reset()] then go back
2901 **      to step 2.  Do this zero or more times.
2902 ** <li> Destroy the object using [sqlite3_finalize()].
2903 ** </ol>
2904 **
2905 ** Refer to documentation on individual methods above for additional
2906 ** information.
2907 */
2908 typedef struct sqlite3_stmt sqlite3_stmt;
2909
2910 /*
2911 ** CAPI3REF: Run-time Limits
2912 **
2913 ** ^(This interface allows the size of various constructs to be limited
2914 ** on a connection by connection basis.  The first parameter is the
2915 ** [database connection] whose limit is to be set or queried.  The
2916 ** second parameter is one of the [limit categories] that define a
2917 ** class of constructs to be size limited.  The third parameter is the
2918 ** new limit for that construct.  The function returns the old limit.)^
2919 **
2920 ** ^If the new limit is a negative number, the limit is unchanged.
2921 ** ^(For the limit category of SQLITE_LIMIT_XYZ there is a 
2922 ** [limits | hard upper bound]
2923 ** set by a compile-time C preprocessor macro named 
2924 ** [limits | SQLITE_MAX_XYZ].
2925 ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
2926 ** ^Attempts to increase a limit above its hard upper bound are
2927 ** silently truncated to the hard upper bound.
2928 **
2929 ** Run-time limits are intended for use in applications that manage
2930 ** both their own internal database and also databases that are controlled
2931 ** by untrusted external sources.  An example application might be a
2932 ** web browser that has its own databases for storing history and
2933 ** separate databases controlled by JavaScript applications downloaded
2934 ** off the Internet.  The internal databases can be given the
2935 ** large, default limits.  Databases managed by external sources can
2936 ** be given much smaller limits designed to prevent a denial of service
2937 ** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
2938 ** interface to further control untrusted SQL.  The size of the database
2939 ** created by an untrusted script can be contained using the
2940 ** [max_page_count] [PRAGMA].
2941 **
2942 ** New run-time limit categories may be added in future releases.
2943 */
2944 SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
2945
2946 /*
2947 ** CAPI3REF: Run-Time Limit Categories
2948 ** KEYWORDS: {limit category} {*limit categories}
2949 **
2950 ** These constants define various performance limits
2951 ** that can be lowered at run-time using [sqlite3_limit()].
2952 ** The synopsis of the meanings of the various limits is shown below.
2953 ** Additional information is available at [limits | Limits in SQLite].
2954 **
2955 ** <dl>
2956 ** ^(<dt>SQLITE_LIMIT_LENGTH</dt>
2957 ** <dd>The maximum size of any string or BLOB or table row.<dd>)^
2958 **
2959 ** ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
2960 ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
2961 **
2962 ** ^(<dt>SQLITE_LIMIT_COLUMN</dt>
2963 ** <dd>The maximum number of columns in a table definition or in the
2964 ** result set of a [SELECT] or the maximum number of columns in an index
2965 ** or in an ORDER BY or GROUP BY clause.</dd>)^
2966 **
2967 ** ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
2968 ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
2969 **
2970 ** ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
2971 ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
2972 **
2973 ** ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
2974 ** <dd>The maximum number of instructions in a virtual machine program
2975 ** used to implement an SQL statement.</dd>)^
2976 **
2977 ** ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
2978 ** <dd>The maximum number of arguments on a function.</dd>)^
2979 **
2980 ** ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
2981 ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
2982 **
2983 ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
2984 ** <dd>The maximum length of the pattern argument to the [LIKE] or
2985 ** [GLOB] operators.</dd>)^
2986 **
2987 ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
2988 ** <dd>The maximum number of variables in an SQL statement that can
2989 ** be bound.</dd>)^
2990 **
2991 ** ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
2992 ** <dd>The maximum depth of recursion for triggers.</dd>)^
2993 ** </dl>
2994 */
2995 #define SQLITE_LIMIT_LENGTH                    0
2996 #define SQLITE_LIMIT_SQL_LENGTH                1
2997 #define SQLITE_LIMIT_COLUMN                    2
2998 #define SQLITE_LIMIT_EXPR_DEPTH                3
2999 #define SQLITE_LIMIT_COMPOUND_SELECT           4
3000 #define SQLITE_LIMIT_VDBE_OP                   5
3001 #define SQLITE_LIMIT_FUNCTION_ARG              6
3002 #define SQLITE_LIMIT_ATTACHED                  7
3003 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
3004 #define SQLITE_LIMIT_VARIABLE_NUMBER           9
3005 #define SQLITE_LIMIT_TRIGGER_DEPTH            10
3006
3007 /*
3008 ** CAPI3REF: Compiling An SQL Statement
3009 ** KEYWORDS: {SQL statement compiler}
3010 **
3011 ** To execute an SQL query, it must first be compiled into a byte-code
3012 ** program using one of these routines.
3013 **
3014 ** The first argument, "db", is a [database connection] obtained from a
3015 ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
3016 ** [sqlite3_open16()].  The database connection must not have been closed.
3017 **
3018 ** The second argument, "zSql", is the statement to be compiled, encoded
3019 ** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
3020 ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
3021 ** use UTF-16.
3022 **
3023 ** ^If the nByte argument is less than zero, then zSql is read up to the
3024 ** first zero terminator. ^If nByte is non-negative, then it is the maximum
3025 ** number of  bytes read from zSql.  ^When nByte is non-negative, the
3026 ** zSql string ends at either the first '\000' or '\u0000' character or
3027 ** the nByte-th byte, whichever comes first. If the caller knows
3028 ** that the supplied string is nul-terminated, then there is a small
3029 ** performance advantage to be gained by passing an nByte parameter that
3030 ** is equal to the number of bytes in the input string <i>including</i>
3031 ** the nul-terminator bytes.
3032 **
3033 ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
3034 ** past the end of the first SQL statement in zSql.  These routines only
3035 ** compile the first statement in zSql, so *pzTail is left pointing to
3036 ** what remains uncompiled.
3037 **
3038 ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
3039 ** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set
3040 ** to NULL.  ^If the input text contains no SQL (if the input is an empty
3041 ** string or a comment) then *ppStmt is set to NULL.
3042 ** The calling procedure is responsible for deleting the compiled
3043 ** SQL statement using [sqlite3_finalize()] after it has finished with it.
3044 ** ppStmt may not be NULL.
3045 **
3046 ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
3047 ** otherwise an [error code] is returned.
3048 **
3049 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
3050 ** recommended for all new programs. The two older interfaces are retained
3051 ** for backwards compatibility, but their use is discouraged.
3052 ** ^In the "v2" interfaces, the prepared statement
3053 ** that is returned (the [sqlite3_stmt] object) contains a copy of the
3054 ** original SQL text. This causes the [sqlite3_step()] interface to
3055 ** behave differently in three ways:
3056 **
3057 ** <ol>
3058 ** <li>
3059 ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
3060 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
3061 ** statement and try to run it again.  ^If the schema has changed in
3062 ** a way that makes the statement no longer valid, [sqlite3_step()] will still
3063 ** return [SQLITE_SCHEMA].  But unlike the legacy behavior, [SQLITE_SCHEMA] is
3064 ** now a fatal error.  Calling [sqlite3_prepare_v2()] again will not make the
3065 ** error go away.  Note: use [sqlite3_errmsg()] to find the text
3066 ** of the parsing error that results in an [SQLITE_SCHEMA] return.
3067 ** </li>
3068 **
3069 ** <li>
3070 ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
3071 ** [error codes] or [extended error codes].  ^The legacy behavior was that
3072 ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
3073 ** and the application would have to make a second call to [sqlite3_reset()]
3074 ** in order to find the underlying cause of the problem. With the "v2" prepare
3075 ** interfaces, the underlying reason for the error is returned immediately.
3076 ** </li>
3077 **
3078 ** <li>
3079 ** ^If the value of a [parameter | host parameter] in the WHERE clause might
3080 ** change the query plan for a statement, then the statement may be
3081 ** automatically recompiled (as if there had been a schema change) on the first 
3082 ** [sqlite3_step()] call following any change to the 
3083 ** [sqlite3_bind_text | bindings] of the [parameter]. 
3084 ** </li>
3085 ** </ol>
3086 */
3087 SQLITE_API int sqlite3_prepare(
3088   sqlite3 *db,            /* Database handle */
3089   const char *zSql,       /* SQL statement, UTF-8 encoded */
3090   int nByte,              /* Maximum length of zSql in bytes. */
3091   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3092   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3093 );
3094 SQLITE_API int sqlite3_prepare_v2(
3095   sqlite3 *db,            /* Database handle */
3096   const char *zSql,       /* SQL statement, UTF-8 encoded */
3097   int nByte,              /* Maximum length of zSql in bytes. */
3098   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3099   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3100 );
3101 SQLITE_API int sqlite3_prepare16(
3102   sqlite3 *db,            /* Database handle */
3103   const void *zSql,       /* SQL statement, UTF-16 encoded */
3104   int nByte,              /* Maximum length of zSql in bytes. */
3105   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3106   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3107 );
3108 SQLITE_API int sqlite3_prepare16_v2(
3109   sqlite3 *db,            /* Database handle */
3110   const void *zSql,       /* SQL statement, UTF-16 encoded */
3111   int nByte,              /* Maximum length of zSql in bytes. */
3112   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3113   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3114 );
3115
3116 /*
3117 ** CAPI3REF: Retrieving Statement SQL
3118 **
3119 ** ^This interface can be used to retrieve a saved copy of the original
3120 ** SQL text used to create a [prepared statement] if that statement was
3121 ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
3122 */
3123 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
3124
3125 /*
3126 ** CAPI3REF: Dynamically Typed Value Object
3127 ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
3128 **
3129 ** SQLite uses the sqlite3_value object to represent all values
3130 ** that can be stored in a database table. SQLite uses dynamic typing
3131 ** for the values it stores.  ^Values stored in sqlite3_value objects
3132 ** can be integers, floating point values, strings, BLOBs, or NULL.
3133 **
3134 ** An sqlite3_value object may be either "protected" or "unprotected".
3135 ** Some interfaces require a protected sqlite3_value.  Other interfaces
3136 ** will accept either a protected or an unprotected sqlite3_value.
3137 ** Every interface that accepts sqlite3_value arguments specifies
3138 ** whether or not it requires a protected sqlite3_value.
3139 **
3140 ** The terms "protected" and "unprotected" refer to whether or not
3141 ** a mutex is held.  A internal mutex is held for a protected
3142 ** sqlite3_value object but no mutex is held for an unprotected
3143 ** sqlite3_value object.  If SQLite is compiled to be single-threaded
3144 ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
3145 ** or if SQLite is run in one of reduced mutex modes 
3146 ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
3147 ** then there is no distinction between protected and unprotected
3148 ** sqlite3_value objects and they can be used interchangeably.  However,
3149 ** for maximum code portability it is recommended that applications
3150 ** still make the distinction between between protected and unprotected
3151 ** sqlite3_value objects even when not strictly required.
3152 **
3153 ** ^The sqlite3_value objects that are passed as parameters into the
3154 ** implementation of [application-defined SQL functions] are protected.
3155 ** ^The sqlite3_value object returned by
3156 ** [sqlite3_column_value()] is unprotected.
3157 ** Unprotected sqlite3_value objects may only be used with
3158 ** [sqlite3_result_value()] and [sqlite3_bind_value()].
3159 ** The [sqlite3_value_blob | sqlite3_value_type()] family of
3160 ** interfaces require protected sqlite3_value objects.
3161 */
3162 typedef struct Mem sqlite3_value;
3163
3164 /*
3165 ** CAPI3REF: SQL Function Context Object
3166 **
3167 ** The context in which an SQL function executes is stored in an
3168 ** sqlite3_context object.  ^A pointer to an sqlite3_context object
3169 ** is always first parameter to [application-defined SQL functions].
3170 ** The application-defined SQL function implementation will pass this
3171 ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
3172 ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
3173 ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
3174 ** and/or [sqlite3_set_auxdata()].
3175 */
3176 typedef struct sqlite3_context sqlite3_context;
3177
3178 /*
3179 ** CAPI3REF: Binding Values To Prepared Statements
3180 ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
3181 ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
3182 **
3183 ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
3184 ** literals may be replaced by a [parameter] that matches one of following
3185 ** templates:
3186 **
3187 ** <ul>
3188 ** <li>  ?
3189 ** <li>  ?NNN
3190 ** <li>  :VVV
3191 ** <li>  @VVV
3192 ** <li>  $VVV
3193 ** </ul>
3194 **
3195 ** In the templates above, NNN represents an integer literal,
3196 ** and VVV represents an alphanumeric identifer.)^  ^The values of these
3197 ** parameters (also called "host parameter names" or "SQL parameters")
3198 ** can be set using the sqlite3_bind_*() routines defined here.
3199 **
3200 ** ^The first argument to the sqlite3_bind_*() routines is always
3201 ** a pointer to the [sqlite3_stmt] object returned from
3202 ** [sqlite3_prepare_v2()] or its variants.
3203 **
3204 ** ^The second argument is the index of the SQL parameter to be set.
3205 ** ^The leftmost SQL parameter has an index of 1.  ^When the same named
3206 ** SQL parameter is used more than once, second and subsequent
3207 ** occurrences have the same index as the first occurrence.
3208 ** ^The index for named parameters can be looked up using the
3209 ** [sqlite3_bind_parameter_index()] API if desired.  ^The index
3210 ** for "?NNN" parameters is the value of NNN.
3211 ** ^The NNN value must be between 1 and the [sqlite3_limit()]
3212 ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
3213 **
3214 ** ^The third argument is the value to bind to the parameter.
3215 **
3216 ** ^(In those routines that have a fourth argument, its value is the
3217 ** number of bytes in the parameter.  To be clear: the value is the
3218 ** number of <u>bytes</u> in the value, not the number of characters.)^
3219 ** ^If the fourth parameter is negative, the length of the string is
3220 ** the number of bytes up to the first zero terminator.
3221 **
3222 ** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
3223 ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
3224 ** string after SQLite has finished with it. ^If the fifth argument is
3225 ** the special value [SQLITE_STATIC], then SQLite assumes that the
3226 ** information is in static, unmanaged space and does not need to be freed.
3227 ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
3228 ** SQLite makes its own private copy of the data immediately, before
3229 ** the sqlite3_bind_*() routine returns.
3230 **
3231 ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
3232 ** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory
3233 ** (just an integer to hold its size) while it is being processed.
3234 ** Zeroblobs are intended to serve as placeholders for BLOBs whose
3235 ** content is later written using
3236 ** [sqlite3_blob_open | incremental BLOB I/O] routines.
3237 ** ^A negative value for the zeroblob results in a zero-length BLOB.
3238 **
3239 ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
3240 ** for the [prepared statement] or with a prepared statement for which
3241 ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
3242 ** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()
3243 ** routine is passed a [prepared statement] that has been finalized, the
3244 ** result is undefined and probably harmful.
3245 **
3246 ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
3247 ** ^Unbound parameters are interpreted as NULL.
3248 **
3249 ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
3250 ** [error code] if anything goes wrong.
3251 ** ^[SQLITE_RANGE] is returned if the parameter
3252 ** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.
3253 **
3254 ** See also: [sqlite3_bind_parameter_count()],
3255 ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
3256 */
3257 SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
3258 SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
3259 SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
3260 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
3261 SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
3262 SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
3263 SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
3264 SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
3265 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
3266
3267 /*
3268 ** CAPI3REF: Number Of SQL Parameters
3269 **
3270 ** ^This routine can be used to find the number of [SQL parameters]
3271 ** in a [prepared statement].  SQL parameters are tokens of the
3272 ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
3273 ** placeholders for values that are [sqlite3_bind_blob | bound]
3274 ** to the parameters at a later time.
3275 **
3276 ** ^(This routine actually returns the index of the largest (rightmost)
3277 ** parameter. For all forms except ?NNN, this will correspond to the
3278 ** number of unique parameters.  If parameters of the ?NNN form are used,
3279 ** there may be gaps in the list.)^
3280 **
3281 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3282 ** [sqlite3_bind_parameter_name()], and
3283 ** [sqlite3_bind_parameter_index()].
3284 */
3285 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
3286
3287 /*
3288 ** CAPI3REF: Name Of A Host Parameter
3289 **
3290 ** ^The sqlite3_bind_parameter_name(P,N) interface returns
3291 ** the name of the N-th [SQL parameter] in the [prepared statement] P.
3292 ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
3293 ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
3294 ** respectively.
3295 ** In other words, the initial ":" or "$" or "@" or "?"
3296 ** is included as part of the name.)^
3297 ** ^Parameters of the form "?" without a following integer have no name
3298 ** and are referred to as "nameless" or "anonymous parameters".
3299 **
3300 ** ^The first host parameter has an index of 1, not 0.
3301 **
3302 ** ^If the value N is out of range or if the N-th parameter is
3303 ** nameless, then NULL is returned.  ^The returned string is
3304 ** always in UTF-8 encoding even if the named parameter was
3305 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
3306 ** [sqlite3_prepare16_v2()].
3307 **
3308 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3309 ** [sqlite3_bind_parameter_count()], and
3310 ** [sqlite3_bind_parameter_index()].
3311 */
3312 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
3313
3314 /*
3315 ** CAPI3REF: Index Of A Parameter With A Given Name
3316 **
3317 ** ^Return the index of an SQL parameter given its name.  ^The
3318 ** index value returned is suitable for use as the second
3319 ** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero
3320 ** is returned if no matching parameter is found.  ^The parameter
3321 ** name must be given in UTF-8 even if the original statement
3322 ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
3323 **
3324 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3325 ** [sqlite3_bind_parameter_count()], and
3326 ** [sqlite3_bind_parameter_index()].
3327 */
3328 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
3329
3330 /*
3331 ** CAPI3REF: Reset All Bindings On A Prepared Statement
3332 **
3333 ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
3334 ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
3335 ** ^Use this routine to reset all host parameters to NULL.
3336 */
3337 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
3338
3339 /*
3340 ** CAPI3REF: Number Of Columns In A Result Set
3341 **
3342 ** ^Return the number of columns in the result set returned by the
3343 ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
3344 ** statement that does not return data (for example an [UPDATE]).
3345 */
3346 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
3347
3348 /*
3349 ** CAPI3REF: Column Names In A Result Set
3350 **
3351 ** ^These routines return the name assigned to a particular column
3352 ** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()
3353 ** interface returns a pointer to a zero-terminated UTF-8 string
3354 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
3355 ** UTF-16 string.  ^The first parameter is the [prepared statement]
3356 ** that implements the [SELECT] statement. ^The second parameter is the
3357 ** column number.  ^The leftmost column is number 0.
3358 **
3359 ** ^The returned string pointer is valid until either the [prepared statement]
3360 ** is destroyed by [sqlite3_finalize()] or until the next call to
3361 ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
3362 **
3363 ** ^If sqlite3_malloc() fails during the processing of either routine
3364 ** (for example during a conversion from UTF-8 to UTF-16) then a
3365 ** NULL pointer is returned.
3366 **
3367 ** ^The name of a result column is the value of the "AS" clause for
3368 ** that column, if there is an AS clause.  If there is no AS clause
3369 ** then the name of the column is unspecified and may change from
3370 ** one release of SQLite to the next.
3371 */
3372 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
3373 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
3374
3375 /*
3376 ** CAPI3REF: Source Of Data In A Query Result
3377 **
3378 ** ^These routines provide a means to determine the database, table, and
3379 ** table column that is the origin of a particular result column in
3380 ** [SELECT] statement.
3381 ** ^The name of the database or table or column can be returned as
3382 ** either a UTF-8 or UTF-16 string.  ^The _database_ routines return
3383 ** the database name, the _table_ routines return the table name, and
3384 ** the origin_ routines return the column name.
3385 ** ^The returned string is valid until the [prepared statement] is destroyed
3386 ** using [sqlite3_finalize()] or until the same information is requested
3387 ** again in a different encoding.
3388 **
3389 ** ^The names returned are the original un-aliased names of the
3390 ** database, table, and column.
3391 **
3392 ** ^The first argument to these interfaces is a [prepared statement].
3393 ** ^These functions return information about the Nth result column returned by
3394 ** the statement, where N is the second function argument.
3395 ** ^The left-most column is column 0 for these routines.
3396 **
3397 ** ^If the Nth column returned by the statement is an expression or
3398 ** subquery and is not a column value, then all of these functions return
3399 ** NULL.  ^These routine might also return NULL if a memory allocation error
3400 ** occurs.  ^Otherwise, they return the name of the attached database, table,
3401 ** or column that query result column was extracted from.
3402 **
3403 ** ^As with all other SQLite APIs, those whose names end with "16" return
3404 ** UTF-16 encoded strings and the other functions return UTF-8.
3405 **
3406 ** ^These APIs are only available if the library was compiled with the
3407 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
3408 **
3409 ** If two or more threads call one or more of these routines against the same
3410 ** prepared statement and column at the same time then the results are
3411 ** undefined.
3412 **
3413 ** If two or more threads call one or more
3414 ** [sqlite3_column_database_name | column metadata interfaces]
3415 ** for the same [prepared statement] and result column
3416 ** at the same time then the results are undefined.
3417 */
3418 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
3419 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
3420 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
3421 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
3422 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
3423 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
3424
3425 /*
3426 ** CAPI3REF: Declared Datatype Of A Query Result
3427 **
3428 ** ^(The first parameter is a [prepared statement].
3429 ** If this statement is a [SELECT] statement and the Nth column of the
3430 ** returned result set of that [SELECT] is a table column (not an
3431 ** expression or subquery) then the declared type of the table
3432 ** column is returned.)^  ^If the Nth column of the result set is an
3433 ** expression or subquery, then a NULL pointer is returned.
3434 ** ^The returned string is always UTF-8 encoded.
3435 **
3436 ** ^(For example, given the database schema:
3437 **
3438 ** CREATE TABLE t1(c1 VARIANT);
3439 **
3440 ** and the following statement to be compiled:
3441 **
3442 ** SELECT c1 + 1, c1 FROM t1;
3443 **
3444 ** this routine would return the string "VARIANT" for the second result
3445 ** column (i==1), and a NULL pointer for the first result column (i==0).)^
3446 **
3447 ** ^SQLite uses dynamic run-time typing.  ^So just because a column
3448 ** is declared to contain a particular type does not mean that the
3449 ** data stored in that column is of the declared type.  SQLite is
3450 ** strongly typed, but the typing is dynamic not static.  ^Type
3451 ** is associated with individual values, not with the containers
3452 ** used to hold those values.
3453 */
3454 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
3455 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
3456
3457 /*
3458 ** CAPI3REF: Evaluate An SQL Statement
3459 **
3460 ** After a [prepared statement] has been prepared using either
3461 ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
3462 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
3463 ** must be called one or more times to evaluate the statement.
3464 **
3465 ** The details of the behavior of the sqlite3_step() interface depend
3466 ** on whether the statement was prepared using the newer "v2" interface
3467 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
3468 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
3469 ** new "v2" interface is recommended for new applications but the legacy
3470 ** interface will continue to be supported.
3471 **
3472 ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
3473 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
3474 ** ^With the "v2" interface, any of the other [result codes] or
3475 ** [extended result codes] might be returned as well.
3476 **
3477 ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
3478 ** database locks it needs to do its job.  ^If the statement is a [COMMIT]
3479 ** or occurs outside of an explicit transaction, then you can retry the
3480 ** statement.  If the statement is not a [COMMIT] and occurs within a
3481 ** explicit transaction then you should rollback the transaction before
3482 ** continuing.
3483 **
3484 ** ^[SQLITE_DONE] means that the statement has finished executing
3485 ** successfully.  sqlite3_step() should not be called again on this virtual
3486 ** machine without first calling [sqlite3_reset()] to reset the virtual
3487 ** machine back to its initial state.
3488 **
3489 ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
3490 ** is returned each time a new row of data is ready for processing by the
3491 ** caller. The values may be accessed using the [column access functions].
3492 ** sqlite3_step() is called again to retrieve the next row of data.
3493 **
3494 ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
3495 ** violation) has occurred.  sqlite3_step() should not be called again on
3496 ** the VM. More information may be found by calling [sqlite3_errmsg()].
3497 ** ^With the legacy interface, a more specific error code (for example,
3498 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
3499 ** can be obtained by calling [sqlite3_reset()] on the
3500 ** [prepared statement].  ^In the "v2" interface,
3501 ** the more specific error code is returned directly by sqlite3_step().
3502 **
3503 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
3504 ** Perhaps it was called on a [prepared statement] that has
3505 ** already been [sqlite3_finalize | finalized] or on one that had
3506 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
3507 ** be the case that the same database connection is being used by two or
3508 ** more threads at the same moment in time.
3509 **
3510 ** For all versions of SQLite up to and including 3.6.23.1, it was required
3511 ** after sqlite3_step() returned anything other than [SQLITE_ROW] that
3512 ** [sqlite3_reset()] be called before any subsequent invocation of
3513 ** sqlite3_step().  Failure to invoke [sqlite3_reset()] in this way would
3514 ** result in an [SQLITE_MISUSE] return from sqlite3_step().  But after
3515 ** version 3.6.23.1, sqlite3_step() began calling [sqlite3_reset()] 
3516 ** automatically in this circumstance rather than returning [SQLITE_MISUSE].  
3517 **
3518 ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
3519 ** API always returns a generic error code, [SQLITE_ERROR], following any
3520 ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
3521 ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
3522 ** specific [error codes] that better describes the error.
3523 ** We admit that this is a goofy design.  The problem has been fixed
3524 ** with the "v2" interface.  If you prepare all of your SQL statements
3525 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
3526 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
3527 ** then the more specific [error codes] are returned directly
3528 ** by sqlite3_step().  The use of the "v2" interface is recommended.
3529 */
3530 SQLITE_API int sqlite3_step(sqlite3_stmt*);
3531
3532 /*
3533 ** CAPI3REF: Number of columns in a result set
3534 **
3535 ** ^The sqlite3_data_count(P) the number of columns in the
3536 ** of the result set of [prepared statement] P.
3537 */
3538 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
3539
3540 /*
3541 ** CAPI3REF: Fundamental Datatypes
3542 ** KEYWORDS: SQLITE_TEXT
3543 **
3544 ** ^(Every value in SQLite has one of five fundamental datatypes:
3545 **
3546 ** <ul>
3547 ** <li> 64-bit signed integer
3548 ** <li> 64-bit IEEE floating point number
3549 ** <li> string
3550 ** <li> BLOB
3551 ** <li> NULL
3552 ** </ul>)^
3553 **
3554 ** These constants are codes for each of those types.
3555 **
3556 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
3557 ** for a completely different meaning.  Software that links against both
3558 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
3559 ** SQLITE_TEXT.
3560 */
3561 #define SQLITE_INTEGER  1
3562 #define SQLITE_FLOAT    2
3563 #define SQLITE_BLOB     4
3564 #define SQLITE_NULL     5
3565 #ifdef SQLITE_TEXT
3566 # undef SQLITE_TEXT
3567 #else
3568 # define SQLITE_TEXT     3
3569 #endif
3570 #define SQLITE3_TEXT     3
3571
3572 /*
3573 ** CAPI3REF: Result Values From A Query
3574 ** KEYWORDS: {column access functions}
3575 **
3576 ** These routines form the "result set" interface.
3577 **
3578 ** ^These routines return information about a single column of the current
3579 ** result row of a query.  ^In every case the first argument is a pointer
3580 ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
3581 ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
3582 ** and the second argument is the index of the column for which information
3583 ** should be returned. ^The leftmost column of the result set has the index 0.
3584 ** ^The number of columns in the result can be determined using
3585 ** [sqlite3_column_count()].
3586 **
3587 ** If the SQL statement does not currently point to a valid row, or if the
3588 ** column index is out of range, the result is undefined.
3589 ** These routines may only be called when the most recent call to
3590 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
3591 ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
3592 ** If any of these routines are called after [sqlite3_reset()] or
3593 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
3594 ** something other than [SQLITE_ROW], the results are undefined.
3595 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
3596 ** are called from a different thread while any of these routines
3597 ** are pending, then the results are undefined.
3598 **
3599 ** ^The sqlite3_column_type() routine returns the
3600 ** [SQLITE_INTEGER | datatype code] for the initial data type
3601 ** of the result column.  ^The returned value is one of [SQLITE_INTEGER],
3602 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
3603 ** returned by sqlite3_column_type() is only meaningful if no type
3604 ** conversions have occurred as described below.  After a type conversion,
3605 ** the value returned by sqlite3_column_type() is undefined.  Future
3606 ** versions of SQLite may change the behavior of sqlite3_column_type()
3607 ** following a type conversion.
3608 **
3609 ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
3610 ** routine returns the number of bytes in that BLOB or string.
3611 ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
3612 ** the string to UTF-8 and then returns the number of bytes.
3613 ** ^If the result is a numeric value then sqlite3_column_bytes() uses
3614 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
3615 ** the number of bytes in that string.
3616 ** ^The value returned does not include the zero terminator at the end
3617 ** of the string.  ^For clarity: the value returned is the number of
3618 ** bytes in the string, not the number of characters.
3619 **
3620 ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
3621 ** even empty strings, are always zero terminated.  ^The return
3622 ** value from sqlite3_column_blob() for a zero-length BLOB is an arbitrary
3623 ** pointer, possibly even a NULL pointer.
3624 **
3625 ** ^The sqlite3_column_bytes16() routine is similar to sqlite3_column_bytes()
3626 ** but leaves the result in UTF-16 in native byte order instead of UTF-8.
3627 ** ^The zero terminator is not included in this count.
3628 **
3629 ** ^The object returned by [sqlite3_column_value()] is an
3630 ** [unprotected sqlite3_value] object.  An unprotected sqlite3_value object
3631 ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
3632 ** If the [unprotected sqlite3_value] object returned by
3633 ** [sqlite3_column_value()] is used in any other way, including calls
3634 ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
3635 ** or [sqlite3_value_bytes()], then the behavior is undefined.
3636 **
3637 ** These routines attempt to convert the value where appropriate.  ^For
3638 ** example, if the internal representation is FLOAT and a text result
3639 ** is requested, [sqlite3_snprintf()] is used internally to perform the
3640 ** conversion automatically.  ^(The following table details the conversions
3641 ** that are applied:
3642 **
3643 ** <blockquote>
3644 ** <table border="1">
3645 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
3646 **
3647 ** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
3648 ** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
3649 ** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer
3650 ** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer
3651 ** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
3652 ** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
3653 ** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
3654 ** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer
3655 ** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
3656 ** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT
3657 ** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()
3658 ** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()
3659 ** <tr><td>  TEXT    <td>   BLOB    <td> No change
3660 ** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()
3661 ** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()
3662 ** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
3663 ** </table>
3664 ** </blockquote>)^
3665 **
3666 ** The table above makes reference to standard C library functions atoi()
3667 ** and atof().  SQLite does not really use these functions.  It has its
3668 ** own equivalent internal routines.  The atoi() and atof() names are
3669 ** used in the table for brevity and because they are familiar to most
3670 ** C programmers.
3671 **
3672 ** ^Note that when type conversions occur, pointers returned by prior
3673 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
3674 ** sqlite3_column_text16() may be invalidated.
3675 ** ^(Type conversions and pointer invalidations might occur
3676 ** in the following cases:
3677 **
3678 ** <ul>
3679 ** <li> The initial content is a BLOB and sqlite3_column_text() or
3680 **      sqlite3_column_text16() is called.  A zero-terminator might
3681 **      need to be added to the string.</li>
3682 ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
3683 **      sqlite3_column_text16() is called.  The content must be converted
3684 **      to UTF-16.</li>
3685 ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
3686 **      sqlite3_column_text() is called.  The content must be converted
3687 **      to UTF-8.</li>
3688 ** </ul>)^
3689 **
3690 ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
3691 ** not invalidate a prior pointer, though of course the content of the buffer
3692 ** that the prior pointer points to will have been modified.  Other kinds
3693 ** of conversion are done in place when it is possible, but sometimes they
3694 ** are not possible and in those cases prior pointers are invalidated.
3695 **
3696 ** ^(The safest and easiest to remember policy is to invoke these routines
3697 ** in one of the following ways:
3698 **
3699 ** <ul>
3700 **  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
3701 **  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
3702 **  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
3703 ** </ul>)^
3704 **
3705 ** In other words, you should call sqlite3_column_text(),
3706 ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
3707 ** into the desired format, then invoke sqlite3_column_bytes() or
3708 ** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
3709 ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
3710 ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
3711 ** with calls to sqlite3_column_bytes().
3712 **
3713 ** ^The pointers returned are valid until a type conversion occurs as
3714 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
3715 ** [sqlite3_finalize()] is called.  ^The memory space used to hold strings
3716 ** and BLOBs is freed automatically.  Do <b>not</b> pass the pointers returned
3717 ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
3718 ** [sqlite3_free()].
3719 **
3720 ** ^(If a memory allocation error occurs during the evaluation of any
3721 ** of these routines, a default value is returned.  The default value
3722 ** is either the integer 0, the floating point number 0.0, or a NULL
3723 ** pointer.  Subsequent calls to [sqlite3_errcode()] will return
3724 ** [SQLITE_NOMEM].)^
3725 */
3726 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
3727 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
3728 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
3729 SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
3730 SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
3731 SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
3732 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
3733 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
3734 SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
3735 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
3736
3737 /*
3738 ** CAPI3REF: Destroy A Prepared Statement Object
3739 **
3740 ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
3741 ** ^If the statement was executed successfully or not executed at all, then
3742 ** SQLITE_OK is returned. ^If execution of the statement failed then an
3743 ** [error code] or [extended error code] is returned.
3744 **
3745 ** ^This routine can be called at any point during the execution of the
3746 ** [prepared statement].  ^If the virtual machine has not
3747 ** completed execution when this routine is called, that is like
3748 ** encountering an error or an [sqlite3_interrupt | interrupt].
3749 ** ^Incomplete updates may be rolled back and transactions canceled,
3750 ** depending on the circumstances, and the
3751 ** [error code] returned will be [SQLITE_ABORT].
3752 */
3753 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
3754
3755 /*
3756 ** CAPI3REF: Reset A Prepared Statement Object
3757 **
3758 ** The sqlite3_reset() function is called to reset a [prepared statement]
3759 ** object back to its initial state, ready to be re-executed.
3760 ** ^Any SQL statement variables that had values bound to them using
3761 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
3762 ** Use [sqlite3_clear_bindings()] to reset the bindings.
3763 **
3764 ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
3765 ** back to the beginning of its program.
3766 **
3767 ** ^If the most recent call to [sqlite3_step(S)] for the
3768 ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
3769 ** or if [sqlite3_step(S)] has never before been called on S,
3770 ** then [sqlite3_reset(S)] returns [SQLITE_OK].
3771 **
3772 ** ^If the most recent call to [sqlite3_step(S)] for the
3773 ** [prepared statement] S indicated an error, then
3774 ** [sqlite3_reset(S)] returns an appropriate [error code].
3775 **
3776 ** ^The [sqlite3_reset(S)] interface does not change the values
3777 ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
3778 */
3779 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
3780
3781 /*
3782 ** CAPI3REF: Create Or Redefine SQL Functions
3783 ** KEYWORDS: {function creation routines}
3784 ** KEYWORDS: {application-defined SQL function}
3785 ** KEYWORDS: {application-defined SQL functions}
3786 **
3787 ** ^These two functions (collectively known as "function creation routines")
3788 ** are used to add SQL functions or aggregates or to redefine the behavior
3789 ** of existing SQL functions or aggregates.  The only difference between the
3790 ** two is that the second parameter, the name of the (scalar) function or
3791 ** aggregate, is encoded in UTF-8 for sqlite3_create_function() and UTF-16
3792 ** for sqlite3_create_function16().
3793 **
3794 ** ^The first parameter is the [database connection] to which the SQL
3795 ** function is to be added.  ^If an application uses more than one database
3796 ** connection then application-defined SQL functions must be added
3797 ** to each database connection separately.
3798 **
3799 ** The second parameter is the name of the SQL function to be created or
3800 ** redefined.  ^The length of the name is limited to 255 bytes, exclusive of
3801 ** the zero-terminator.  Note that the name length limit is in bytes, not
3802 ** characters.  ^Any attempt to create a function with a longer name
3803 ** will result in [SQLITE_ERROR] being returned.
3804 **
3805 ** ^The third parameter (nArg)
3806 ** is the number of arguments that the SQL function or
3807 ** aggregate takes. ^If this parameter is -1, then the SQL function or
3808 ** aggregate may take any number of arguments between 0 and the limit
3809 ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third
3810 ** parameter is less than -1 or greater than 127 then the behavior is
3811 ** undefined.
3812 **
3813 ** The fourth parameter, eTextRep, specifies what
3814 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
3815 ** its parameters.  Any SQL function implementation should be able to work
3816 ** work with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
3817 ** more efficient with one encoding than another.  ^An application may
3818 ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
3819 ** times with the same function but with different values of eTextRep.
3820 ** ^When multiple implementations of the same function are available, SQLite
3821 ** will pick the one that involves the least amount of data conversion.
3822 ** If there is only a single implementation which does not care what text
3823 ** encoding is used, then the fourth argument should be [SQLITE_ANY].
3824 **
3825 ** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
3826 ** function can gain access to this pointer using [sqlite3_user_data()].)^
3827 **
3828 ** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are
3829 ** pointers to C-language functions that implement the SQL function or
3830 ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
3831 ** callback only; NULL pointers should be passed as the xStep and xFinal
3832 ** parameters. ^An aggregate SQL function requires an implementation of xStep
3833 ** and xFinal and NULL should be passed for xFunc. ^To delete an existing
3834 ** SQL function or aggregate, pass NULL for all three function callbacks.
3835 **
3836 ** ^It is permitted to register multiple implementations of the same
3837 ** functions with the same name but with either differing numbers of
3838 ** arguments or differing preferred text encodings.  ^SQLite will use
3839 ** the implementation that most closely matches the way in which the
3840 ** SQL function is used.  ^A function implementation with a non-negative
3841 ** nArg parameter is a better match than a function implementation with
3842 ** a negative nArg.  ^A function where the preferred text encoding
3843 ** matches the database encoding is a better
3844 ** match than a function where the encoding is different.  
3845 ** ^A function where the encoding difference is between UTF16le and UTF16be
3846 ** is a closer match than a function where the encoding difference is
3847 ** between UTF8 and UTF16.
3848 **
3849 ** ^Built-in functions may be overloaded by new application-defined functions.
3850 ** ^The first application-defined function with a given name overrides all
3851 ** built-in functions in the same [database connection] with the same name.
3852 ** ^Subsequent application-defined functions of the same name only override 
3853 ** prior application-defined functions that are an exact match for the
3854 ** number of parameters and preferred encoding.
3855 **
3856 ** ^An application-defined function is permitted to call other
3857 ** SQLite interfaces.  However, such calls must not
3858 ** close the database connection nor finalize or reset the prepared
3859 ** statement in which the function is running.
3860 */
3861 SQLITE_API int sqlite3_create_function(
3862   sqlite3 *db,
3863   const char *zFunctionName,
3864   int nArg,
3865   int eTextRep,
3866   void *pApp,
3867   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
3868   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
3869   void (*xFinal)(sqlite3_context*)
3870 );
3871 SQLITE_API int sqlite3_create_function16(
3872   sqlite3 *db,
3873   const void *zFunctionName,
3874   int nArg,
3875   int eTextRep,
3876   void *pApp,
3877   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
3878   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
3879   void (*xFinal)(sqlite3_context*)
3880 );
3881
3882 /*
3883 ** CAPI3REF: Text Encodings
3884 **
3885 ** These constant define integer codes that represent the various
3886 ** text encodings supported by SQLite.
3887 */
3888 #define SQLITE_UTF8           1
3889 #define SQLITE_UTF16LE        2
3890 #define SQLITE_UTF16BE        3
3891 #define SQLITE_UTF16          4    /* Use native byte order */
3892 #define SQLITE_ANY            5    /* sqlite3_create_function only */
3893 #define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
3894
3895 /*
3896 ** CAPI3REF: Deprecated Functions
3897 ** DEPRECATED
3898 **
3899 ** These functions are [deprecated].  In order to maintain
3900 ** backwards compatibility with older code, these functions continue 
3901 ** to be supported.  However, new applications should avoid
3902 ** the use of these functions.  To help encourage people to avoid
3903 ** using these functions, we are not going to tell you what they do.
3904 */
3905 #ifndef SQLITE_OMIT_DEPRECATED
3906 SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
3907 SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
3908 SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
3909 SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
3910 SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
3911 SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
3912 #endif
3913
3914 /*
3915 ** CAPI3REF: Obtaining SQL Function Parameter Values
3916 **
3917 ** The C-language implementation of SQL functions and aggregates uses
3918 ** this set of interface routines to access the parameter values on
3919 ** the function or aggregate.
3920 **
3921 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
3922 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
3923 ** define callbacks that implement the SQL functions and aggregates.
3924 ** The 4th parameter to these callbacks is an array of pointers to
3925 ** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for
3926 ** each parameter to the SQL function.  These routines are used to
3927 ** extract values from the [sqlite3_value] objects.
3928 **
3929 ** These routines work only with [protected sqlite3_value] objects.
3930 ** Any attempt to use these routines on an [unprotected sqlite3_value]
3931 ** object results in undefined behavior.
3932 **
3933 ** ^These routines work just like the corresponding [column access functions]
3934 ** except that  these routines take a single [protected sqlite3_value] object
3935 ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
3936 **
3937 ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
3938 ** in the native byte-order of the host machine.  ^The
3939 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
3940 ** extract UTF-16 strings as big-endian and little-endian respectively.
3941 **
3942 ** ^(The sqlite3_value_numeric_type() interface attempts to apply
3943 ** numeric affinity to the value.  This means that an attempt is
3944 ** made to convert the value to an integer or floating point.  If
3945 ** such a conversion is possible without loss of information (in other
3946 ** words, if the value is a string that looks like a number)
3947 ** then the conversion is performed.  Otherwise no conversion occurs.
3948 ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
3949 **
3950 ** Please pay particular attention to the fact that the pointer returned
3951 ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
3952 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
3953 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
3954 ** or [sqlite3_value_text16()].
3955 **
3956 ** These routines must be called from the same thread as
3957 ** the SQL function that supplied the [sqlite3_value*] parameters.
3958 */
3959 SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
3960 SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
3961 SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
3962 SQLITE_API double sqlite3_value_double(sqlite3_value*);
3963 SQLITE_API int sqlite3_value_int(sqlite3_value*);
3964 SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
3965 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
3966 SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
3967 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
3968 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
3969 SQLITE_API int sqlite3_value_type(sqlite3_value*);
3970 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
3971
3972 /*
3973 ** CAPI3REF: Obtain Aggregate Function Context
3974 **
3975 ** Implementions of aggregate SQL functions use this
3976 ** routine to allocate memory for storing their state.
3977 **
3978 ** ^The first time the sqlite3_aggregate_context(C,N) routine is called 
3979 ** for a particular aggregate function, SQLite
3980 ** allocates N of memory, zeroes out that memory, and returns a pointer
3981 ** to the new memory. ^On second and subsequent calls to
3982 ** sqlite3_aggregate_context() for the same aggregate function instance,
3983 ** the same buffer is returned.  Sqlite3_aggregate_context() is normally
3984 ** called once for each invocation of the xStep callback and then one
3985 ** last time when the xFinal callback is invoked.  ^(When no rows match
3986 ** an aggregate query, the xStep() callback of the aggregate function
3987 ** implementation is never called and xFinal() is called exactly once.
3988 ** In those cases, sqlite3_aggregate_context() might be called for the
3989 ** first time from within xFinal().)^
3990 **
3991 ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer if N is
3992 ** less than or equal to zero or if a memory allocate error occurs.
3993 **
3994 ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
3995 ** determined by the N parameter on first successful call.  Changing the
3996 ** value of N in subsequent call to sqlite3_aggregate_context() within
3997 ** the same aggregate function instance will not resize the memory
3998 ** allocation.)^
3999 **
4000 ** ^SQLite automatically frees the memory allocated by 
4001 ** sqlite3_aggregate_context() when the aggregate query concludes.
4002 **
4003 ** The first parameter must be a copy of the
4004 ** [sqlite3_context | SQL function context] that is the first parameter
4005 ** to the xStep or xFinal callback routine that implements the aggregate
4006 ** function.
4007 **
4008 ** This routine must be called from the same thread in which
4009 ** the aggregate SQL function is running.
4010 */
4011 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
4012
4013 /*
4014 ** CAPI3REF: User Data For Functions
4015 **
4016 ** ^The sqlite3_user_data() interface returns a copy of
4017 ** the pointer that was the pUserData parameter (the 5th parameter)
4018 ** of the [sqlite3_create_function()]
4019 ** and [sqlite3_create_function16()] routines that originally
4020 ** registered the application defined function.
4021 **
4022 ** This routine must be called from the same thread in which
4023 ** the application-defined function is running.
4024 */
4025 SQLITE_API void *sqlite3_user_data(sqlite3_context*);
4026
4027 /*
4028 ** CAPI3REF: Database Connection For Functions
4029 **
4030 ** ^The sqlite3_context_db_handle() interface returns a copy of
4031 ** the pointer to the [database connection] (the 1st parameter)
4032 ** of the [sqlite3_create_function()]
4033 ** and [sqlite3_create_function16()] routines that originally
4034 ** registered the application defined function.
4035 */
4036 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
4037
4038 /*
4039 ** CAPI3REF: Function Auxiliary Data
4040 **
4041 ** The following two functions may be used by scalar SQL functions to
4042 ** associate metadata with argument values. If the same value is passed to
4043 ** multiple invocations of the same SQL function during query execution, under
4044 ** some circumstances the associated metadata may be preserved. This may
4045 ** be used, for example, to add a regular-expression matching scalar
4046 ** function. The compiled version of the regular expression is stored as
4047 ** metadata associated with the SQL value passed as the regular expression
4048 ** pattern.  The compiled regular expression can be reused on multiple
4049 ** invocations of the same function so that the original pattern string
4050 ** does not need to be recompiled on each invocation.
4051 **
4052 ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
4053 ** associated by the sqlite3_set_auxdata() function with the Nth argument
4054 ** value to the application-defined function. ^If no metadata has been ever
4055 ** been set for the Nth argument of the function, or if the corresponding
4056 ** function parameter has changed since the meta-data was set,
4057 ** then sqlite3_get_auxdata() returns a NULL pointer.
4058 **
4059 ** ^The sqlite3_set_auxdata() interface saves the metadata
4060 ** pointed to by its 3rd parameter as the metadata for the N-th
4061 ** argument of the application-defined function.  Subsequent
4062 ** calls to sqlite3_get_auxdata() might return this data, if it has
4063 ** not been destroyed.
4064 ** ^If it is not NULL, SQLite will invoke the destructor
4065 ** function given by the 4th parameter to sqlite3_set_auxdata() on
4066 ** the metadata when the corresponding function parameter changes
4067 ** or when the SQL statement completes, whichever comes first.
4068 **
4069 ** SQLite is free to call the destructor and drop metadata on any
4070 ** parameter of any function at any time.  ^The only guarantee is that
4071 ** the destructor will be called before the metadata is dropped.
4072 **
4073 ** ^(In practice, metadata is preserved between function calls for
4074 ** expressions that are constant at compile time. This includes literal
4075 ** values and [parameters].)^
4076 **
4077 ** These routines must be called from the same thread in which
4078 ** the SQL function is running.
4079 */
4080 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
4081 SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
4082
4083
4084 /*
4085 ** CAPI3REF: Constants Defining Special Destructor Behavior
4086 **
4087 ** These are special values for the destructor that is passed in as the
4088 ** final argument to routines like [sqlite3_result_blob()].  ^If the destructor
4089 ** argument is SQLITE_STATIC, it means that the content pointer is constant
4090 ** and will never change.  It does not need to be destroyed.  ^The
4091 ** SQLITE_TRANSIENT value means that the content will likely change in
4092 ** the near future and that SQLite should make its own private copy of
4093 ** the content before returning.
4094 **
4095 ** The typedef is necessary to work around problems in certain
4096 ** C++ compilers.  See ticket #2191.
4097 */
4098 typedef void (*sqlite3_destructor_type)(void*);
4099 #define SQLITE_STATIC      ((sqlite3_destructor_type)0)
4100 #define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
4101
4102 /*
4103 ** CAPI3REF: Setting The Result Of An SQL Function
4104 **
4105 ** These routines are used by the xFunc or xFinal callbacks that
4106 ** implement SQL functions and aggregates.  See
4107 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
4108 ** for additional information.
4109 **
4110 ** These functions work very much like the [parameter binding] family of
4111 ** functions used to bind values to host parameters in prepared statements.
4112 ** Refer to the [SQL parameter] documentation for additional information.
4113 **
4114 ** ^The sqlite3_result_blob() interface sets the result from
4115 ** an application-defined function to be the BLOB whose content is pointed
4116 ** to by the second parameter and which is N bytes long where N is the
4117 ** third parameter.
4118 **
4119 ** ^The sqlite3_result_zeroblob() interfaces set the result of
4120 ** the application-defined function to be a BLOB containing all zero
4121 ** bytes and N bytes in size, where N is the value of the 2nd parameter.
4122 **
4123 ** ^The sqlite3_result_double() interface sets the result from
4124 ** an application-defined function to be a floating point value specified
4125 ** by its 2nd argument.
4126 **
4127 ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
4128 ** cause the implemented SQL function to throw an exception.
4129 ** ^SQLite uses the string pointed to by the
4130 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
4131 ** as the text of an error message.  ^SQLite interprets the error
4132 ** message string from sqlite3_result_error() as UTF-8. ^SQLite
4133 ** interprets the string from sqlite3_result_error16() as UTF-16 in native
4134 ** byte order.  ^If the third parameter to sqlite3_result_error()
4135 ** or sqlite3_result_error16() is negative then SQLite takes as the error
4136 ** message all text up through the first zero character.
4137 ** ^If the third parameter to sqlite3_result_error() or
4138 ** sqlite3_result_error16() is non-negative then SQLite takes that many
4139 ** bytes (not characters) from the 2nd parameter as the error message.
4140 ** ^The sqlite3_result_error() and sqlite3_result_error16()
4141 ** routines make a private copy of the error message text before
4142 ** they return.  Hence, the calling function can deallocate or
4143 ** modify the text after they return without harm.
4144 ** ^The sqlite3_result_error_code() function changes the error code
4145 ** returned by SQLite as a result of an error in a function.  ^By default,
4146 ** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()
4147 ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
4148 **
4149 ** ^The sqlite3_result_toobig() interface causes SQLite to throw an error
4150 ** indicating that a string or BLOB is too long to represent.
4151 **
4152 ** ^The sqlite3_result_nomem() interface causes SQLite to throw an error
4153 ** indicating that a memory allocation failed.
4154 **
4155 ** ^The sqlite3_result_int() interface sets the return value
4156 ** of the application-defined function to be the 32-bit signed integer
4157 ** value given in the 2nd argument.
4158 ** ^The sqlite3_result_int64() interface sets the return value
4159 ** of the application-defined function to be the 64-bit signed integer
4160 ** value given in the 2nd argument.
4161 **
4162 ** ^The sqlite3_result_null() interface sets the return value
4163 ** of the application-defined function to be NULL.
4164 **
4165 ** ^The sqlite3_result_text(), sqlite3_result_text16(),
4166 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
4167 ** set the return value of the application-defined function to be
4168 ** a text string which is represented as UTF-8, UTF-16 native byte order,
4169 ** UTF-16 little endian, or UTF-16 big endian, respectively.
4170 ** ^SQLite takes the text result from the application from
4171 ** the 2nd parameter of the sqlite3_result_text* interfaces.
4172 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4173 ** is negative, then SQLite takes result text from the 2nd parameter
4174 ** through the first zero character.
4175 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4176 ** is non-negative, then as many bytes (not characters) of the text
4177 ** pointed to by the 2nd parameter are taken as the application-defined
4178 ** function result.
4179 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4180 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
4181 ** function as the destructor on the text or BLOB result when it has
4182 ** finished using that result.
4183 ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
4184 ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
4185 ** assumes that the text or BLOB result is in constant space and does not
4186 ** copy the content of the parameter nor call a destructor on the content
4187 ** when it has finished using that result.
4188 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4189 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
4190 ** then SQLite makes a copy of the result into space obtained from
4191 ** from [sqlite3_malloc()] before it returns.
4192 **
4193 ** ^The sqlite3_result_value() interface sets the result of
4194 ** the application-defined function to be a copy the
4195 ** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The
4196 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
4197 ** so that the [sqlite3_value] specified in the parameter may change or
4198 ** be deallocated after sqlite3_result_value() returns without harm.
4199 ** ^A [protected sqlite3_value] object may always be used where an
4200 ** [unprotected sqlite3_value] object is required, so either
4201 ** kind of [sqlite3_value] object can be used with this interface.
4202 **
4203 ** If these routines are called from within the different thread
4204 ** than the one containing the application-defined function that received
4205 ** the [sqlite3_context] pointer, the results are undefined.
4206 */
4207 SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
4208 SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
4209 SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
4210 SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
4211 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
4212 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
4213 SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
4214 SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
4215 SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
4216 SQLITE_API void sqlite3_result_null(sqlite3_context*);
4217 SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
4218 SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
4219 SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
4220 SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
4221 SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
4222 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
4223
4224 /*
4225 ** CAPI3REF: Define New Collating Sequences
4226 **
4227 ** These functions are used to add new collation sequences to the
4228 ** [database connection] specified as the first argument.
4229 **
4230 ** ^The name of the new collation sequence is specified as a UTF-8 string
4231 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
4232 ** and a UTF-16 string for sqlite3_create_collation16(). ^In all cases
4233 ** the name is passed as the second function argument.
4234 **
4235 ** ^The third argument may be one of the constants [SQLITE_UTF8],
4236 ** [SQLITE_UTF16LE], or [SQLITE_UTF16BE], indicating that the user-supplied
4237 ** routine expects to be passed pointers to strings encoded using UTF-8,
4238 ** UTF-16 little-endian, or UTF-16 big-endian, respectively. ^The
4239 ** third argument might also be [SQLITE_UTF16] to indicate that the routine
4240 ** expects pointers to be UTF-16 strings in the native byte order, or the
4241 ** argument can be [SQLITE_UTF16_ALIGNED] if the
4242 ** the routine expects pointers to 16-bit word aligned strings
4243 ** of UTF-16 in the native byte order.
4244 **
4245 ** A pointer to the user supplied routine must be passed as the fifth
4246 ** argument.  ^If it is NULL, this is the same as deleting the collation
4247 ** sequence (so that SQLite cannot call it anymore).
4248 ** ^Each time the application supplied function is invoked, it is passed
4249 ** as its first parameter a copy of the void* passed as the fourth argument
4250 ** to sqlite3_create_collation() or sqlite3_create_collation16().
4251 **
4252 ** ^The remaining arguments to the application-supplied routine are two strings,
4253 ** each represented by a (length, data) pair and encoded in the encoding
4254 ** that was passed as the third argument when the collation sequence was
4255 ** registered.  The application defined collation routine should
4256 ** return negative, zero or positive if the first string is less than,
4257 ** equal to, or greater than the second string. i.e. (STRING1 - STRING2).
4258 **
4259 ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
4260 ** except that it takes an extra argument which is a destructor for
4261 ** the collation.  ^The destructor is called when the collation is
4262 ** destroyed and is passed a copy of the fourth parameter void* pointer
4263 ** of the sqlite3_create_collation_v2().
4264 ** ^Collations are destroyed when they are overridden by later calls to the
4265 ** collation creation functions or when the [database connection] is closed
4266 ** using [sqlite3_close()].
4267 **
4268 ** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
4269 */
4270 SQLITE_API int sqlite3_create_collation(
4271   sqlite3*, 
4272   const char *zName, 
4273   int eTextRep, 
4274   void*,
4275   int(*xCompare)(void*,int,const void*,int,const void*)
4276 );
4277 SQLITE_API int sqlite3_create_collation_v2(
4278   sqlite3*, 
4279   const char *zName, 
4280   int eTextRep, 
4281   void*,
4282   int(*xCompare)(void*,int,const void*,int,const void*),
4283   void(*xDestroy)(void*)
4284 );
4285 SQLITE_API int sqlite3_create_collation16(
4286   sqlite3*, 
4287   const void *zName,
4288   int eTextRep, 
4289   void*,
4290   int(*xCompare)(void*,int,const void*,int,const void*)
4291 );
4292
4293 /*
4294 ** CAPI3REF: Collation Needed Callbacks
4295 **
4296 ** ^To avoid having to register all collation sequences before a database
4297 ** can be used, a single callback function may be registered with the
4298 ** [database connection] to be invoked whenever an undefined collation
4299 ** sequence is required.
4300 **
4301 ** ^If the function is registered using the sqlite3_collation_needed() API,
4302 ** then it is passed the names of undefined collation sequences as strings
4303 ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
4304 ** the names are passed as UTF-16 in machine native byte order.
4305 ** ^A call to either function replaces the existing collation-needed callback.
4306 **
4307 ** ^(When the callback is invoked, the first argument passed is a copy
4308 ** of the second argument to sqlite3_collation_needed() or
4309 ** sqlite3_collation_needed16().  The second argument is the database
4310 ** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
4311 ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
4312 ** sequence function required.  The fourth parameter is the name of the
4313 ** required collation sequence.)^
4314 **
4315 ** The callback function should register the desired collation using
4316 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
4317 ** [sqlite3_create_collation_v2()].
4318 */
4319 SQLITE_API int sqlite3_collation_needed(
4320   sqlite3*, 
4321   void*, 
4322   void(*)(void*,sqlite3*,int eTextRep,const char*)
4323 );
4324 SQLITE_API int sqlite3_collation_needed16(
4325   sqlite3*, 
4326   void*,
4327   void(*)(void*,sqlite3*,int eTextRep,const void*)
4328 );
4329
4330 #ifdef SQLITE_HAS_CODEC
4331 /*
4332 ** Specify the key for an encrypted database.  This routine should be
4333 ** called right after sqlite3_open().
4334 **
4335 ** The code to implement this API is not available in the public release
4336 ** of SQLite.
4337 */
4338 SQLITE_API int sqlite3_key(
4339   sqlite3 *db,                   /* Database to be rekeyed */
4340   const void *pKey, int nKey     /* The key */
4341 );
4342
4343 /*
4344 ** Change the key on an open database.  If the current database is not
4345 ** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
4346 ** database is decrypted.
4347 **
4348 ** The code to implement this API is not available in the public release
4349 ** of SQLite.
4350 */
4351 SQLITE_API int sqlite3_rekey(
4352   sqlite3 *db,                   /* Database to be rekeyed */
4353   const void *pKey, int nKey     /* The new key */
4354 );
4355
4356 /*
4357 ** Specify the activation key for a SEE database.  Unless 
4358 ** activated, none of the SEE routines will work.
4359 */
4360 SQLITE_API void sqlite3_activate_see(
4361   const char *zPassPhrase        /* Activation phrase */
4362 );
4363 #endif
4364
4365 #ifdef SQLITE_ENABLE_CEROD
4366 /*
4367 ** Specify the activation key for a CEROD database.  Unless 
4368 ** activated, none of the CEROD routines will work.
4369 */
4370 SQLITE_API void sqlite3_activate_cerod(
4371   const char *zPassPhrase        /* Activation phrase */
4372 );
4373 #endif
4374
4375 /*
4376 ** CAPI3REF: Suspend Execution For A Short Time
4377 **
4378 ** ^The sqlite3_sleep() function causes the current thread to suspend execution
4379 ** for at least a number of milliseconds specified in its parameter.
4380 **
4381 ** ^If the operating system does not support sleep requests with
4382 ** millisecond time resolution, then the time will be rounded up to
4383 ** the nearest second. ^The number of milliseconds of sleep actually
4384 ** requested from the operating system is returned.
4385 **
4386 ** ^SQLite implements this interface by calling the xSleep()
4387 ** method of the default [sqlite3_vfs] object.
4388 */
4389 SQLITE_API int sqlite3_sleep(int);
4390
4391 /*
4392 ** CAPI3REF: Name Of The Folder Holding Temporary Files
4393 **
4394 ** ^(If this global variable is made to point to a string which is
4395 ** the name of a folder (a.k.a. directory), then all temporary files
4396 ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
4397 ** will be placed in that directory.)^  ^If this variable
4398 ** is a NULL pointer, then SQLite performs a search for an appropriate
4399 ** temporary file directory.
4400 **
4401 ** It is not safe to read or modify this variable in more than one
4402 ** thread at a time.  It is not safe to read or modify this variable
4403 ** if a [database connection] is being used at the same time in a separate
4404 ** thread.
4405 ** It is intended that this variable be set once
4406 ** as part of process initialization and before any SQLite interface
4407 ** routines have been called and that this variable remain unchanged
4408 ** thereafter.
4409 **
4410 ** ^The [temp_store_directory pragma] may modify this variable and cause
4411 ** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
4412 ** the [temp_store_directory pragma] always assumes that any string
4413 ** that this variable points to is held in memory obtained from 
4414 ** [sqlite3_malloc] and the pragma may attempt to free that memory
4415 ** using [sqlite3_free].
4416 ** Hence, if this variable is modified directly, either it should be
4417 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
4418 ** or else the use of the [temp_store_directory pragma] should be avoided.
4419 */
4420 SQLITE_API char *sqlite3_temp_directory;
4421
4422 /*
4423 ** CAPI3REF: Test For Auto-Commit Mode
4424 ** KEYWORDS: {autocommit mode}
4425 **
4426 ** ^The sqlite3_get_autocommit() interface returns non-zero or
4427 ** zero if the given database connection is or is not in autocommit mode,
4428 ** respectively.  ^Autocommit mode is on by default.
4429 ** ^Autocommit mode is disabled by a [BEGIN] statement.
4430 ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
4431 **
4432 ** If certain kinds of errors occur on a statement within a multi-statement
4433 ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
4434 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
4435 ** transaction might be rolled back automatically.  The only way to
4436 ** find out whether SQLite automatically rolled back the transaction after
4437 ** an error is to use this function.
4438 **
4439 ** If another thread changes the autocommit status of the database
4440 ** connection while this routine is running, then the return value
4441 ** is undefined.
4442 */
4443 SQLITE_API int sqlite3_get_autocommit(sqlite3*);
4444
4445 /*
4446 ** CAPI3REF: Find The Database Handle Of A Prepared Statement
4447 **
4448 ** ^The sqlite3_db_handle interface returns the [database connection] handle
4449 ** to which a [prepared statement] belongs.  ^The [database connection]
4450 ** returned by sqlite3_db_handle is the same [database connection]
4451 ** that was the first argument
4452 ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
4453 ** create the statement in the first place.
4454 */
4455 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
4456
4457 /*
4458 ** CAPI3REF: Find the next prepared statement
4459 **
4460 ** ^This interface returns a pointer to the next [prepared statement] after
4461 ** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL
4462 ** then this interface returns a pointer to the first prepared statement
4463 ** associated with the database connection pDb.  ^If no prepared statement
4464 ** satisfies the conditions of this routine, it returns NULL.
4465 **
4466 ** The [database connection] pointer D in a call to
4467 ** [sqlite3_next_stmt(D,S)] must refer to an open database
4468 ** connection and in particular must not be a NULL pointer.
4469 */
4470 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
4471
4472 /*
4473 ** CAPI3REF: Commit And Rollback Notification Callbacks
4474 **
4475 ** ^The sqlite3_commit_hook() interface registers a callback
4476 ** function to be invoked whenever a transaction is [COMMIT | committed].
4477 ** ^Any callback set by a previous call to sqlite3_commit_hook()
4478 ** for the same database connection is overridden.
4479 ** ^The sqlite3_rollback_hook() interface registers a callback
4480 ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
4481 ** ^Any callback set by a previous call to sqlite3_rollback_hook()
4482 ** for the same database connection is overridden.
4483 ** ^The pArg argument is passed through to the callback.
4484 ** ^If the callback on a commit hook function returns non-zero,
4485 ** then the commit is converted into a rollback.
4486 **
4487 ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
4488 ** return the P argument from the previous call of the same function
4489 ** on the same [database connection] D, or NULL for
4490 ** the first call for each function on D.
4491 **
4492 ** The callback implementation must not do anything that will modify
4493 ** the database connection that invoked the callback.  Any actions
4494 ** to modify the database connection must be deferred until after the
4495 ** completion of the [sqlite3_step()] call that triggered the commit
4496 ** or rollback hook in the first place.
4497 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
4498 ** database connections for the meaning of "modify" in this paragraph.
4499 **
4500 ** ^Registering a NULL function disables the callback.
4501 **
4502 ** ^When the commit hook callback routine returns zero, the [COMMIT]
4503 ** operation is allowed to continue normally.  ^If the commit hook
4504 ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
4505 ** ^The rollback hook is invoked on a rollback that results from a commit
4506 ** hook returning non-zero, just as it would be with any other rollback.
4507 **
4508 ** ^For the purposes of this API, a transaction is said to have been
4509 ** rolled back if an explicit "ROLLBACK" statement is executed, or
4510 ** an error or constraint causes an implicit rollback to occur.
4511 ** ^The rollback callback is not invoked if a transaction is
4512 ** automatically rolled back because the database connection is closed.
4513 **
4514 ** See also the [sqlite3_update_hook()] interface.
4515 */
4516 SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
4517 SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
4518
4519 /*
4520 ** CAPI3REF: Data Change Notification Callbacks
4521 **
4522 ** ^The sqlite3_update_hook() interface registers a callback function
4523 ** with the [database connection] identified by the first argument
4524 ** to be invoked whenever a row is updated, inserted or deleted.
4525 ** ^Any callback set by a previous call to this function
4526 ** for the same database connection is overridden.
4527 **
4528 ** ^The second argument is a pointer to the function to invoke when a
4529 ** row is updated, inserted or deleted.
4530 ** ^The first argument to the callback is a copy of the third argument
4531 ** to sqlite3_update_hook().
4532 ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
4533 ** or [SQLITE_UPDATE], depending on the operation that caused the callback
4534 ** to be invoked.
4535 ** ^The third and fourth arguments to the callback contain pointers to the
4536 ** database and table name containing the affected row.
4537 ** ^The final callback parameter is the [rowid] of the row.
4538 ** ^In the case of an update, this is the [rowid] after the update takes place.
4539 **
4540 ** ^(The update hook is not invoked when internal system tables are
4541 ** modified (i.e. sqlite_master and sqlite_sequence).)^
4542 **
4543 ** ^In the current implementation, the update hook
4544 ** is not invoked when duplication rows are deleted because of an
4545 ** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook
4546 ** invoked when rows are deleted using the [truncate optimization].
4547 ** The exceptions defined in this paragraph might change in a future
4548 ** release of SQLite.
4549 **
4550 ** The update hook implementation must not do anything that will modify
4551 ** the database connection that invoked the update hook.  Any actions
4552 ** to modify the database connection must be deferred until after the
4553 ** completion of the [sqlite3_step()] call that triggered the update hook.
4554 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
4555 ** database connections for the meaning of "modify" in this paragraph.
4556 **
4557 ** ^The sqlite3_update_hook(D,C,P) function
4558 ** returns the P argument from the previous call
4559 ** on the same [database connection] D, or NULL for
4560 ** the first call on D.
4561 **
4562 ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
4563 ** interfaces.
4564 */
4565 SQLITE_API void *sqlite3_update_hook(
4566   sqlite3*, 
4567   void(*)(void *,int ,char const *,char const *,sqlite3_int64),
4568   void*
4569 );
4570
4571 /*
4572 ** CAPI3REF: Enable Or Disable Shared Pager Cache
4573 ** KEYWORDS: {shared cache}
4574 **
4575 ** ^(This routine enables or disables the sharing of the database cache
4576 ** and schema data structures between [database connection | connections]
4577 ** to the same database. Sharing is enabled if the argument is true
4578 ** and disabled if the argument is false.)^
4579 **
4580 ** ^Cache sharing is enabled and disabled for an entire process.
4581 ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
4582 ** sharing was enabled or disabled for each thread separately.
4583 **
4584 ** ^(The cache sharing mode set by this interface effects all subsequent
4585 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
4586 ** Existing database connections continue use the sharing mode
4587 ** that was in effect at the time they were opened.)^
4588 **
4589 ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
4590 ** successfully.  An [error code] is returned otherwise.)^
4591 **
4592 ** ^Shared cache is disabled by default. But this might change in
4593 ** future releases of SQLite.  Applications that care about shared
4594 ** cache setting should set it explicitly.
4595 **
4596 ** See Also:  [SQLite Shared-Cache Mode]
4597 */
4598 SQLITE_API int sqlite3_enable_shared_cache(int);
4599
4600 /*
4601 ** CAPI3REF: Attempt To Free Heap Memory
4602 **
4603 ** ^The sqlite3_release_memory() interface attempts to free N bytes
4604 ** of heap memory by deallocating non-essential memory allocations
4605 ** held by the database library.   Memory used to cache database
4606 ** pages to improve performance is an example of non-essential memory.
4607 ** ^sqlite3_release_memory() returns the number of bytes actually freed,
4608 ** which might be more or less than the amount requested.
4609 */
4610 SQLITE_API int sqlite3_release_memory(int);
4611
4612 /*
4613 ** CAPI3REF: Impose A Limit On Heap Size
4614 **
4615 ** ^The sqlite3_soft_heap_limit() interface places a "soft" limit
4616 ** on the amount of heap memory that may be allocated by SQLite.
4617 ** ^If an internal allocation is requested that would exceed the
4618 ** soft heap limit, [sqlite3_release_memory()] is invoked one or
4619 ** more times to free up some space before the allocation is performed.
4620 **
4621 ** ^The limit is called "soft" because if [sqlite3_release_memory()]
4622 ** cannot free sufficient memory to prevent the limit from being exceeded,
4623 ** the memory is allocated anyway and the current operation proceeds.
4624 **
4625 ** ^A negative or zero value for N means that there is no soft heap limit and
4626 ** [sqlite3_release_memory()] will only be called when memory is exhausted.
4627 ** ^The default value for the soft heap limit is zero.
4628 **
4629 ** ^(SQLite makes a best effort to honor the soft heap limit.
4630 ** But if the soft heap limit cannot be honored, execution will
4631 ** continue without error or notification.)^  This is why the limit is
4632 ** called a "soft" limit.  It is advisory only.
4633 **
4634 ** Prior to SQLite version 3.5.0, this routine only constrained the memory
4635 ** allocated by a single thread - the same thread in which this routine
4636 ** runs.  Beginning with SQLite version 3.5.0, the soft heap limit is
4637 ** applied to all threads. The value specified for the soft heap limit
4638 ** is an upper bound on the total memory allocation for all threads. In
4639 ** version 3.5.0 there is no mechanism for limiting the heap usage for
4640 ** individual threads.
4641 */
4642 SQLITE_API void sqlite3_soft_heap_limit(int);
4643
4644 /*
4645 ** CAPI3REF: Extract Metadata About A Column Of A Table
4646 **
4647 ** ^This routine returns metadata about a specific column of a specific
4648 ** database table accessible using the [database connection] handle
4649 ** passed as the first function argument.
4650 **
4651 ** ^The column is identified by the second, third and fourth parameters to
4652 ** this function. ^The second parameter is either the name of the database
4653 ** (i.e. "main", "temp", or an attached database) containing the specified
4654 ** table or NULL. ^If it is NULL, then all attached databases are searched
4655 ** for the table using the same algorithm used by the database engine to
4656 ** resolve unqualified table references.
4657 **
4658 ** ^The third and fourth parameters to this function are the table and column
4659 ** name of the desired column, respectively. Neither of these parameters
4660 ** may be NULL.
4661 **
4662 ** ^Metadata is returned by writing to the memory locations passed as the 5th
4663 ** and subsequent parameters to this function. ^Any of these arguments may be
4664 ** NULL, in which case the corresponding element of metadata is omitted.
4665 **
4666 ** ^(<blockquote>
4667 ** <table border="1">
4668 ** <tr><th> Parameter <th> Output<br>Type <th>  Description
4669 **
4670 ** <tr><td> 5th <td> const char* <td> Data type
4671 ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
4672 ** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
4673 ** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
4674 ** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]
4675 ** </table>
4676 ** </blockquote>)^
4677 **
4678 ** ^The memory pointed to by the character pointers returned for the
4679 ** declaration type and collation sequence is valid only until the next
4680 ** call to any SQLite API function.
4681 **
4682 ** ^If the specified table is actually a view, an [error code] is returned.
4683 **
4684 ** ^If the specified column is "rowid", "oid" or "_rowid_" and an
4685 ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
4686 ** parameters are set for the explicitly declared column. ^(If there is no
4687 ** explicitly declared [INTEGER PRIMARY KEY] column, then the output
4688 ** parameters are set as follows:
4689 **
4690 ** <pre>
4691 **     data type: "INTEGER"
4692 **     collation sequence: "BINARY"
4693 **     not null: 0
4694 **     primary key: 1
4695 **     auto increment: 0
4696 ** </pre>)^
4697 **
4698 ** ^(This function may load one or more schemas from database files. If an
4699 ** error occurs during this process, or if the requested table or column
4700 ** cannot be found, an [error code] is returned and an error message left
4701 ** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
4702 **
4703 ** ^This API is only available if the library was compiled with the
4704 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
4705 */
4706 SQLITE_API int sqlite3_table_column_metadata(
4707   sqlite3 *db,                /* Connection handle */
4708   const char *zDbName,        /* Database name or NULL */
4709   const char *zTableName,     /* Table name */
4710   const char *zColumnName,    /* Column name */
4711   char const **pzDataType,    /* OUTPUT: Declared data type */
4712   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
4713   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
4714   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
4715   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
4716 );
4717
4718 /*
4719 ** CAPI3REF: Load An Extension
4720 **
4721 ** ^This interface loads an SQLite extension library from the named file.
4722 **
4723 ** ^The sqlite3_load_extension() interface attempts to load an
4724 ** SQLite extension library contained in the file zFile.
4725 **
4726 ** ^The entry point is zProc.
4727 ** ^zProc may be 0, in which case the name of the entry point
4728 ** defaults to "sqlite3_extension_init".
4729 ** ^The sqlite3_load_extension() interface returns
4730 ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
4731 ** ^If an error occurs and pzErrMsg is not 0, then the
4732 ** [sqlite3_load_extension()] interface shall attempt to
4733 ** fill *pzErrMsg with error message text stored in memory
4734 ** obtained from [sqlite3_malloc()]. The calling function
4735 ** should free this memory by calling [sqlite3_free()].
4736 **
4737 ** ^Extension loading must be enabled using
4738 ** [sqlite3_enable_load_extension()] prior to calling this API,
4739 ** otherwise an error will be returned.
4740 **
4741 ** See also the [load_extension() SQL function].
4742 */
4743 SQLITE_API int sqlite3_load_extension(
4744   sqlite3 *db,          /* Load the extension into this database connection */
4745   const char *zFile,    /* Name of the shared library containing extension */
4746   const char *zProc,    /* Entry point.  Derived from zFile if 0 */
4747   char **pzErrMsg       /* Put error message here if not 0 */
4748 );
4749
4750 /*
4751 ** CAPI3REF: Enable Or Disable Extension Loading
4752 **
4753 ** ^So as not to open security holes in older applications that are
4754 ** unprepared to deal with extension loading, and as a means of disabling
4755 ** extension loading while evaluating user-entered SQL, the following API
4756 ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
4757 **
4758 ** ^Extension loading is off by default. See ticket #1863.
4759 ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
4760 ** to turn extension loading on and call it with onoff==0 to turn
4761 ** it back off again.
4762 */
4763 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
4764
4765 /*
4766 ** CAPI3REF: Automatically Load An Extensions
4767 **
4768 ** ^This API can be invoked at program startup in order to register
4769 ** one or more statically linked extensions that will be available
4770 ** to all new [database connections].
4771 **
4772 ** ^(This routine stores a pointer to the extension entry point
4773 ** in an array that is obtained from [sqlite3_malloc()].  That memory
4774 ** is deallocated by [sqlite3_reset_auto_extension()].)^
4775 **
4776 ** ^This function registers an extension entry point that is
4777 ** automatically invoked whenever a new [database connection]
4778 ** is opened using [sqlite3_open()], [sqlite3_open16()],
4779 ** or [sqlite3_open_v2()].
4780 ** ^Duplicate extensions are detected so calling this routine
4781 ** multiple times with the same extension is harmless.
4782 ** ^Automatic extensions apply across all threads.
4783 */
4784 SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
4785
4786 /*
4787 ** CAPI3REF: Reset Automatic Extension Loading
4788 **
4789 ** ^(This function disables all previously registered automatic
4790 ** extensions. It undoes the effect of all prior
4791 ** [sqlite3_auto_extension()] calls.)^
4792 **
4793 ** ^This function disables automatic extensions in all threads.
4794 */
4795 SQLITE_API void sqlite3_reset_auto_extension(void);
4796
4797 /*
4798 ** The interface to the virtual-table mechanism is currently considered
4799 ** to be experimental.  The interface might change in incompatible ways.
4800 ** If this is a problem for you, do not use the interface at this time.
4801 **
4802 ** When the virtual-table mechanism stabilizes, we will declare the
4803 ** interface fixed, support it indefinitely, and remove this comment.
4804 */
4805
4806 /*
4807 ** Structures used by the virtual table interface
4808 */
4809 typedef struct sqlite3_vtab sqlite3_vtab;
4810 typedef struct sqlite3_index_info sqlite3_index_info;
4811 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
4812 typedef struct sqlite3_module sqlite3_module;
4813
4814 /*
4815 ** CAPI3REF: Virtual Table Object
4816 ** KEYWORDS: sqlite3_module {virtual table module}
4817 **
4818 ** This structure, sometimes called a a "virtual table module", 
4819 ** defines the implementation of a [virtual tables].  
4820 ** This structure consists mostly of methods for the module.
4821 **
4822 ** ^A virtual table module is created by filling in a persistent
4823 ** instance of this structure and passing a pointer to that instance
4824 ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
4825 ** ^The registration remains valid until it is replaced by a different
4826 ** module or until the [database connection] closes.  The content
4827 ** of this structure must not change while it is registered with
4828 ** any database connection.
4829 */
4830 struct sqlite3_module {
4831   int iVersion;
4832   int (*xCreate)(sqlite3*, void *pAux,
4833                int argc, const char *const*argv,
4834                sqlite3_vtab **ppVTab, char**);
4835   int (*xConnect)(sqlite3*, void *pAux,
4836                int argc, const char *const*argv,
4837                sqlite3_vtab **ppVTab, char**);
4838   int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
4839   int (*xDisconnect)(sqlite3_vtab *pVTab);
4840   int (*xDestroy)(sqlite3_vtab *pVTab);
4841   int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
4842   int (*xClose)(sqlite3_vtab_cursor*);
4843   int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
4844                 int argc, sqlite3_value **argv);
4845   int (*xNext)(sqlite3_vtab_cursor*);
4846   int (*xEof)(sqlite3_vtab_cursor*);
4847   int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
4848   int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
4849   int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
4850   int (*xBegin)(sqlite3_vtab *pVTab);
4851   int (*xSync)(sqlite3_vtab *pVTab);
4852   int (*xCommit)(sqlite3_vtab *pVTab);
4853   int (*xRollback)(sqlite3_vtab *pVTab);
4854   int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
4855                        void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
4856                        void **ppArg);
4857   int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
4858 };
4859
4860 /*
4861 ** CAPI3REF: Virtual Table Indexing Information
4862 ** KEYWORDS: sqlite3_index_info
4863 **
4864 ** The sqlite3_index_info structure and its substructures is used to
4865 ** pass information into and receive the reply from the [xBestIndex]
4866 ** method of a [virtual table module].  The fields under **Inputs** are the
4867 ** inputs to xBestIndex and are read-only.  xBestIndex inserts its
4868 ** results into the **Outputs** fields.
4869 **
4870 ** ^(The aConstraint[] array records WHERE clause constraints of the form:
4871 **
4872 ** <pre>column OP expr</pre>
4873 **
4874 ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
4875 ** stored in aConstraint[].op.)^  ^(The index of the column is stored in
4876 ** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
4877 ** expr on the right-hand side can be evaluated (and thus the constraint
4878 ** is usable) and false if it cannot.)^
4879 **
4880 ** ^The optimizer automatically inverts terms of the form "expr OP column"
4881 ** and makes other simplifications to the WHERE clause in an attempt to
4882 ** get as many WHERE clause terms into the form shown above as possible.
4883 ** ^The aConstraint[] array only reports WHERE clause terms that are
4884 ** relevant to the particular virtual table being queried.
4885 **
4886 ** ^Information about the ORDER BY clause is stored in aOrderBy[].
4887 ** ^Each term of aOrderBy records a column of the ORDER BY clause.
4888 **
4889 ** The [xBestIndex] method must fill aConstraintUsage[] with information
4890 ** about what parameters to pass to xFilter.  ^If argvIndex>0 then
4891 ** the right-hand side of the corresponding aConstraint[] is evaluated
4892 ** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit
4893 ** is true, then the constraint is assumed to be fully handled by the
4894 ** virtual table and is not checked again by SQLite.)^
4895 **
4896 ** ^The idxNum and idxPtr values are recorded and passed into the
4897 ** [xFilter] method.
4898 ** ^[sqlite3_free()] is used to free idxPtr if and only if
4899 ** needToFreeIdxPtr is true.
4900 **
4901 ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
4902 ** the correct order to satisfy the ORDER BY clause so that no separate
4903 ** sorting step is required.
4904 **
4905 ** ^The estimatedCost value is an estimate of the cost of doing the
4906 ** particular lookup.  A full scan of a table with N entries should have
4907 ** a cost of N.  A binary search of a table of N entries should have a
4908 ** cost of approximately log(N).
4909 */
4910 struct sqlite3_index_info {
4911   /* Inputs */
4912   int nConstraint;           /* Number of entries in aConstraint */
4913   struct sqlite3_index_constraint {
4914      int iColumn;              /* Column on left-hand side of constraint */
4915      unsigned char op;         /* Constraint operator */
4916      unsigned char usable;     /* True if this constraint is usable */
4917      int iTermOffset;          /* Used internally - xBestIndex should ignore */
4918   } *aConstraint;            /* Table of WHERE clause constraints */
4919   int nOrderBy;              /* Number of terms in the ORDER BY clause */
4920   struct sqlite3_index_orderby {
4921      int iColumn;              /* Column number */
4922      unsigned char desc;       /* True for DESC.  False for ASC. */
4923   } *aOrderBy;               /* The ORDER BY clause */
4924   /* Outputs */
4925   struct sqlite3_index_constraint_usage {
4926     int argvIndex;           /* if >0, constraint is part of argv to xFilter */
4927     unsigned char omit;      /* Do not code a test for this constraint */
4928   } *aConstraintUsage;
4929   int idxNum;                /* Number used to identify the index */
4930   char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
4931   int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
4932   int orderByConsumed;       /* True if output is already ordered */
4933   double estimatedCost;      /* Estimated cost of using this index */
4934 };
4935 #define SQLITE_INDEX_CONSTRAINT_EQ    2
4936 #define SQLITE_INDEX_CONSTRAINT_GT    4
4937 #define SQLITE_INDEX_CONSTRAINT_LE    8
4938 #define SQLITE_INDEX_CONSTRAINT_LT    16
4939 #define SQLITE_INDEX_CONSTRAINT_GE    32
4940 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
4941
4942 /*
4943 ** CAPI3REF: Register A Virtual Table Implementation
4944 **
4945 ** ^These routines are used to register a new [virtual table module] name.
4946 ** ^Module names must be registered before
4947 ** creating a new [virtual table] using the module and before using a
4948 ** preexisting [virtual table] for the module.
4949 **
4950 ** ^The module name is registered on the [database connection] specified
4951 ** by the first parameter.  ^The name of the module is given by the 
4952 ** second parameter.  ^The third parameter is a pointer to
4953 ** the implementation of the [virtual table module].   ^The fourth
4954 ** parameter is an arbitrary client data pointer that is passed through
4955 ** into the [xCreate] and [xConnect] methods of the virtual table module
4956 ** when a new virtual table is be being created or reinitialized.
4957 **
4958 ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
4959 ** is a pointer to a destructor for the pClientData.  ^SQLite will
4960 ** invoke the destructor function (if it is not NULL) when SQLite
4961 ** no longer needs the pClientData pointer.  ^The sqlite3_create_module()
4962 ** interface is equivalent to sqlite3_create_module_v2() with a NULL
4963 ** destructor.
4964 */
4965 SQLITE_API int sqlite3_create_module(
4966   sqlite3 *db,               /* SQLite connection to register module with */
4967   const char *zName,         /* Name of the module */
4968   const sqlite3_module *p,   /* Methods for the module */
4969   void *pClientData          /* Client data for xCreate/xConnect */
4970 );
4971 SQLITE_API int sqlite3_create_module_v2(
4972   sqlite3 *db,               /* SQLite connection to register module with */
4973   const char *zName,         /* Name of the module */
4974   const sqlite3_module *p,   /* Methods for the module */
4975   void *pClientData,         /* Client data for xCreate/xConnect */
4976   void(*xDestroy)(void*)     /* Module destructor function */
4977 );
4978
4979 /*
4980 ** CAPI3REF: Virtual Table Instance Object
4981 ** KEYWORDS: sqlite3_vtab
4982 **
4983 ** Every [virtual table module] implementation uses a subclass
4984 ** of this object to describe a particular instance
4985 ** of the [virtual table].  Each subclass will
4986 ** be tailored to the specific needs of the module implementation.
4987 ** The purpose of this superclass is to define certain fields that are
4988 ** common to all module implementations.
4989 **
4990 ** ^Virtual tables methods can set an error message by assigning a
4991 ** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
4992 ** take care that any prior string is freed by a call to [sqlite3_free()]
4993 ** prior to assigning a new string to zErrMsg.  ^After the error message
4994 ** is delivered up to the client application, the string will be automatically
4995 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
4996 */
4997 struct sqlite3_vtab {
4998   const sqlite3_module *pModule;  /* The module for this virtual table */
4999   int nRef;                       /* NO LONGER USED */
5000   char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
5001   /* Virtual table implementations will typically add additional fields */
5002 };
5003
5004 /*
5005 ** CAPI3REF: Virtual Table Cursor Object
5006 ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
5007 **
5008 ** Every [virtual table module] implementation uses a subclass of the
5009 ** following structure to describe cursors that point into the
5010 ** [virtual table] and are used
5011 ** to loop through the virtual table.  Cursors are created using the
5012 ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
5013 ** by the [sqlite3_module.xClose | xClose] method.  Cursors are used
5014 ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
5015 ** of the module.  Each module implementation will define
5016 ** the content of a cursor structure to suit its own needs.
5017 **
5018 ** This superclass exists in order to define fields of the cursor that
5019 ** are common to all implementations.
5020 */
5021 struct sqlite3_vtab_cursor {
5022   sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
5023   /* Virtual table implementations will typically add additional fields */
5024 };
5025
5026 /*
5027 ** CAPI3REF: Declare The Schema Of A Virtual Table
5028 **
5029 ** ^The [xCreate] and [xConnect] methods of a
5030 ** [virtual table module] call this interface
5031 ** to declare the format (the names and datatypes of the columns) of
5032 ** the virtual tables they implement.
5033 */
5034 SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
5035
5036 /*
5037 ** CAPI3REF: Overload A Function For A Virtual Table
5038 **
5039 ** ^(Virtual tables can provide alternative implementations of functions
5040 ** using the [xFindFunction] method of the [virtual table module].  
5041 ** But global versions of those functions
5042 ** must exist in order to be overloaded.)^
5043 **
5044 ** ^(This API makes sure a global version of a function with a particular
5045 ** name and number of parameters exists.  If no such function exists
5046 ** before this API is called, a new function is created.)^  ^The implementation
5047 ** of the new function always causes an exception to be thrown.  So
5048 ** the new function is not good for anything by itself.  Its only
5049 ** purpose is to be a placeholder function that can be overloaded
5050 ** by a [virtual table].
5051 */
5052 SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
5053
5054 /*
5055 ** The interface to the virtual-table mechanism defined above (back up
5056 ** to a comment remarkably similar to this one) is currently considered
5057 ** to be experimental.  The interface might change in incompatible ways.
5058 ** If this is a problem for you, do not use the interface at this time.
5059 **
5060 ** When the virtual-table mechanism stabilizes, we will declare the
5061 ** interface fixed, support it indefinitely, and remove this comment.
5062 */
5063
5064 /*
5065 ** CAPI3REF: A Handle To An Open BLOB
5066 ** KEYWORDS: {BLOB handle} {BLOB handles}
5067 **
5068 ** An instance of this object represents an open BLOB on which
5069 ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
5070 ** ^Objects of this type are created by [sqlite3_blob_open()]
5071 ** and destroyed by [sqlite3_blob_close()].
5072 ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
5073 ** can be used to read or write small subsections of the BLOB.
5074 ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
5075 */
5076 typedef struct sqlite3_blob sqlite3_blob;
5077
5078 /*
5079 ** CAPI3REF: Open A BLOB For Incremental I/O
5080 **
5081 ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
5082 ** in row iRow, column zColumn, table zTable in database zDb;
5083 ** in other words, the same BLOB that would be selected by:
5084 **
5085 ** <pre>
5086 **     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
5087 ** </pre>)^
5088 **
5089 ** ^If the flags parameter is non-zero, then the BLOB is opened for read
5090 ** and write access. ^If it is zero, the BLOB is opened for read access.
5091 ** ^It is not possible to open a column that is part of an index or primary 
5092 ** key for writing. ^If [foreign key constraints] are enabled, it is 
5093 ** not possible to open a column that is part of a [child key] for writing.
5094 **
5095 ** ^Note that the database name is not the filename that contains
5096 ** the database but rather the symbolic name of the database that
5097 ** appears after the AS keyword when the database is connected using [ATTACH].
5098 ** ^For the main database file, the database name is "main".
5099 ** ^For TEMP tables, the database name is "temp".
5100 **
5101 ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
5102 ** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
5103 ** to be a null pointer.)^
5104 ** ^This function sets the [database connection] error code and message
5105 ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
5106 ** functions. ^Note that the *ppBlob variable is always initialized in a
5107 ** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
5108 ** regardless of the success or failure of this routine.
5109 **
5110 ** ^(If the row that a BLOB handle points to is modified by an
5111 ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
5112 ** then the BLOB handle is marked as "expired".
5113 ** This is true if any column of the row is changed, even a column
5114 ** other than the one the BLOB handle is open on.)^
5115 ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
5116 ** a expired BLOB handle fail with an return code of [SQLITE_ABORT].
5117 ** ^(Changes written into a BLOB prior to the BLOB expiring are not
5118 ** rolled back by the expiration of the BLOB.  Such changes will eventually
5119 ** commit if the transaction continues to completion.)^
5120 **
5121 ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
5122 ** the opened blob.  ^The size of a blob may not be changed by this
5123 ** interface.  Use the [UPDATE] SQL command to change the size of a
5124 ** blob.
5125 **
5126 ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
5127 ** and the built-in [zeroblob] SQL function can be used, if desired,
5128 ** to create an empty, zero-filled blob in which to read or write using
5129 ** this interface.
5130 **
5131 ** To avoid a resource leak, every open [BLOB handle] should eventually
5132 ** be released by a call to [sqlite3_blob_close()].
5133 */
5134 SQLITE_API int sqlite3_blob_open(
5135   sqlite3*,
5136   const char *zDb,
5137   const char *zTable,
5138   const char *zColumn,
5139   sqlite3_int64 iRow,
5140   int flags,
5141   sqlite3_blob **ppBlob
5142 );
5143
5144 /*
5145 ** CAPI3REF: Close A BLOB Handle
5146 **
5147 ** ^Closes an open [BLOB handle].
5148 **
5149 ** ^Closing a BLOB shall cause the current transaction to commit
5150 ** if there are no other BLOBs, no pending prepared statements, and the
5151 ** database connection is in [autocommit mode].
5152 ** ^If any writes were made to the BLOB, they might be held in cache
5153 ** until the close operation if they will fit.
5154 **
5155 ** ^(Closing the BLOB often forces the changes
5156 ** out to disk and so if any I/O errors occur, they will likely occur
5157 ** at the time when the BLOB is closed.  Any errors that occur during
5158 ** closing are reported as a non-zero return value.)^
5159 **
5160 ** ^(The BLOB is closed unconditionally.  Even if this routine returns
5161 ** an error code, the BLOB is still closed.)^
5162 **
5163 ** ^Calling this routine with a null pointer (such as would be returned
5164 ** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
5165 */
5166 SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
5167
5168 /*
5169 ** CAPI3REF: Return The Size Of An Open BLOB
5170 **
5171 ** ^Returns the size in bytes of the BLOB accessible via the 
5172 ** successfully opened [BLOB handle] in its only argument.  ^The
5173 ** incremental blob I/O routines can only read or overwriting existing
5174 ** blob content; they cannot change the size of a blob.
5175 **
5176 ** This routine only works on a [BLOB handle] which has been created
5177 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5178 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5179 ** to this routine results in undefined and probably undesirable behavior.
5180 */
5181 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
5182
5183 /*
5184 ** CAPI3REF: Read Data From A BLOB Incrementally
5185 **
5186 ** ^(This function is used to read data from an open [BLOB handle] into a
5187 ** caller-supplied buffer. N bytes of data are copied into buffer Z
5188 ** from the open BLOB, starting at offset iOffset.)^
5189 **
5190 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
5191 ** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is
5192 ** less than zero, [SQLITE_ERROR] is returned and no data is read.
5193 ** ^The size of the blob (and hence the maximum value of N+iOffset)
5194 ** can be determined using the [sqlite3_blob_bytes()] interface.
5195 **
5196 ** ^An attempt to read from an expired [BLOB handle] fails with an
5197 ** error code of [SQLITE_ABORT].
5198 **
5199 ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
5200 ** Otherwise, an [error code] or an [extended error code] is returned.)^
5201 **
5202 ** This routine only works on a [BLOB handle] which has been created
5203 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5204 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5205 ** to this routine results in undefined and probably undesirable behavior.
5206 **
5207 ** See also: [sqlite3_blob_write()].
5208 */
5209 SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
5210
5211 /*
5212 ** CAPI3REF: Write Data Into A BLOB Incrementally
5213 **
5214 ** ^This function is used to write data into an open [BLOB handle] from a
5215 ** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
5216 ** into the open BLOB, starting at offset iOffset.
5217 **
5218 ** ^If the [BLOB handle] passed as the first argument was not opened for
5219 ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
5220 ** this function returns [SQLITE_READONLY].
5221 **
5222 ** ^This function may only modify the contents of the BLOB; it is
5223 ** not possible to increase the size of a BLOB using this API.
5224 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
5225 ** [SQLITE_ERROR] is returned and no data is written.  ^If N is
5226 ** less than zero [SQLITE_ERROR] is returned and no data is written.
5227 ** The size of the BLOB (and hence the maximum value of N+iOffset)
5228 ** can be determined using the [sqlite3_blob_bytes()] interface.
5229 **
5230 ** ^An attempt to write to an expired [BLOB handle] fails with an
5231 ** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred
5232 ** before the [BLOB handle] expired are not rolled back by the
5233 ** expiration of the handle, though of course those changes might
5234 ** have been overwritten by the statement that expired the BLOB handle
5235 ** or by other independent statements.
5236 **
5237 ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
5238 ** Otherwise, an  [error code] or an [extended error code] is returned.)^
5239 **
5240 ** This routine only works on a [BLOB handle] which has been created
5241 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5242 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5243 ** to this routine results in undefined and probably undesirable behavior.
5244 **
5245 ** See also: [sqlite3_blob_read()].
5246 */
5247 SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
5248
5249 /*
5250 ** CAPI3REF: Virtual File System Objects
5251 **
5252 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
5253 ** that SQLite uses to interact
5254 ** with the underlying operating system.  Most SQLite builds come with a
5255 ** single default VFS that is appropriate for the host computer.
5256 ** New VFSes can be registered and existing VFSes can be unregistered.
5257 ** The following interfaces are provided.
5258 **
5259 ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
5260 ** ^Names are case sensitive.
5261 ** ^Names are zero-terminated UTF-8 strings.
5262 ** ^If there is no match, a NULL pointer is returned.
5263 ** ^If zVfsName is NULL then the default VFS is returned.
5264 **
5265 ** ^New VFSes are registered with sqlite3_vfs_register().
5266 ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
5267 ** ^The same VFS can be registered multiple times without injury.
5268 ** ^To make an existing VFS into the default VFS, register it again
5269 ** with the makeDflt flag set.  If two different VFSes with the
5270 ** same name are registered, the behavior is undefined.  If a
5271 ** VFS is registered with a name that is NULL or an empty string,
5272 ** then the behavior is undefined.
5273 **
5274 ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
5275 ** ^(If the default VFS is unregistered, another VFS is chosen as
5276 ** the default.  The choice for the new VFS is arbitrary.)^
5277 */
5278 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
5279 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
5280 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
5281
5282 /*
5283 ** CAPI3REF: Mutexes
5284 **
5285 ** The SQLite core uses these routines for thread
5286 ** synchronization. Though they are intended for internal
5287 ** use by SQLite, code that links against SQLite is
5288 ** permitted to use any of these routines.
5289 **
5290 ** The SQLite source code contains multiple implementations
5291 ** of these mutex routines.  An appropriate implementation
5292 ** is selected automatically at compile-time.  ^(The following
5293 ** implementations are available in the SQLite core:
5294 **
5295 ** <ul>
5296 ** <li>   SQLITE_MUTEX_OS2
5297 ** <li>   SQLITE_MUTEX_PTHREAD
5298 ** <li>   SQLITE_MUTEX_W32
5299 ** <li>   SQLITE_MUTEX_NOOP
5300 ** </ul>)^
5301 **
5302 ** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
5303 ** that does no real locking and is appropriate for use in
5304 ** a single-threaded application.  ^The SQLITE_MUTEX_OS2,
5305 ** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations
5306 ** are appropriate for use on OS/2, Unix, and Windows.
5307 **
5308 ** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
5309 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
5310 ** implementation is included with the library. In this case the
5311 ** application must supply a custom mutex implementation using the
5312 ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
5313 ** before calling sqlite3_initialize() or any other public sqlite3_
5314 ** function that calls sqlite3_initialize().)^
5315 **
5316 ** ^The sqlite3_mutex_alloc() routine allocates a new
5317 ** mutex and returns a pointer to it. ^If it returns NULL
5318 ** that means that a mutex could not be allocated.  ^SQLite
5319 ** will unwind its stack and return an error.  ^(The argument
5320 ** to sqlite3_mutex_alloc() is one of these integer constants:
5321 **
5322 ** <ul>
5323 ** <li>  SQLITE_MUTEX_FAST
5324 ** <li>  SQLITE_MUTEX_RECURSIVE
5325 ** <li>  SQLITE_MUTEX_STATIC_MASTER
5326 ** <li>  SQLITE_MUTEX_STATIC_MEM
5327 ** <li>  SQLITE_MUTEX_STATIC_MEM2
5328 ** <li>  SQLITE_MUTEX_STATIC_PRNG
5329 ** <li>  SQLITE_MUTEX_STATIC_LRU
5330 ** <li>  SQLITE_MUTEX_STATIC_LRU2
5331 ** </ul>)^
5332 **
5333 ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
5334 ** cause sqlite3_mutex_alloc() to create
5335 ** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
5336 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
5337 ** The mutex implementation does not need to make a distinction
5338 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
5339 ** not want to.  ^SQLite will only request a recursive mutex in
5340 ** cases where it really needs one.  ^If a faster non-recursive mutex
5341 ** implementation is available on the host platform, the mutex subsystem
5342 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
5343 **
5344 ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
5345 ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
5346 ** a pointer to a static preexisting mutex.  ^Six static mutexes are
5347 ** used by the current version of SQLite.  Future versions of SQLite
5348 ** may add additional static mutexes.  Static mutexes are for internal
5349 ** use by SQLite only.  Applications that use SQLite mutexes should
5350 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
5351 ** SQLITE_MUTEX_RECURSIVE.
5352 **
5353 ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
5354 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
5355 ** returns a different mutex on every call.  ^But for the static
5356 ** mutex types, the same mutex is returned on every call that has
5357 ** the same type number.
5358 **
5359 ** ^The sqlite3_mutex_free() routine deallocates a previously
5360 ** allocated dynamic mutex.  ^SQLite is careful to deallocate every
5361 ** dynamic mutex that it allocates.  The dynamic mutexes must not be in
5362 ** use when they are deallocated.  Attempting to deallocate a static
5363 ** mutex results in undefined behavior.  ^SQLite never deallocates
5364 ** a static mutex.
5365 **
5366 ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
5367 ** to enter a mutex.  ^If another thread is already within the mutex,
5368 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
5369 ** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
5370 ** upon successful entry.  ^(Mutexes created using
5371 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
5372 ** In such cases the,
5373 ** mutex must be exited an equal number of times before another thread
5374 ** can enter.)^  ^(If the same thread tries to enter any other
5375 ** kind of mutex more than once, the behavior is undefined.
5376 ** SQLite will never exhibit
5377 ** such behavior in its own use of mutexes.)^
5378 **
5379 ** ^(Some systems (for example, Windows 95) do not support the operation
5380 ** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
5381 ** will always return SQLITE_BUSY.  The SQLite core only ever uses
5382 ** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
5383 **
5384 ** ^The sqlite3_mutex_leave() routine exits a mutex that was
5385 ** previously entered by the same thread.   ^(The behavior
5386 ** is undefined if the mutex is not currently entered by the
5387 ** calling thread or is not currently allocated.  SQLite will
5388 ** never do either.)^
5389 **
5390 ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
5391 ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
5392 ** behave as no-ops.
5393 **
5394 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
5395 */
5396 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
5397 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
5398 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
5399 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
5400 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
5401
5402 /*
5403 ** CAPI3REF: Mutex Methods Object
5404 **
5405 ** An instance of this structure defines the low-level routines
5406 ** used to allocate and use mutexes.
5407 **
5408 ** Usually, the default mutex implementations provided by SQLite are
5409 ** sufficient, however the user has the option of substituting a custom
5410 ** implementation for specialized deployments or systems for which SQLite
5411 ** does not provide a suitable implementation. In this case, the user
5412 ** creates and populates an instance of this structure to pass
5413 ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
5414 ** Additionally, an instance of this structure can be used as an
5415 ** output variable when querying the system for the current mutex
5416 ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
5417 **
5418 ** ^The xMutexInit method defined by this structure is invoked as
5419 ** part of system initialization by the sqlite3_initialize() function.
5420 ** ^The xMutexInit routine is calle by SQLite exactly once for each
5421 ** effective call to [sqlite3_initialize()].
5422 **
5423 ** ^The xMutexEnd method defined by this structure is invoked as
5424 ** part of system shutdown by the sqlite3_shutdown() function. The
5425 ** implementation of this method is expected to release all outstanding
5426 ** resources obtained by the mutex methods implementation, especially
5427 ** those obtained by the xMutexInit method.  ^The xMutexEnd()
5428 ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
5429 **
5430 ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
5431 ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
5432 ** xMutexNotheld) implement the following interfaces (respectively):
5433 **
5434 ** <ul>
5435 **   <li>  [sqlite3_mutex_alloc()] </li>
5436 **   <li>  [sqlite3_mutex_free()] </li>
5437 **   <li>  [sqlite3_mutex_enter()] </li>
5438 **   <li>  [sqlite3_mutex_try()] </li>
5439 **   <li>  [sqlite3_mutex_leave()] </li>
5440 **   <li>  [sqlite3_mutex_held()] </li>
5441 **   <li>  [sqlite3_mutex_notheld()] </li>
5442 ** </ul>)^
5443 **
5444 ** The only difference is that the public sqlite3_XXX functions enumerated
5445 ** above silently ignore any invocations that pass a NULL pointer instead
5446 ** of a valid mutex handle. The implementations of the methods defined
5447 ** by this structure are not required to handle this case, the results
5448 ** of passing a NULL pointer instead of a valid mutex handle are undefined
5449 ** (i.e. it is acceptable to provide an implementation that segfaults if
5450 ** it is passed a NULL pointer).
5451 **
5452 ** The xMutexInit() method must be threadsafe.  ^It must be harmless to
5453 ** invoke xMutexInit() mutiple times within the same process and without
5454 ** intervening calls to xMutexEnd().  Second and subsequent calls to
5455 ** xMutexInit() must be no-ops.
5456 **
5457 ** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
5458 ** and its associates).  ^Similarly, xMutexAlloc() must not use SQLite memory
5459 ** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite
5460 ** memory allocation for a fast or recursive mutex.
5461 **
5462 ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
5463 ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
5464 ** If xMutexInit fails in any way, it is expected to clean up after itself
5465 ** prior to returning.
5466 */
5467 typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
5468 struct sqlite3_mutex_methods {
5469   int (*xMutexInit)(void);
5470   int (*xMutexEnd)(void);
5471   sqlite3_mutex *(*xMutexAlloc)(int);
5472   void (*xMutexFree)(sqlite3_mutex *);
5473   void (*xMutexEnter)(sqlite3_mutex *);
5474   int (*xMutexTry)(sqlite3_mutex *);
5475   void (*xMutexLeave)(sqlite3_mutex *);
5476   int (*xMutexHeld)(sqlite3_mutex *);
5477   int (*xMutexNotheld)(sqlite3_mutex *);
5478 };
5479
5480 /*
5481 ** CAPI3REF: Mutex Verification Routines
5482 **
5483 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
5484 ** are intended for use inside assert() statements.  ^The SQLite core
5485 ** never uses these routines except inside an assert() and applications
5486 ** are advised to follow the lead of the core.  ^The SQLite core only
5487 ** provides implementations for these routines when it is compiled
5488 ** with the SQLITE_DEBUG flag.  ^External mutex implementations
5489 ** are only required to provide these routines if SQLITE_DEBUG is
5490 ** defined and if NDEBUG is not defined.
5491 **
5492 ** ^These routines should return true if the mutex in their argument
5493 ** is held or not held, respectively, by the calling thread.
5494 **
5495 ** ^The implementation is not required to provided versions of these
5496 ** routines that actually work. If the implementation does not provide working
5497 ** versions of these routines, it should at least provide stubs that always
5498 ** return true so that one does not get spurious assertion failures.
5499 **
5500 ** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
5501 ** the routine should return 1.   This seems counter-intuitive since
5502 ** clearly the mutex cannot be held if it does not exist.  But the
5503 ** the reason the mutex does not exist is because the build is not
5504 ** using mutexes.  And we do not want the assert() containing the
5505 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
5506 ** the appropriate thing to do.  ^The sqlite3_mutex_notheld()
5507 ** interface should also return 1 when given a NULL pointer.
5508 */
5509 #ifndef NDEBUG
5510 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
5511 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
5512 #endif
5513
5514 /*
5515 ** CAPI3REF: Mutex Types
5516 **
5517 ** The [sqlite3_mutex_alloc()] interface takes a single argument
5518 ** which is one of these integer constants.
5519 **
5520 ** The set of static mutexes may change from one SQLite release to the
5521 ** next.  Applications that override the built-in mutex logic must be
5522 ** prepared to accommodate additional static mutexes.
5523 */
5524 #define SQLITE_MUTEX_FAST             0
5525 #define SQLITE_MUTEX_RECURSIVE        1
5526 #define SQLITE_MUTEX_STATIC_MASTER    2
5527 #define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
5528 #define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */
5529 #define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */
5530 #define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
5531 #define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
5532 #define SQLITE_MUTEX_STATIC_LRU2      7  /* lru page list */
5533
5534 /*
5535 ** CAPI3REF: Retrieve the mutex for a database connection
5536 **
5537 ** ^This interface returns a pointer the [sqlite3_mutex] object that 
5538 ** serializes access to the [database connection] given in the argument
5539 ** when the [threading mode] is Serialized.
5540 ** ^If the [threading mode] is Single-thread or Multi-thread then this
5541 ** routine returns a NULL pointer.
5542 */
5543 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
5544
5545 /*
5546 ** CAPI3REF: Low-Level Control Of Database Files
5547 **
5548 ** ^The [sqlite3_file_control()] interface makes a direct call to the
5549 ** xFileControl method for the [sqlite3_io_methods] object associated
5550 ** with a particular database identified by the second argument. ^The
5551 ** name of the database "main" for the main database or "temp" for the
5552 ** TEMP database, or the name that appears after the AS keyword for
5553 ** databases that are added using the [ATTACH] SQL command.
5554 ** ^A NULL pointer can be used in place of "main" to refer to the
5555 ** main database file.
5556 ** ^The third and fourth parameters to this routine
5557 ** are passed directly through to the second and third parameters of
5558 ** the xFileControl method.  ^The return value of the xFileControl
5559 ** method becomes the return value of this routine.
5560 **
5561 ** ^If the second parameter (zDbName) does not match the name of any
5562 ** open database file, then SQLITE_ERROR is returned.  ^This error
5563 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
5564 ** or [sqlite3_errmsg()].  The underlying xFileControl method might
5565 ** also return SQLITE_ERROR.  There is no way to distinguish between
5566 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
5567 ** xFileControl method.
5568 **
5569 ** See also: [SQLITE_FCNTL_LOCKSTATE]
5570 */
5571 SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
5572
5573 /*
5574 ** CAPI3REF: Testing Interface
5575 **
5576 ** ^The sqlite3_test_control() interface is used to read out internal
5577 ** state of SQLite and to inject faults into SQLite for testing
5578 ** purposes.  ^The first parameter is an operation code that determines
5579 ** the number, meaning, and operation of all subsequent parameters.
5580 **
5581 ** This interface is not for use by applications.  It exists solely
5582 ** for verifying the correct operation of the SQLite library.  Depending
5583 ** on how the SQLite library is compiled, this interface might not exist.
5584 **
5585 ** The details of the operation codes, their meanings, the parameters
5586 ** they take, and what they do are all subject to change without notice.
5587 ** Unlike most of the SQLite API, this function is not guaranteed to
5588 ** operate consistently from one release to the next.
5589 */
5590 SQLITE_API int sqlite3_test_control(int op, ...);
5591
5592 /*
5593 ** CAPI3REF: Testing Interface Operation Codes
5594 **
5595 ** These constants are the valid operation code parameters used
5596 ** as the first argument to [sqlite3_test_control()].
5597 **
5598 ** These parameters and their meanings are subject to change
5599 ** without notice.  These values are for testing purposes only.
5600 ** Applications should not use any of these parameters or the
5601 ** [sqlite3_test_control()] interface.
5602 */
5603 #define SQLITE_TESTCTRL_FIRST                    5
5604 #define SQLITE_TESTCTRL_PRNG_SAVE                5
5605 #define SQLITE_TESTCTRL_PRNG_RESTORE             6
5606 #define SQLITE_TESTCTRL_PRNG_RESET               7
5607 #define SQLITE_TESTCTRL_BITVEC_TEST              8
5608 #define SQLITE_TESTCTRL_FAULT_INSTALL            9
5609 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
5610 #define SQLITE_TESTCTRL_PENDING_BYTE            11
5611 #define SQLITE_TESTCTRL_ASSERT                  12
5612 #define SQLITE_TESTCTRL_ALWAYS                  13
5613 #define SQLITE_TESTCTRL_RESERVE                 14
5614 #define SQLITE_TESTCTRL_OPTIMIZATIONS           15
5615 #define SQLITE_TESTCTRL_ISKEYWORD               16
5616 #define SQLITE_TESTCTRL_PGHDRSZ                 17
5617 #define SQLITE_TESTCTRL_LAST                    17
5618
5619 /*
5620 ** CAPI3REF: SQLite Runtime Status
5621 **
5622 ** ^This interface is used to retrieve runtime status information
5623 ** about the preformance of SQLite, and optionally to reset various
5624 ** highwater marks.  ^The first argument is an integer code for
5625 ** the specific parameter to measure.  ^(Recognized integer codes
5626 ** are of the form [SQLITE_STATUS_MEMORY_USED | SQLITE_STATUS_...].)^
5627 ** ^The current value of the parameter is returned into *pCurrent.
5628 ** ^The highest recorded value is returned in *pHighwater.  ^If the
5629 ** resetFlag is true, then the highest record value is reset after
5630 ** *pHighwater is written.  ^(Some parameters do not record the highest
5631 ** value.  For those parameters
5632 ** nothing is written into *pHighwater and the resetFlag is ignored.)^
5633 ** ^(Other parameters record only the highwater mark and not the current
5634 ** value.  For these latter parameters nothing is written into *pCurrent.)^
5635 **
5636 ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
5637 ** non-zero [error code] on failure.
5638 **
5639 ** This routine is threadsafe but is not atomic.  This routine can be
5640 ** called while other threads are running the same or different SQLite
5641 ** interfaces.  However the values returned in *pCurrent and
5642 ** *pHighwater reflect the status of SQLite at different points in time
5643 ** and it is possible that another thread might change the parameter
5644 ** in between the times when *pCurrent and *pHighwater are written.
5645 **
5646 ** See also: [sqlite3_db_status()]
5647 */
5648 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
5649
5650
5651 /*
5652 ** CAPI3REF: Status Parameters
5653 **
5654 ** These integer constants designate various run-time status parameters
5655 ** that can be returned by [sqlite3_status()].
5656 **
5657 ** <dl>
5658 ** ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
5659 ** <dd>This parameter is the current amount of memory checked out
5660 ** using [sqlite3_malloc()], either directly or indirectly.  The
5661 ** figure includes calls made to [sqlite3_malloc()] by the application
5662 ** and internal memory usage by the SQLite library.  Scratch memory
5663 ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
5664 ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
5665 ** this parameter.  The amount returned is the sum of the allocation
5666 ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
5667 **
5668 ** ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
5669 ** <dd>This parameter records the largest memory allocation request
5670 ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
5671 ** internal equivalents).  Only the value returned in the
5672 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
5673 ** The value written into the *pCurrent parameter is undefined.</dd>)^
5674 **
5675 ** ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
5676 ** <dd>This parameter returns the number of pages used out of the
5677 ** [pagecache memory allocator] that was configured using 
5678 ** [SQLITE_CONFIG_PAGECACHE].  The
5679 ** value returned is in pages, not in bytes.</dd>)^
5680 **
5681 ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
5682 ** <dd>This parameter returns the number of bytes of page cache
5683 ** allocation which could not be statisfied by the [SQLITE_CONFIG_PAGECACHE]
5684 ** buffer and where forced to overflow to [sqlite3_malloc()].  The
5685 ** returned value includes allocations that overflowed because they
5686 ** where too large (they were larger than the "sz" parameter to
5687 ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
5688 ** no space was left in the page cache.</dd>)^
5689 **
5690 ** ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
5691 ** <dd>This parameter records the largest memory allocation request
5692 ** handed to [pagecache memory allocator].  Only the value returned in the
5693 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
5694 ** The value written into the *pCurrent parameter is undefined.</dd>)^
5695 **
5696 ** ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
5697 ** <dd>This parameter returns the number of allocations used out of the
5698 ** [scratch memory allocator] configured using
5699 ** [SQLITE_CONFIG_SCRATCH].  The value returned is in allocations, not
5700 ** in bytes.  Since a single thread may only have one scratch allocation
5701 ** outstanding at time, this parameter also reports the number of threads
5702 ** using scratch memory at the same time.</dd>)^
5703 **
5704 ** ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
5705 ** <dd>This parameter returns the number of bytes of scratch memory
5706 ** allocation which could not be statisfied by the [SQLITE_CONFIG_SCRATCH]
5707 ** buffer and where forced to overflow to [sqlite3_malloc()].  The values
5708 ** returned include overflows because the requested allocation was too
5709 ** larger (that is, because the requested allocation was larger than the
5710 ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
5711 ** slots were available.
5712 ** </dd>)^
5713 **
5714 ** ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
5715 ** <dd>This parameter records the largest memory allocation request
5716 ** handed to [scratch memory allocator].  Only the value returned in the
5717 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
5718 ** The value written into the *pCurrent parameter is undefined.</dd>)^
5719 **
5720 ** ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
5721 ** <dd>This parameter records the deepest parser stack.  It is only
5722 ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
5723 ** </dl>
5724 **
5725 ** New status parameters may be added from time to time.
5726 */
5727 #define SQLITE_STATUS_MEMORY_USED          0
5728 #define SQLITE_STATUS_PAGECACHE_USED       1
5729 #define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
5730 #define SQLITE_STATUS_SCRATCH_USED         3
5731 #define SQLITE_STATUS_SCRATCH_OVERFLOW     4
5732 #define SQLITE_STATUS_MALLOC_SIZE          5
5733 #define SQLITE_STATUS_PARSER_STACK         6
5734 #define SQLITE_STATUS_PAGECACHE_SIZE       7
5735 #define SQLITE_STATUS_SCRATCH_SIZE         8
5736
5737 /*
5738 ** CAPI3REF: Database Connection Status
5739 **
5740 ** ^This interface is used to retrieve runtime status information 
5741 ** about a single [database connection].  ^The first argument is the
5742 ** database connection object to be interrogated.  ^The second argument
5743 ** is an integer constant, taken from the set of
5744 ** [SQLITE_DBSTATUS_LOOKASIDE_USED | SQLITE_DBSTATUS_*] macros, that
5745 ** determiness the parameter to interrogate.  The set of 
5746 ** [SQLITE_DBSTATUS_LOOKASIDE_USED | SQLITE_DBSTATUS_*] macros is likely
5747 ** to grow in future releases of SQLite.
5748 **
5749 ** ^The current value of the requested parameter is written into *pCur
5750 ** and the highest instantaneous value is written into *pHiwtr.  ^If
5751 ** the resetFlg is true, then the highest instantaneous value is
5752 ** reset back down to the current value.
5753 **
5754 ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
5755 */
5756 SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
5757
5758 /*
5759 ** CAPI3REF: Status Parameters for database connections
5760 **
5761 ** These constants are the available integer "verbs" that can be passed as
5762 ** the second argument to the [sqlite3_db_status()] interface.
5763 **
5764 ** New verbs may be added in future releases of SQLite. Existing verbs
5765 ** might be discontinued. Applications should check the return code from
5766 ** [sqlite3_db_status()] to make sure that the call worked.
5767 ** The [sqlite3_db_status()] interface will return a non-zero error code
5768 ** if a discontinued or unsupported verb is invoked.
5769 **
5770 ** <dl>
5771 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
5772 ** <dd>This parameter returns the number of lookaside memory slots currently
5773 ** checked out.</dd>)^
5774 **
5775 ** <dt>SQLITE_DBSTATUS_CACHE_USED</dt>
5776 ** <dd>^This parameter returns the approximate number of of bytes of heap
5777 ** memory used by all pager caches associated with the database connection.
5778 ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
5779 ** checked out.</dd>)^
5780 ** </dl>
5781 */
5782 #define SQLITE_DBSTATUS_LOOKASIDE_USED     0
5783 #define SQLITE_DBSTATUS_CACHE_USED         1
5784 #define SQLITE_DBSTATUS_MAX                1   /* Largest defined DBSTATUS */
5785
5786
5787 /*
5788 ** CAPI3REF: Prepared Statement Status
5789 **
5790 ** ^(Each prepared statement maintains various
5791 ** [SQLITE_STMTSTATUS_SORT | counters] that measure the number
5792 ** of times it has performed specific operations.)^  These counters can
5793 ** be used to monitor the performance characteristics of the prepared
5794 ** statements.  For example, if the number of table steps greatly exceeds
5795 ** the number of table searches or result rows, that would tend to indicate
5796 ** that the prepared statement is using a full table scan rather than
5797 ** an index.  
5798 **
5799 ** ^(This interface is used to retrieve and reset counter values from
5800 ** a [prepared statement].  The first argument is the prepared statement
5801 ** object to be interrogated.  The second argument
5802 ** is an integer code for a specific [SQLITE_STMTSTATUS_SORT | counter]
5803 ** to be interrogated.)^
5804 ** ^The current value of the requested counter is returned.
5805 ** ^If the resetFlg is true, then the counter is reset to zero after this
5806 ** interface call returns.
5807 **
5808 ** See also: [sqlite3_status()] and [sqlite3_db_status()].
5809 */
5810 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
5811
5812 /*
5813 ** CAPI3REF: Status Parameters for prepared statements
5814 **
5815 ** These preprocessor macros define integer codes that name counter
5816 ** values associated with the [sqlite3_stmt_status()] interface.
5817 ** The meanings of the various counters are as follows:
5818 **
5819 ** <dl>
5820 ** <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
5821 ** <dd>^This is the number of times that SQLite has stepped forward in
5822 ** a table as part of a full table scan.  Large numbers for this counter
5823 ** may indicate opportunities for performance improvement through 
5824 ** careful use of indices.</dd>
5825 **
5826 ** <dt>SQLITE_STMTSTATUS_SORT</dt>
5827 ** <dd>^This is the number of sort operations that have occurred.
5828 ** A non-zero value in this counter may indicate an opportunity to
5829 ** improvement performance through careful use of indices.</dd>
5830 **
5831 ** <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
5832 ** <dd>^This is the number of rows inserted into transient indices that
5833 ** were created automatically in order to help joins run faster.
5834 ** A non-zero value in this counter may indicate an opportunity to
5835 ** improvement performance by adding permanent indices that do not
5836 ** need to be reinitialized each time the statement is run.</dd>
5837 **
5838 ** </dl>
5839 */
5840 #define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
5841 #define SQLITE_STMTSTATUS_SORT              2
5842 #define SQLITE_STMTSTATUS_AUTOINDEX         3
5843
5844 /*
5845 ** CAPI3REF: Custom Page Cache Object
5846 **
5847 ** The sqlite3_pcache type is opaque.  It is implemented by
5848 ** the pluggable module.  The SQLite core has no knowledge of
5849 ** its size or internal structure and never deals with the
5850 ** sqlite3_pcache object except by holding and passing pointers
5851 ** to the object.
5852 **
5853 ** See [sqlite3_pcache_methods] for additional information.
5854 */
5855 typedef struct sqlite3_pcache sqlite3_pcache;
5856
5857 /*
5858 ** CAPI3REF: Application Defined Page Cache.
5859 ** KEYWORDS: {page cache}
5860 **
5861 ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE], ...) interface can
5862 ** register an alternative page cache implementation by passing in an 
5863 ** instance of the sqlite3_pcache_methods structure.)^ The majority of the 
5864 ** heap memory used by SQLite is used by the page cache to cache data read 
5865 ** from, or ready to be written to, the database file. By implementing a 
5866 ** custom page cache using this API, an application can control more 
5867 ** precisely the amount of memory consumed by SQLite, the way in which 
5868 ** that memory is allocated and released, and the policies used to 
5869 ** determine exactly which parts of a database file are cached and for 
5870 ** how long.
5871 **
5872 ** ^(The contents of the sqlite3_pcache_methods structure are copied to an
5873 ** internal buffer by SQLite within the call to [sqlite3_config].  Hence
5874 ** the application may discard the parameter after the call to
5875 ** [sqlite3_config()] returns.)^
5876 **
5877 ** ^The xInit() method is called once for each call to [sqlite3_initialize()]
5878 ** (usually only once during the lifetime of the process). ^(The xInit()
5879 ** method is passed a copy of the sqlite3_pcache_methods.pArg value.)^
5880 ** ^The xInit() method can set up up global structures and/or any mutexes
5881 ** required by the custom page cache implementation. 
5882 **
5883 ** ^The xShutdown() method is called from within [sqlite3_shutdown()], 
5884 ** if the application invokes this API. It can be used to clean up 
5885 ** any outstanding resources before process shutdown, if required.
5886 **
5887 ** ^SQLite holds a [SQLITE_MUTEX_RECURSIVE] mutex when it invokes
5888 ** the xInit method, so the xInit method need not be threadsafe.  ^The
5889 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
5890 ** not need to be threadsafe either.  All other methods must be threadsafe
5891 ** in multithreaded applications.
5892 **
5893 ** ^SQLite will never invoke xInit() more than once without an intervening
5894 ** call to xShutdown().
5895 **
5896 ** ^The xCreate() method is used to construct a new cache instance.  SQLite
5897 ** will typically create one cache instance for each open database file,
5898 ** though this is not guaranteed. ^The
5899 ** first parameter, szPage, is the size in bytes of the pages that must
5900 ** be allocated by the cache.  ^szPage will not be a power of two.  ^szPage
5901 ** will the page size of the database file that is to be cached plus an
5902 ** increment (here called "R") of about 100 or 200.  ^SQLite will use the
5903 ** extra R bytes on each page to store metadata about the underlying
5904 ** database page on disk.  The value of R depends
5905 ** on the SQLite version, the target platform, and how SQLite was compiled.
5906 ** ^R is constant for a particular build of SQLite.  ^The second argument to
5907 ** xCreate(), bPurgeable, is true if the cache being created will
5908 ** be used to cache database pages of a file stored on disk, or
5909 ** false if it is used for an in-memory database. ^The cache implementation
5910 ** does not have to do anything special based with the value of bPurgeable;
5911 ** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
5912 ** never invoke xUnpin() except to deliberately delete a page.
5913 ** ^In other words, a cache created with bPurgeable set to false will
5914 ** never contain any unpinned pages.
5915 **
5916 ** ^(The xCachesize() method may be called at any time by SQLite to set the
5917 ** suggested maximum cache-size (number of pages stored by) the cache
5918 ** instance passed as the first argument. This is the value configured using
5919 ** the SQLite "[PRAGMA cache_size]" command.)^  ^As with the bPurgeable
5920 ** parameter, the implementation is not required to do anything with this
5921 ** value; it is advisory only.
5922 **
5923 ** ^The xPagecount() method should return the number of pages currently
5924 ** stored in the cache.
5925 ** 
5926 ** ^The xFetch() method is used to fetch a page and return a pointer to it. 
5927 ** ^A 'page', in this context, is a buffer of szPage bytes aligned at an
5928 ** 8-byte boundary. ^The page to be fetched is determined by the key. ^The
5929 ** mimimum key value is 1. After it has been retrieved using xFetch, the page 
5930 ** is considered to be "pinned".
5931 **
5932 ** ^If the requested page is already in the page cache, then the page cache
5933 ** implementation must return a pointer to the page buffer with its content
5934 ** intact.  ^(If the requested page is not already in the cache, then the
5935 ** behavior of the cache implementation is determined by the value of the
5936 ** createFlag parameter passed to xFetch, according to the following table:
5937 **
5938 ** <table border=1 width=85% align=center>
5939 ** <tr><th> createFlag <th> Behaviour when page is not already in cache
5940 ** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.
5941 ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
5942 **                 Otherwise return NULL.
5943 ** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return
5944 **                 NULL if allocating a new page is effectively impossible.
5945 ** </table>)^
5946 **
5947 ** SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  If
5948 ** a call to xFetch() with createFlag==1 returns NULL, then SQLite will
5949 ** attempt to unpin one or more cache pages by spilling the content of
5950 ** pinned pages to disk and synching the operating system disk cache. After
5951 ** attempting to unpin pages, the xFetch() method will be invoked again with
5952 ** a createFlag of 2.
5953 **
5954 ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
5955 ** as its second argument. ^(If the third parameter, discard, is non-zero,
5956 ** then the page should be evicted from the cache. In this case SQLite 
5957 ** assumes that the next time the page is retrieved from the cache using
5958 ** the xFetch() method, it will be zeroed.)^ ^If the discard parameter is
5959 ** zero, then the page is considered to be unpinned. ^The cache implementation
5960 ** may choose to evict unpinned pages at any time.
5961 **
5962 ** ^(The cache is not required to perform any reference counting. A single 
5963 ** call to xUnpin() unpins the page regardless of the number of prior calls 
5964 ** to xFetch().)^
5965 **
5966 ** ^The xRekey() method is used to change the key value associated with the
5967 ** page passed as the second argument from oldKey to newKey. ^If the cache
5968 ** previously contains an entry associated with newKey, it should be
5969 ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
5970 ** to be pinned.
5971 **
5972 ** ^When SQLite calls the xTruncate() method, the cache must discard all
5973 ** existing cache entries with page numbers (keys) greater than or equal
5974 ** to the value of the iLimit parameter passed to xTruncate(). ^If any
5975 ** of these pages are pinned, they are implicitly unpinned, meaning that
5976 ** they can be safely discarded.
5977 **
5978 ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
5979 ** All resources associated with the specified cache should be freed. ^After
5980 ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
5981 ** handle invalid, and will not use it with any other sqlite3_pcache_methods
5982 ** functions.
5983 */
5984 typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
5985 struct sqlite3_pcache_methods {
5986   void *pArg;
5987   int (*xInit)(void*);
5988   void (*xShutdown)(void*);
5989   sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
5990   void (*xCachesize)(sqlite3_pcache*, int nCachesize);
5991   int (*xPagecount)(sqlite3_pcache*);
5992   void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
5993   void (*xUnpin)(sqlite3_pcache*, void*, int discard);
5994   void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
5995   void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
5996   void (*xDestroy)(sqlite3_pcache*);
5997 };
5998
5999 /*
6000 ** CAPI3REF: Online Backup Object
6001 **
6002 ** The sqlite3_backup object records state information about an ongoing
6003 ** online backup operation.  ^The sqlite3_backup object is created by
6004 ** a call to [sqlite3_backup_init()] and is destroyed by a call to
6005 ** [sqlite3_backup_finish()].
6006 **
6007 ** See Also: [Using the SQLite Online Backup API]
6008 */
6009 typedef struct sqlite3_backup sqlite3_backup;
6010
6011 /*
6012 ** CAPI3REF: Online Backup API.
6013 **
6014 ** The backup API copies the content of one database into another.
6015 ** It is useful either for creating backups of databases or
6016 ** for copying in-memory databases to or from persistent files. 
6017 **
6018 ** See Also: [Using the SQLite Online Backup API]
6019 **
6020 ** ^Exclusive access is required to the destination database for the 
6021 ** duration of the operation. ^However the source database is only
6022 ** read-locked while it is actually being read; it is not locked
6023 ** continuously for the entire backup operation. ^Thus, the backup may be
6024 ** performed on a live source database without preventing other users from
6025 ** reading or writing to the source database while the backup is underway.
6026 ** 
6027 ** ^(To perform a backup operation: 
6028 **   <ol>
6029 **     <li><b>sqlite3_backup_init()</b> is called once to initialize the
6030 **         backup, 
6031 **     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer 
6032 **         the data between the two databases, and finally
6033 **     <li><b>sqlite3_backup_finish()</b> is called to release all resources 
6034 **         associated with the backup operation. 
6035 **   </ol>)^
6036 ** There should be exactly one call to sqlite3_backup_finish() for each
6037 ** successful call to sqlite3_backup_init().
6038 **
6039 ** <b>sqlite3_backup_init()</b>
6040 **
6041 ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the 
6042 ** [database connection] associated with the destination database 
6043 ** and the database name, respectively.
6044 ** ^The database name is "main" for the main database, "temp" for the
6045 ** temporary database, or the name specified after the AS keyword in
6046 ** an [ATTACH] statement for an attached database.
6047 ** ^The S and M arguments passed to 
6048 ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
6049 ** and database name of the source database, respectively.
6050 ** ^The source and destination [database connections] (parameters S and D)
6051 ** must be different or else sqlite3_backup_init(D,N,S,M) will file with
6052 ** an error.
6053 **
6054 ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
6055 ** returned and an error code and error message are store3d in the
6056 ** destination [database connection] D.
6057 ** ^The error code and message for the failed call to sqlite3_backup_init()
6058 ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
6059 ** [sqlite3_errmsg16()] functions.
6060 ** ^A successful call to sqlite3_backup_init() returns a pointer to an
6061 ** [sqlite3_backup] object.
6062 ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
6063 ** sqlite3_backup_finish() functions to perform the specified backup 
6064 ** operation.
6065 **
6066 ** <b>sqlite3_backup_step()</b>
6067 **
6068 ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between 
6069 ** the source and destination databases specified by [sqlite3_backup] object B.
6070 ** ^If N is negative, all remaining source pages are copied. 
6071 ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
6072 ** are still more pages to be copied, then the function resturns [SQLITE_OK].
6073 ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
6074 ** from source to destination, then it returns [SQLITE_DONE].
6075 ** ^If an error occurs while running sqlite3_backup_step(B,N),
6076 ** then an [error code] is returned. ^As well as [SQLITE_OK] and
6077 ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
6078 ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
6079 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
6080 **
6081 ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
6082 ** <ol>
6083 ** <li> the destination database was opened read-only, or
6084 ** <li> the destination database is using write-ahead-log journaling
6085 ** and the destination and source page sizes differ, or
6086 ** <li> The destination database is an in-memory database and the
6087 ** destination and source page sizes differ.
6088 ** </ol>)^
6089 **
6090 ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
6091 ** the [sqlite3_busy_handler | busy-handler function]
6092 ** is invoked (if one is specified). ^If the 
6093 ** busy-handler returns non-zero before the lock is available, then 
6094 ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
6095 ** sqlite3_backup_step() can be retried later. ^If the source
6096 ** [database connection]
6097 ** is being used to write to the source database when sqlite3_backup_step()
6098 ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
6099 ** case the call to sqlite3_backup_step() can be retried later on. ^(If
6100 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
6101 ** [SQLITE_READONLY] is returned, then 
6102 ** there is no point in retrying the call to sqlite3_backup_step(). These 
6103 ** errors are considered fatal.)^  The application must accept 
6104 ** that the backup operation has failed and pass the backup operation handle 
6105 ** to the sqlite3_backup_finish() to release associated resources.
6106 **
6107 ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
6108 ** on the destination file. ^The exclusive lock is not released until either 
6109 ** sqlite3_backup_finish() is called or the backup operation is complete 
6110 ** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to
6111 ** sqlite3_backup_step() obtains a [shared lock] on the source database that
6112 ** lasts for the duration of the sqlite3_backup_step() call.
6113 ** ^Because the source database is not locked between calls to
6114 ** sqlite3_backup_step(), the source database may be modified mid-way
6115 ** through the backup process.  ^If the source database is modified by an
6116 ** external process or via a database connection other than the one being
6117 ** used by the backup operation, then the backup will be automatically
6118 ** restarted by the next call to sqlite3_backup_step(). ^If the source 
6119 ** database is modified by the using the same database connection as is used
6120 ** by the backup operation, then the backup database is automatically
6121 ** updated at the same time.
6122 **
6123 ** <b>sqlite3_backup_finish()</b>
6124 **
6125 ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the 
6126 ** application wishes to abandon the backup operation, the application
6127 ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
6128 ** ^The sqlite3_backup_finish() interfaces releases all
6129 ** resources associated with the [sqlite3_backup] object. 
6130 ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
6131 ** active write-transaction on the destination database is rolled back.
6132 ** The [sqlite3_backup] object is invalid
6133 ** and may not be used following a call to sqlite3_backup_finish().
6134 **
6135 ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
6136 ** sqlite3_backup_step() errors occurred, regardless or whether or not
6137 ** sqlite3_backup_step() completed.
6138 ** ^If an out-of-memory condition or IO error occurred during any prior
6139 ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
6140 ** sqlite3_backup_finish() returns the corresponding [error code].
6141 **
6142 ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
6143 ** is not a permanent error and does not affect the return value of
6144 ** sqlite3_backup_finish().
6145 **
6146 ** <b>sqlite3_backup_remaining(), sqlite3_backup_pagecount()</b>
6147 **
6148 ** ^Each call to sqlite3_backup_step() sets two values inside
6149 ** the [sqlite3_backup] object: the number of pages still to be backed
6150 ** up and the total number of pages in the source databae file.
6151 ** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
6152 ** retrieve these two values, respectively.
6153 **
6154 ** ^The values returned by these functions are only updated by
6155 ** sqlite3_backup_step(). ^If the source database is modified during a backup
6156 ** operation, then the values are not updated to account for any extra
6157 ** pages that need to be updated or the size of the source database file
6158 ** changing.
6159 **
6160 ** <b>Concurrent Usage of Database Handles</b>
6161 **
6162 ** ^The source [database connection] may be used by the application for other
6163 ** purposes while a backup operation is underway or being initialized.
6164 ** ^If SQLite is compiled and configured to support threadsafe database
6165 ** connections, then the source database connection may be used concurrently
6166 ** from within other threads.
6167 **
6168 ** However, the application must guarantee that the destination 
6169 ** [database connection] is not passed to any other API (by any thread) after 
6170 ** sqlite3_backup_init() is called and before the corresponding call to
6171 ** sqlite3_backup_finish().  SQLite does not currently check to see
6172 ** if the application incorrectly accesses the destination [database connection]
6173 ** and so no error code is reported, but the operations may malfunction
6174 ** nevertheless.  Use of the destination database connection while a
6175 ** backup is in progress might also also cause a mutex deadlock.
6176 **
6177 ** If running in [shared cache mode], the application must
6178 ** guarantee that the shared cache used by the destination database
6179 ** is not accessed while the backup is running. In practice this means
6180 ** that the application must guarantee that the disk file being 
6181 ** backed up to is not accessed by any connection within the process,
6182 ** not just the specific connection that was passed to sqlite3_backup_init().
6183 **
6184 ** The [sqlite3_backup] object itself is partially threadsafe. Multiple 
6185 ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
6186 ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
6187 ** APIs are not strictly speaking threadsafe. If they are invoked at the
6188 ** same time as another thread is invoking sqlite3_backup_step() it is
6189 ** possible that they return invalid values.
6190 */
6191 SQLITE_API sqlite3_backup *sqlite3_backup_init(
6192   sqlite3 *pDest,                        /* Destination database handle */
6193   const char *zDestName,                 /* Destination database name */
6194   sqlite3 *pSource,                      /* Source database handle */
6195   const char *zSourceName                /* Source database name */
6196 );
6197 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
6198 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
6199 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
6200 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
6201
6202 /*
6203 ** CAPI3REF: Unlock Notification
6204 **
6205 ** ^When running in shared-cache mode, a database operation may fail with
6206 ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
6207 ** individual tables within the shared-cache cannot be obtained. See
6208 ** [SQLite Shared-Cache Mode] for a description of shared-cache locking. 
6209 ** ^This API may be used to register a callback that SQLite will invoke 
6210 ** when the connection currently holding the required lock relinquishes it.
6211 ** ^This API is only available if the library was compiled with the
6212 ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
6213 **
6214 ** See Also: [Using the SQLite Unlock Notification Feature].
6215 **
6216 ** ^Shared-cache locks are released when a database connection concludes
6217 ** its current transaction, either by committing it or rolling it back. 
6218 **
6219 ** ^When a connection (known as the blocked connection) fails to obtain a
6220 ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
6221 ** identity of the database connection (the blocking connection) that
6222 ** has locked the required resource is stored internally. ^After an 
6223 ** application receives an SQLITE_LOCKED error, it may call the
6224 ** sqlite3_unlock_notify() method with the blocked connection handle as 
6225 ** the first argument to register for a callback that will be invoked
6226 ** when the blocking connections current transaction is concluded. ^The
6227 ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
6228 ** call that concludes the blocking connections transaction.
6229 **
6230 ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
6231 ** there is a chance that the blocking connection will have already
6232 ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
6233 ** If this happens, then the specified callback is invoked immediately,
6234 ** from within the call to sqlite3_unlock_notify().)^
6235 **
6236 ** ^If the blocked connection is attempting to obtain a write-lock on a
6237 ** shared-cache table, and more than one other connection currently holds
6238 ** a read-lock on the same table, then SQLite arbitrarily selects one of 
6239 ** the other connections to use as the blocking connection.
6240 **
6241 ** ^(There may be at most one unlock-notify callback registered by a 
6242 ** blocked connection. If sqlite3_unlock_notify() is called when the
6243 ** blocked connection already has a registered unlock-notify callback,
6244 ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
6245 ** called with a NULL pointer as its second argument, then any existing
6246 ** unlock-notify callback is cancelled. ^The blocked connections 
6247 ** unlock-notify callback may also be canceled by closing the blocked
6248 ** connection using [sqlite3_close()].
6249 **
6250 ** The unlock-notify callback is not reentrant. If an application invokes
6251 ** any sqlite3_xxx API functions from within an unlock-notify callback, a
6252 ** crash or deadlock may be the result.
6253 **
6254 ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
6255 ** returns SQLITE_OK.
6256 **
6257 ** <b>Callback Invocation Details</b>
6258 **
6259 ** When an unlock-notify callback is registered, the application provides a 
6260 ** single void* pointer that is passed to the callback when it is invoked.
6261 ** However, the signature of the callback function allows SQLite to pass
6262 ** it an array of void* context pointers. The first argument passed to
6263 ** an unlock-notify callback is a pointer to an array of void* pointers,
6264 ** and the second is the number of entries in the array.
6265 **
6266 ** When a blocking connections transaction is concluded, there may be
6267 ** more than one blocked connection that has registered for an unlock-notify
6268 ** callback. ^If two or more such blocked connections have specified the
6269 ** same callback function, then instead of invoking the callback function
6270 ** multiple times, it is invoked once with the set of void* context pointers
6271 ** specified by the blocked connections bundled together into an array.
6272 ** This gives the application an opportunity to prioritize any actions 
6273 ** related to the set of unblocked database connections.
6274 **
6275 ** <b>Deadlock Detection</b>
6276 **
6277 ** Assuming that after registering for an unlock-notify callback a 
6278 ** database waits for the callback to be issued before taking any further
6279 ** action (a reasonable assumption), then using this API may cause the
6280 ** application to deadlock. For example, if connection X is waiting for
6281 ** connection Y's transaction to be concluded, and similarly connection
6282 ** Y is waiting on connection X's transaction, then neither connection
6283 ** will proceed and the system may remain deadlocked indefinitely.
6284 **
6285 ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
6286 ** detection. ^If a given call to sqlite3_unlock_notify() would put the
6287 ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
6288 ** unlock-notify callback is registered. The system is said to be in
6289 ** a deadlocked state if connection A has registered for an unlock-notify
6290 ** callback on the conclusion of connection B's transaction, and connection
6291 ** B has itself registered for an unlock-notify callback when connection
6292 ** A's transaction is concluded. ^Indirect deadlock is also detected, so
6293 ** the system is also considered to be deadlocked if connection B has
6294 ** registered for an unlock-notify callback on the conclusion of connection
6295 ** C's transaction, where connection C is waiting on connection A. ^Any
6296 ** number of levels of indirection are allowed.
6297 **
6298 ** <b>The "DROP TABLE" Exception</b>
6299 **
6300 ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost 
6301 ** always appropriate to call sqlite3_unlock_notify(). There is however,
6302 ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
6303 ** SQLite checks if there are any currently executing SELECT statements
6304 ** that belong to the same connection. If there are, SQLITE_LOCKED is
6305 ** returned. In this case there is no "blocking connection", so invoking
6306 ** sqlite3_unlock_notify() results in the unlock-notify callback being
6307 ** invoked immediately. If the application then re-attempts the "DROP TABLE"
6308 ** or "DROP INDEX" query, an infinite loop might be the result.
6309 **
6310 ** One way around this problem is to check the extended error code returned
6311 ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
6312 ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
6313 ** the special "DROP TABLE/INDEX" case, the extended error code is just 
6314 ** SQLITE_LOCKED.)^
6315 */
6316 SQLITE_API int sqlite3_unlock_notify(
6317   sqlite3 *pBlocked,                          /* Waiting connection */
6318   void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */
6319   void *pNotifyArg                            /* Argument to pass to xNotify */
6320 );
6321
6322
6323 /*
6324 ** CAPI3REF: String Comparison
6325 **
6326 ** ^The [sqlite3_strnicmp()] API allows applications and extensions to
6327 ** compare the contents of two buffers containing UTF-8 strings in a
6328 ** case-indendent fashion, using the same definition of case independence 
6329 ** that SQLite uses internally when comparing identifiers.
6330 */
6331 SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
6332
6333 /*
6334 ** CAPI3REF: Error Logging Interface
6335 **
6336 ** ^The [sqlite3_log()] interface writes a message into the error log
6337 ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
6338 ** ^If logging is enabled, the zFormat string and subsequent arguments are
6339 ** used with [sqlite3_snprintf()] to generate the final output string.
6340 **
6341 ** The sqlite3_log() interface is intended for use by extensions such as
6342 ** virtual tables, collating functions, and SQL functions.  While there is
6343 ** nothing to prevent an application from calling sqlite3_log(), doing so
6344 ** is considered bad form.
6345 **
6346 ** The zFormat string must not be NULL.
6347 **
6348 ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
6349 ** will not use dynamically allocated memory.  The log message is stored in
6350 ** a fixed-length buffer on the stack.  If the log message is longer than
6351 ** a few hundred characters, it will be truncated to the length of the
6352 ** buffer.
6353 */
6354 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
6355
6356 /*
6357 ** CAPI3REF: Write-Ahead Log Commit Hook
6358 **
6359 ** ^The [sqlite3_wal_hook()] function is used to register a callback that
6360 ** will be invoked each time a database connection commits data to a
6361 ** [write-ahead log] (i.e. whenever a transaction is committed in
6362 ** [journal_mode | journal_mode=WAL mode]). 
6363 **
6364 ** ^The callback is invoked by SQLite after the commit has taken place and 
6365 ** the associated write-lock on the database released, so the implementation 
6366 ** may read, write or [checkpoint] the database as required.
6367 **
6368 ** ^The first parameter passed to the callback function when it is invoked
6369 ** is a copy of the third parameter passed to sqlite3_wal_hook() when
6370 ** registering the callback. ^The second is a copy of the database handle.
6371 ** ^The third parameter is the name of the database that was written to -
6372 ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
6373 ** is the number of pages currently in the write-ahead log file,
6374 ** including those that were just committed.
6375 **
6376 ** The callback function should normally return [SQLITE_OK].  ^If an error
6377 ** code is returned, that error will propagate back up through the
6378 ** SQLite code base to cause the statement that provoked the callback
6379 ** to report an error, though the commit will have still occurred. If the
6380 ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
6381 ** that does not correspond to any valid SQLite error code, the results
6382 ** are undefined.
6383 **
6384 ** A single database handle may have at most a single write-ahead log callback 
6385 ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
6386 ** previously registered write-ahead log callback. ^Note that the
6387 ** [sqlite3_wal_autocheckpoint()] interface and the
6388 ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
6389 ** those overwrite any prior [sqlite3_wal_hook()] settings.
6390 */
6391 SQLITE_API void *sqlite3_wal_hook(
6392   sqlite3*, 
6393   int(*)(void *,sqlite3*,const char*,int),
6394   void*
6395 );
6396
6397 /*
6398 ** CAPI3REF: Configure an auto-checkpoint
6399 **
6400 ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
6401 ** [sqlite3_wal_hook()] that causes any database on [database connection] D
6402 ** to automatically [checkpoint]
6403 ** after committing a transaction if there are N or
6404 ** more frames in the [write-ahead log] file.  ^Passing zero or 
6405 ** a negative value as the nFrame parameter disables automatic
6406 ** checkpoints entirely.
6407 **
6408 ** ^The callback registered by this function replaces any existing callback
6409 ** registered using [sqlite3_wal_hook()].  ^Likewise, registering a callback
6410 ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
6411 ** configured by this function.
6412 **
6413 ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
6414 ** from SQL.
6415 **
6416 ** ^Every new [database connection] defaults to having the auto-checkpoint
6417 ** enabled with a threshold of 1000 pages.  The use of this interface
6418 ** is only necessary if the default setting is found to be suboptimal
6419 ** for a particular application.
6420 */
6421 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
6422
6423 /*
6424 ** CAPI3REF: Checkpoint a database
6425 **
6426 ** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X
6427 ** on [database connection] D to be [checkpointed].  ^If X is NULL or an
6428 ** empty string, then a checkpoint is run on all databases of
6429 ** connection D.  ^If the database connection D is not in
6430 ** [WAL | write-ahead log mode] then this interface is a harmless no-op.
6431 **
6432 ** ^The [wal_checkpoint pragma] can be used to invoke this interface
6433 ** from SQL.  ^The [sqlite3_wal_autocheckpoint()] interface and the
6434 ** [wal_autocheckpoint pragma] can be used to cause this interface to be
6435 ** run whenever the WAL reaches a certain size threshold.
6436 */
6437 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
6438
6439 /*
6440 ** Undo the hack that converts floating point types to integer for
6441 ** builds on processors without floating point support.
6442 */
6443 #ifdef SQLITE_OMIT_FLOATING_POINT
6444 # undef double
6445 #endif
6446
6447 #if 0
6448 }  /* End of the 'extern "C"' block */
6449 #endif
6450 #endif
6451
6452
6453 /************** End of sqlite3.h *********************************************/
6454 /************** Continuing where we left off in sqliteInt.h ******************/
6455 /************** Include hash.h in the middle of sqliteInt.h ******************/
6456 /************** Begin file hash.h ********************************************/
6457 /*
6458 ** 2001 September 22
6459 **
6460 ** The author disclaims copyright to this source code.  In place of
6461 ** a legal notice, here is a blessing:
6462 **
6463 **    May you do good and not evil.
6464 **    May you find forgiveness for yourself and forgive others.
6465 **    May you share freely, never taking more than you give.
6466 **
6467 *************************************************************************
6468 ** This is the header file for the generic hash-table implemenation
6469 ** used in SQLite.
6470 */
6471 #ifndef _SQLITE_HASH_H_
6472 #define _SQLITE_HASH_H_
6473
6474 /* Forward declarations of structures. */
6475 typedef struct Hash Hash;
6476 typedef struct HashElem HashElem;
6477
6478 /* A complete hash table is an instance of the following structure.
6479 ** The internals of this structure are intended to be opaque -- client
6480 ** code should not attempt to access or modify the fields of this structure
6481 ** directly.  Change this structure only by using the routines below.
6482 ** However, some of the "procedures" and "functions" for modifying and
6483 ** accessing this structure are really macros, so we can't really make
6484 ** this structure opaque.
6485 **
6486 ** All elements of the hash table are on a single doubly-linked list.
6487 ** Hash.first points to the head of this list.
6488 **
6489 ** There are Hash.htsize buckets.  Each bucket points to a spot in
6490 ** the global doubly-linked list.  The contents of the bucket are the
6491 ** element pointed to plus the next _ht.count-1 elements in the list.
6492 **
6493 ** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
6494 ** by a linear search of the global list.  For small tables, the 
6495 ** Hash.ht table is never allocated because if there are few elements
6496 ** in the table, it is faster to do a linear search than to manage
6497 ** the hash table.
6498 */
6499 struct Hash {
6500   unsigned int htsize;      /* Number of buckets in the hash table */
6501   unsigned int count;       /* Number of entries in this table */
6502   HashElem *first;          /* The first element of the array */
6503   struct _ht {              /* the hash table */
6504     int count;                 /* Number of entries with this hash */
6505     HashElem *chain;           /* Pointer to first entry with this hash */
6506   } *ht;
6507 };
6508
6509 /* Each element in the hash table is an instance of the following 
6510 ** structure.  All elements are stored on a single doubly-linked list.
6511 **
6512 ** Again, this structure is intended to be opaque, but it can't really
6513 ** be opaque because it is used by macros.
6514 */
6515 struct HashElem {
6516   HashElem *next, *prev;       /* Next and previous elements in the table */
6517   void *data;                  /* Data associated with this element */
6518   const char *pKey; int nKey;  /* Key associated with this element */
6519 };
6520
6521 /*
6522 ** Access routines.  To delete, insert a NULL pointer.
6523 */
6524 SQLITE_PRIVATE void sqlite3HashInit(Hash*);
6525 SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
6526 SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
6527 SQLITE_PRIVATE void sqlite3HashClear(Hash*);
6528
6529 /*
6530 ** Macros for looping over all elements of a hash table.  The idiom is
6531 ** like this:
6532 **
6533 **   Hash h;
6534 **   HashElem *p;
6535 **   ...
6536 **   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
6537 **     SomeStructure *pData = sqliteHashData(p);
6538 **     // do something with pData
6539 **   }
6540 */
6541 #define sqliteHashFirst(H)  ((H)->first)
6542 #define sqliteHashNext(E)   ((E)->next)
6543 #define sqliteHashData(E)   ((E)->data)
6544 /* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */
6545 /* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */
6546
6547 /*
6548 ** Number of entries in a hash table
6549 */
6550 /* #define sqliteHashCount(H)  ((H)->count) // NOT USED */
6551
6552 #endif /* _SQLITE_HASH_H_ */
6553
6554 /************** End of hash.h ************************************************/
6555 /************** Continuing where we left off in sqliteInt.h ******************/
6556 /************** Include parse.h in the middle of sqliteInt.h *****************/
6557 /************** Begin file parse.h *******************************************/
6558 #define TK_SEMI                            1
6559 #define TK_EXPLAIN                         2
6560 #define TK_QUERY                           3
6561 #define TK_PLAN                            4
6562 #define TK_BEGIN                           5
6563 #define TK_TRANSACTION                     6
6564 #define TK_DEFERRED                        7
6565 #define TK_IMMEDIATE                       8
6566 #define TK_EXCLUSIVE                       9
6567 #define TK_COMMIT                         10
6568 #define TK_END                            11
6569 #define TK_ROLLBACK                       12
6570 #define TK_SAVEPOINT                      13
6571 #define TK_RELEASE                        14
6572 #define TK_TO                             15
6573 #define TK_TABLE                          16
6574 #define TK_CREATE                         17
6575 #define TK_IF                             18
6576 #define TK_NOT                            19
6577 #define TK_EXISTS                         20
6578 #define TK_TEMP                           21
6579 #define TK_LP                             22
6580 #define TK_RP                             23
6581 #define TK_AS                             24
6582 #define TK_COMMA                          25
6583 #define TK_ID                             26
6584 #define TK_INDEXED                        27
6585 #define TK_ABORT                          28
6586 #define TK_ACTION                         29
6587 #define TK_AFTER                          30
6588 #define TK_ANALYZE                        31
6589 #define TK_ASC                            32
6590 #define TK_ATTACH                         33
6591 #define TK_BEFORE                         34
6592 #define TK_BY                             35
6593 #define TK_CASCADE                        36
6594 #define TK_CAST                           37
6595 #define TK_COLUMNKW                       38
6596 #define TK_CONFLICT                       39
6597 #define TK_DATABASE                       40
6598 #define TK_DESC                           41
6599 #define TK_DETACH                         42
6600 #define TK_EACH                           43
6601 #define TK_FAIL                           44
6602 #define TK_FOR                            45
6603 #define TK_IGNORE                         46
6604 #define TK_INITIALLY                      47
6605 #define TK_INSTEAD                        48
6606 #define TK_LIKE_KW                        49
6607 #define TK_MATCH                          50
6608 #define TK_NO                             51
6609 #define TK_KEY                            52
6610 #define TK_OF                             53
6611 #define TK_OFFSET                         54
6612 #define TK_PRAGMA                         55
6613 #define TK_RAISE                          56
6614 #define TK_REPLACE                        57
6615 #define TK_RESTRICT                       58
6616 #define TK_ROW                            59
6617 #define TK_TRIGGER                        60
6618 #define TK_VACUUM                         61
6619 #define TK_VIEW                           62
6620 #define TK_VIRTUAL                        63
6621 #define TK_REINDEX                        64
6622 #define TK_RENAME                         65
6623 #define TK_CTIME_KW                       66
6624 #define TK_ANY                            67
6625 #define TK_OR                             68
6626 #define TK_AND                            69
6627 #define TK_IS                             70
6628 #define TK_BETWEEN                        71
6629 #define TK_IN                             72
6630 #define TK_ISNULL                         73
6631 #define TK_NOTNULL                        74
6632 #define TK_NE                             75
6633 #define TK_EQ                             76
6634 #define TK_GT                             77
6635 #define TK_LE                             78
6636 #define TK_LT                             79
6637 #define TK_GE                             80
6638 #define TK_ESCAPE                         81
6639 #define TK_BITAND                         82
6640 #define TK_BITOR                          83
6641 #define TK_LSHIFT                         84
6642 #define TK_RSHIFT                         85
6643 #define TK_PLUS                           86
6644 #define TK_MINUS                          87
6645 #define TK_STAR                           88
6646 #define TK_SLASH                          89
6647 #define TK_REM                            90
6648 #define TK_CONCAT                         91
6649 #define TK_COLLATE                        92
6650 #define TK_BITNOT                         93
6651 #define TK_STRING                         94
6652 #define TK_JOIN_KW                        95
6653 #define TK_CONSTRAINT                     96
6654 #define TK_DEFAULT                        97
6655 #define TK_NULL                           98
6656 #define TK_PRIMARY                        99
6657 #define TK_UNIQUE                         100
6658 #define TK_CHECK                          101
6659 #define TK_REFERENCES                     102
6660 #define TK_AUTOINCR                       103
6661 #define TK_ON                             104
6662 #define TK_INSERT                         105
6663 #define TK_DELETE                         106
6664 #define TK_UPDATE                         107
6665 #define TK_SET                            108
6666 #define TK_DEFERRABLE                     109
6667 #define TK_FOREIGN                        110
6668 #define TK_DROP                           111
6669 #define TK_UNION                          112
6670 #define TK_ALL                            113
6671 #define TK_EXCEPT                         114
6672 #define TK_INTERSECT                      115
6673 #define TK_SELECT                         116
6674 #define TK_DISTINCT                       117
6675 #define TK_DOT                            118
6676 #define TK_FROM                           119
6677 #define TK_JOIN                           120
6678 #define TK_USING                          121
6679 #define TK_ORDER                          122
6680 #define TK_GROUP                          123
6681 #define TK_HAVING                         124
6682 #define TK_LIMIT                          125
6683 #define TK_WHERE                          126
6684 #define TK_INTO                           127
6685 #define TK_VALUES                         128
6686 #define TK_INTEGER                        129
6687 #define TK_FLOAT                          130
6688 #define TK_BLOB                           131
6689 #define TK_REGISTER                       132
6690 #define TK_VARIABLE                       133
6691 #define TK_CASE                           134
6692 #define TK_WHEN                           135
6693 #define TK_THEN                           136
6694 #define TK_ELSE                           137
6695 #define TK_INDEX                          138
6696 #define TK_ALTER                          139
6697 #define TK_ADD                            140
6698 #define TK_TO_TEXT                        141
6699 #define TK_TO_BLOB                        142
6700 #define TK_TO_NUMERIC                     143
6701 #define TK_TO_INT                         144
6702 #define TK_TO_REAL                        145
6703 #define TK_ISNOT                          146
6704 #define TK_END_OF_FILE                    147
6705 #define TK_ILLEGAL                        148
6706 #define TK_SPACE                          149
6707 #define TK_UNCLOSED_STRING                150
6708 #define TK_FUNCTION                       151
6709 #define TK_COLUMN                         152
6710 #define TK_AGG_FUNCTION                   153
6711 #define TK_AGG_COLUMN                     154
6712 #define TK_CONST_FUNC                     155
6713 #define TK_UMINUS                         156
6714 #define TK_UPLUS                          157
6715
6716 /************** End of parse.h ***********************************************/
6717 /************** Continuing where we left off in sqliteInt.h ******************/
6718 #include <stdio.h>
6719 #include <stdlib.h>
6720 #include <string.h>
6721 #include <assert.h>
6722 #include <stddef.h>
6723
6724 /*
6725 ** If compiling for a processor that lacks floating point support,
6726 ** substitute integer for floating-point
6727 */
6728 #ifdef SQLITE_OMIT_FLOATING_POINT
6729 # define double sqlite_int64
6730 # define float sqlite_int64
6731 # define LONGDOUBLE_TYPE sqlite_int64
6732 # ifndef SQLITE_BIG_DBL
6733 #   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
6734 # endif
6735 # define SQLITE_OMIT_DATETIME_FUNCS 1
6736 # define SQLITE_OMIT_TRACE 1
6737 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
6738 # undef SQLITE_HAVE_ISNAN
6739 #endif
6740 #ifndef SQLITE_BIG_DBL
6741 # define SQLITE_BIG_DBL (1e99)
6742 #endif
6743
6744 /*
6745 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
6746 ** afterward. Having this macro allows us to cause the C compiler 
6747 ** to omit code used by TEMP tables without messy #ifndef statements.
6748 */
6749 #ifdef SQLITE_OMIT_TEMPDB
6750 #define OMIT_TEMPDB 1
6751 #else
6752 #define OMIT_TEMPDB 0
6753 #endif
6754
6755 /*
6756 ** The "file format" number is an integer that is incremented whenever
6757 ** the VDBE-level file format changes.  The following macros define the
6758 ** the default file format for new databases and the maximum file format
6759 ** that the library can read.
6760 */
6761 #define SQLITE_MAX_FILE_FORMAT 4
6762 #ifndef SQLITE_DEFAULT_FILE_FORMAT
6763 # define SQLITE_DEFAULT_FILE_FORMAT 1
6764 #endif
6765
6766 /*
6767 ** Determine whether triggers are recursive by default.  This can be
6768 ** changed at run-time using a pragma.
6769 */
6770 #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
6771 # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
6772 #endif
6773
6774 /*
6775 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
6776 ** on the command-line
6777 */
6778 #ifndef SQLITE_TEMP_STORE
6779 # define SQLITE_TEMP_STORE 1
6780 #endif
6781
6782 /*
6783 ** GCC does not define the offsetof() macro so we'll have to do it
6784 ** ourselves.
6785 */
6786 #ifndef offsetof
6787 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
6788 #endif
6789
6790 /*
6791 ** Check to see if this machine uses EBCDIC.  (Yes, believe it or
6792 ** not, there are still machines out there that use EBCDIC.)
6793 */
6794 #if 'A' == '\301'
6795 # define SQLITE_EBCDIC 1
6796 #else
6797 # define SQLITE_ASCII 1
6798 #endif
6799
6800 /*
6801 ** Integers of known sizes.  These typedefs might change for architectures
6802 ** where the sizes very.  Preprocessor macros are available so that the
6803 ** types can be conveniently redefined at compile-type.  Like this:
6804 **
6805 **         cc '-DUINTPTR_TYPE=long long int' ...
6806 */
6807 #ifndef UINT32_TYPE
6808 # ifdef HAVE_UINT32_T
6809 #  define UINT32_TYPE uint32_t
6810 # else
6811 #  define UINT32_TYPE unsigned int
6812 # endif
6813 #endif
6814 #ifndef UINT16_TYPE
6815 # ifdef HAVE_UINT16_T
6816 #  define UINT16_TYPE uint16_t
6817 # else
6818 #  define UINT16_TYPE unsigned short int
6819 # endif
6820 #endif
6821 #ifndef INT16_TYPE
6822 # ifdef HAVE_INT16_T
6823 #  define INT16_TYPE int16_t
6824 # else
6825 #  define INT16_TYPE short int
6826 # endif
6827 #endif
6828 #ifndef UINT8_TYPE
6829 # ifdef HAVE_UINT8_T
6830 #  define UINT8_TYPE uint8_t
6831 # else
6832 #  define UINT8_TYPE unsigned char
6833 # endif
6834 #endif
6835 #ifndef INT8_TYPE
6836 # ifdef HAVE_INT8_T
6837 #  define INT8_TYPE int8_t
6838 # else
6839 #  define INT8_TYPE signed char
6840 # endif
6841 #endif
6842 #ifndef LONGDOUBLE_TYPE
6843 # define LONGDOUBLE_TYPE long double
6844 #endif
6845 typedef sqlite_int64 i64;          /* 8-byte signed integer */
6846 typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
6847 typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
6848 typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
6849 typedef INT16_TYPE i16;            /* 2-byte signed integer */
6850 typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
6851 typedef INT8_TYPE i8;              /* 1-byte signed integer */
6852
6853 /*
6854 ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
6855 ** that can be stored in a u32 without loss of data.  The value
6856 ** is 0x00000000ffffffff.  But because of quirks of some compilers, we
6857 ** have to specify the value in the less intuitive manner shown:
6858 */
6859 #define SQLITE_MAX_U32  ((((u64)1)<<32)-1)
6860
6861 /*
6862 ** Macros to determine whether the machine is big or little endian,
6863 ** evaluated at runtime.
6864 */
6865 #ifdef SQLITE_AMALGAMATION
6866 SQLITE_PRIVATE const int sqlite3one = 1;
6867 #else
6868 SQLITE_PRIVATE const int sqlite3one;
6869 #endif
6870 #if defined(i386) || defined(__i386__) || defined(_M_IX86)\
6871                              || defined(__x86_64) || defined(__x86_64__)
6872 # define SQLITE_BIGENDIAN    0
6873 # define SQLITE_LITTLEENDIAN 1
6874 # define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
6875 #else
6876 # define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
6877 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
6878 # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
6879 #endif
6880
6881 /*
6882 ** Constants for the largest and smallest possible 64-bit signed integers.
6883 ** These macros are designed to work correctly on both 32-bit and 64-bit
6884 ** compilers.
6885 */
6886 #define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
6887 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
6888
6889 /* 
6890 ** Round up a number to the next larger multiple of 8.  This is used
6891 ** to force 8-byte alignment on 64-bit architectures.
6892 */
6893 #define ROUND8(x)     (((x)+7)&~7)
6894
6895 /*
6896 ** Round down to the nearest multiple of 8
6897 */
6898 #define ROUNDDOWN8(x) ((x)&~7)
6899
6900 /*
6901 ** Assert that the pointer X is aligned to an 8-byte boundary.  This
6902 ** macro is used only within assert() to verify that the code gets
6903 ** all alignment restrictions correct.
6904 **
6905 ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
6906 ** underlying malloc() implemention might return us 4-byte aligned
6907 ** pointers.  In that case, only verify 4-byte alignment.
6908 */
6909 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
6910 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)
6911 #else
6912 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)
6913 #endif
6914
6915
6916 /*
6917 ** An instance of the following structure is used to store the busy-handler
6918 ** callback for a given sqlite handle. 
6919 **
6920 ** The sqlite.busyHandler member of the sqlite struct contains the busy
6921 ** callback for the database handle. Each pager opened via the sqlite
6922 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
6923 ** callback is currently invoked only from within pager.c.
6924 */
6925 typedef struct BusyHandler BusyHandler;
6926 struct BusyHandler {
6927   int (*xFunc)(void *,int);  /* The busy callback */
6928   void *pArg;                /* First arg to busy callback */
6929   int nBusy;                 /* Incremented with each busy call */
6930 };
6931
6932 /*
6933 ** Name of the master database table.  The master database table
6934 ** is a special table that holds the names and attributes of all
6935 ** user tables and indices.
6936 */
6937 #define MASTER_NAME       "sqlite_master"
6938 #define TEMP_MASTER_NAME  "sqlite_temp_master"
6939
6940 /*
6941 ** The root-page of the master database table.
6942 */
6943 #define MASTER_ROOT       1
6944
6945 /*
6946 ** The name of the schema table.
6947 */
6948 #define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
6949
6950 /*
6951 ** A convenience macro that returns the number of elements in
6952 ** an array.
6953 */
6954 #define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
6955
6956 /*
6957 ** The following value as a destructor means to use sqlite3DbFree().
6958 ** This is an internal extension to SQLITE_STATIC and SQLITE_TRANSIENT.
6959 */
6960 #define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3DbFree)
6961
6962 /*
6963 ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
6964 ** not support Writable Static Data (WSD) such as global and static variables.
6965 ** All variables must either be on the stack or dynamically allocated from
6966 ** the heap.  When WSD is unsupported, the variable declarations scattered
6967 ** throughout the SQLite code must become constants instead.  The SQLITE_WSD
6968 ** macro is used for this purpose.  And instead of referencing the variable
6969 ** directly, we use its constant as a key to lookup the run-time allocated
6970 ** buffer that holds real variable.  The constant is also the initializer
6971 ** for the run-time allocated buffer.
6972 **
6973 ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
6974 ** macros become no-ops and have zero performance impact.
6975 */
6976 #ifdef SQLITE_OMIT_WSD
6977   #define SQLITE_WSD const
6978   #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
6979   #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
6980 SQLITE_API   int sqlite3_wsd_init(int N, int J);
6981 SQLITE_API   void *sqlite3_wsd_find(void *K, int L);
6982 #else
6983   #define SQLITE_WSD 
6984   #define GLOBAL(t,v) v
6985   #define sqlite3GlobalConfig sqlite3Config
6986 #endif
6987
6988 /*
6989 ** The following macros are used to suppress compiler warnings and to
6990 ** make it clear to human readers when a function parameter is deliberately 
6991 ** left unused within the body of a function. This usually happens when
6992 ** a function is called via a function pointer. For example the 
6993 ** implementation of an SQL aggregate step callback may not use the
6994 ** parameter indicating the number of arguments passed to the aggregate,
6995 ** if it knows that this is enforced elsewhere.
6996 **
6997 ** When a function parameter is not used at all within the body of a function,
6998 ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
6999 ** However, these macros may also be used to suppress warnings related to
7000 ** parameters that may or may not be used depending on compilation options.
7001 ** For example those parameters only used in assert() statements. In these
7002 ** cases the parameters are named as per the usual conventions.
7003 */
7004 #define UNUSED_PARAMETER(x) (void)(x)
7005 #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
7006
7007 /*
7008 ** Forward references to structures
7009 */
7010 typedef struct AggInfo AggInfo;
7011 typedef struct AuthContext AuthContext;
7012 typedef struct AutoincInfo AutoincInfo;
7013 typedef struct Bitvec Bitvec;
7014 typedef struct CollSeq CollSeq;
7015 typedef struct Column Column;
7016 typedef struct Db Db;
7017 typedef struct Schema Schema;
7018 typedef struct Expr Expr;
7019 typedef struct ExprList ExprList;
7020 typedef struct ExprSpan ExprSpan;
7021 typedef struct FKey FKey;
7022 typedef struct FuncDef FuncDef;
7023 typedef struct FuncDefHash FuncDefHash;
7024 typedef struct IdList IdList;
7025 typedef struct Index Index;
7026 typedef struct IndexSample IndexSample;
7027 typedef struct KeyClass KeyClass;
7028 typedef struct KeyInfo KeyInfo;
7029 typedef struct Lookaside Lookaside;
7030 typedef struct LookasideSlot LookasideSlot;
7031 typedef struct Module Module;
7032 typedef struct NameContext NameContext;
7033 typedef struct Parse Parse;
7034 typedef struct RowSet RowSet;
7035 typedef struct Savepoint Savepoint;
7036 typedef struct Select Select;
7037 typedef struct SrcList SrcList;
7038 typedef struct StrAccum StrAccum;
7039 typedef struct Table Table;
7040 typedef struct TableLock TableLock;
7041 typedef struct Token Token;
7042 typedef struct Trigger Trigger;
7043 typedef struct TriggerPrg TriggerPrg;
7044 typedef struct TriggerStep TriggerStep;
7045 typedef struct UnpackedRecord UnpackedRecord;
7046 typedef struct VTable VTable;
7047 typedef struct Walker Walker;
7048 typedef struct WherePlan WherePlan;
7049 typedef struct WhereInfo WhereInfo;
7050 typedef struct WhereLevel WhereLevel;
7051
7052 /*
7053 ** Defer sourcing vdbe.h and btree.h until after the "u8" and 
7054 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
7055 ** pointer types (i.e. FuncDef) defined above.
7056 */
7057 /************** Include btree.h in the middle of sqliteInt.h *****************/
7058 /************** Begin file btree.h *******************************************/
7059 /*
7060 ** 2001 September 15
7061 **
7062 ** The author disclaims copyright to this source code.  In place of
7063 ** a legal notice, here is a blessing:
7064 **
7065 **    May you do good and not evil.
7066 **    May you find forgiveness for yourself and forgive others.
7067 **    May you share freely, never taking more than you give.
7068 **
7069 *************************************************************************
7070 ** This header file defines the interface that the sqlite B-Tree file
7071 ** subsystem.  See comments in the source code for a detailed description
7072 ** of what each interface routine does.
7073 */
7074 #ifndef _BTREE_H_
7075 #define _BTREE_H_
7076
7077 /* TODO: This definition is just included so other modules compile. It
7078 ** needs to be revisited.
7079 */
7080 #define SQLITE_N_BTREE_META 10
7081
7082 /*
7083 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
7084 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
7085 */
7086 #ifndef SQLITE_DEFAULT_AUTOVACUUM
7087   #define SQLITE_DEFAULT_AUTOVACUUM 0
7088 #endif
7089
7090 #define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
7091 #define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
7092 #define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
7093
7094 /*
7095 ** Forward declarations of structure
7096 */
7097 typedef struct Btree Btree;
7098 typedef struct BtCursor BtCursor;
7099 typedef struct BtShared BtShared;
7100 typedef struct BtreeMutexArray BtreeMutexArray;
7101
7102 /*
7103 ** This structure records all of the Btrees that need to hold
7104 ** a mutex before we enter sqlite3VdbeExec().  The Btrees are
7105 ** are placed in aBtree[] in order of aBtree[]->pBt.  That way,
7106 ** we can always lock and unlock them all quickly.
7107 */
7108 struct BtreeMutexArray {
7109   int nMutex;
7110   Btree *aBtree[SQLITE_MAX_ATTACHED+1];
7111 };
7112
7113
7114 SQLITE_PRIVATE int sqlite3BtreeOpen(
7115   const char *zFilename,   /* Name of database file to open */
7116   sqlite3 *db,             /* Associated database connection */
7117   Btree **ppBtree,         /* Return open Btree* here */
7118   int flags,               /* Flags */
7119   int vfsFlags             /* Flags passed through to VFS open */
7120 );
7121
7122 /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
7123 ** following values.
7124 **
7125 ** NOTE:  These values must match the corresponding PAGER_ values in
7126 ** pager.h.
7127 */
7128 #define BTREE_OMIT_JOURNAL  1  /* Do not use journal.  No argument */
7129 #define BTREE_NO_READLOCK   2  /* Omit readlocks on readonly files */
7130 #define BTREE_MEMORY        4  /* In-memory DB.  No argument */
7131 #define BTREE_READONLY      8  /* Open the database in read-only mode */
7132 #define BTREE_READWRITE    16  /* Open for both reading and writing */
7133 #define BTREE_CREATE       32  /* Create the database if it does not exist */
7134
7135 SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
7136 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
7137 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int);
7138 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
7139 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
7140 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
7141 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
7142 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
7143 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
7144 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
7145 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
7146 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
7147 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
7148 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
7149 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*);
7150 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
7151 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*);
7152 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
7153 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
7154 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
7155 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
7156 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
7157 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
7158 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
7159 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
7160 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
7161
7162 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
7163 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
7164 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
7165
7166 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
7167
7168 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
7169 ** of the following flags:
7170 */
7171 #define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
7172 #define BTREE_ZERODATA   2    /* Table has keys only - no data */
7173 #define BTREE_LEAFDATA   4    /* Data stored in leaves only.  Implies INTKEY */
7174
7175 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
7176 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
7177 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
7178
7179 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
7180 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
7181
7182 /*
7183 ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
7184 ** should be one of the following values. The integer values are assigned 
7185 ** to constants so that the offset of the corresponding field in an
7186 ** SQLite database header may be found using the following formula:
7187 **
7188 **   offset = 36 + (idx * 4)
7189 **
7190 ** For example, the free-page-count field is located at byte offset 36 of
7191 ** the database file header. The incr-vacuum-flag field is located at
7192 ** byte offset 64 (== 36+4*7).
7193 */
7194 #define BTREE_FREE_PAGE_COUNT     0
7195 #define BTREE_SCHEMA_VERSION      1
7196 #define BTREE_FILE_FORMAT         2
7197 #define BTREE_DEFAULT_CACHE_SIZE  3
7198 #define BTREE_LARGEST_ROOT_PAGE   4
7199 #define BTREE_TEXT_ENCODING       5
7200 #define BTREE_USER_VERSION        6
7201 #define BTREE_INCR_VACUUM         7
7202
7203 SQLITE_PRIVATE int sqlite3BtreeCursor(
7204   Btree*,                              /* BTree containing table to open */
7205   int iTable,                          /* Index of root page */
7206   int wrFlag,                          /* 1 for writing.  0 for read-only */
7207   struct KeyInfo*,                     /* First argument to compare function */
7208   BtCursor *pCursor                    /* Space to write cursor structure */
7209 );
7210 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
7211 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
7212
7213 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
7214 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
7215   BtCursor*,
7216   UnpackedRecord *pUnKey,
7217   i64 intKey,
7218   int bias,
7219   int *pRes
7220 );
7221 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
7222 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
7223 SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
7224                                   const void *pData, int nData,
7225                                   int nZero, int bias, int seekResult);
7226 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
7227 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
7228 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
7229 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
7230 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
7231 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
7232 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
7233 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
7234 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
7235 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
7236 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
7237 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
7238 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*);
7239
7240 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
7241 SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
7242
7243 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
7244 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
7245 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
7246
7247 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
7248
7249 #ifndef NDEBUG
7250 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
7251 #endif
7252
7253 #ifndef SQLITE_OMIT_BTREECOUNT
7254 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
7255 #endif
7256
7257 #ifdef SQLITE_TEST
7258 SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
7259 SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
7260 #endif
7261
7262 /*
7263 ** If we are not using shared cache, then there is no need to
7264 ** use mutexes to access the BtShared structures.  So make the
7265 ** Enter and Leave procedures no-ops.
7266 */
7267 #ifndef SQLITE_OMIT_SHARED_CACHE
7268 SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
7269 SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
7270 #else
7271 # define sqlite3BtreeEnter(X) 
7272 # define sqlite3BtreeEnterAll(X)
7273 #endif
7274
7275 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
7276 SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
7277 SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
7278 SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
7279 SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
7280 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayEnter(BtreeMutexArray*);
7281 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayLeave(BtreeMutexArray*);
7282 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayInsert(BtreeMutexArray*, Btree*);
7283 #ifndef NDEBUG
7284   /* These routines are used inside assert() statements only. */
7285 SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
7286 SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
7287 #endif
7288 #else
7289
7290 # define sqlite3BtreeLeave(X)
7291 # define sqlite3BtreeEnterCursor(X)
7292 # define sqlite3BtreeLeaveCursor(X)
7293 # define sqlite3BtreeLeaveAll(X)
7294 # define sqlite3BtreeMutexArrayEnter(X)
7295 # define sqlite3BtreeMutexArrayLeave(X)
7296 # define sqlite3BtreeMutexArrayInsert(X,Y)
7297
7298 # define sqlite3BtreeHoldsMutex(X) 1
7299 # define sqlite3BtreeHoldsAllMutexes(X) 1
7300 #endif
7301
7302
7303 #endif /* _BTREE_H_ */
7304
7305 /************** End of btree.h ***********************************************/
7306 /************** Continuing where we left off in sqliteInt.h ******************/
7307 /************** Include vdbe.h in the middle of sqliteInt.h ******************/
7308 /************** Begin file vdbe.h ********************************************/
7309 /*
7310 ** 2001 September 15
7311 **
7312 ** The author disclaims copyright to this source code.  In place of
7313 ** a legal notice, here is a blessing:
7314 **
7315 **    May you do good and not evil.
7316 **    May you find forgiveness for yourself and forgive others.
7317 **    May you share freely, never taking more than you give.
7318 **
7319 *************************************************************************
7320 ** Header file for the Virtual DataBase Engine (VDBE)
7321 **
7322 ** This header defines the interface to the virtual database engine
7323 ** or VDBE.  The VDBE implements an abstract machine that runs a
7324 ** simple program to access and modify the underlying database.
7325 */
7326 #ifndef _SQLITE_VDBE_H_
7327 #define _SQLITE_VDBE_H_
7328
7329 /*
7330 ** A single VDBE is an opaque structure named "Vdbe".  Only routines
7331 ** in the source file sqliteVdbe.c are allowed to see the insides
7332 ** of this structure.
7333 */
7334 typedef struct Vdbe Vdbe;
7335
7336 /*
7337 ** The names of the following types declared in vdbeInt.h are required
7338 ** for the VdbeOp definition.
7339 */
7340 typedef struct VdbeFunc VdbeFunc;
7341 typedef struct Mem Mem;
7342 typedef struct SubProgram SubProgram;
7343
7344 /*
7345 ** A single instruction of the virtual machine has an opcode
7346 ** and as many as three operands.  The instruction is recorded
7347 ** as an instance of the following structure:
7348 */
7349 struct VdbeOp {
7350   u8 opcode;          /* What operation to perform */
7351   signed char p4type; /* One of the P4_xxx constants for p4 */
7352   u8 opflags;         /* Mask of the OPFLG_* flags in opcodes.h */
7353   u8 p5;              /* Fifth parameter is an unsigned character */
7354   int p1;             /* First operand */
7355   int p2;             /* Second parameter (often the jump destination) */
7356   int p3;             /* The third parameter */
7357   union {             /* fourth parameter */
7358     int i;                 /* Integer value if p4type==P4_INT32 */
7359     void *p;               /* Generic pointer */
7360     char *z;               /* Pointer to data for string (char array) types */
7361     i64 *pI64;             /* Used when p4type is P4_INT64 */
7362     double *pReal;         /* Used when p4type is P4_REAL */
7363     FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
7364     VdbeFunc *pVdbeFunc;   /* Used when p4type is P4_VDBEFUNC */
7365     CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
7366     Mem *pMem;             /* Used when p4type is P4_MEM */
7367     VTable *pVtab;         /* Used when p4type is P4_VTAB */
7368     KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
7369     int *ai;               /* Used when p4type is P4_INTARRAY */
7370     SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
7371   } p4;
7372 #ifdef SQLITE_DEBUG
7373   char *zComment;          /* Comment to improve readability */
7374 #endif
7375 #ifdef VDBE_PROFILE
7376   int cnt;                 /* Number of times this instruction was executed */
7377   u64 cycles;              /* Total time spent executing this instruction */
7378 #endif
7379 };
7380 typedef struct VdbeOp VdbeOp;
7381
7382
7383 /*
7384 ** A sub-routine used to implement a trigger program.
7385 */
7386 struct SubProgram {
7387   VdbeOp *aOp;                  /* Array of opcodes for sub-program */
7388   int nOp;                      /* Elements in aOp[] */
7389   int nMem;                     /* Number of memory cells required */
7390   int nCsr;                     /* Number of cursors required */
7391   int nRef;                     /* Number of pointers to this structure */
7392   void *token;                  /* id that may be used to recursive triggers */
7393 };
7394
7395 /*
7396 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
7397 ** it takes up less space.
7398 */
7399 struct VdbeOpList {
7400   u8 opcode;          /* What operation to perform */
7401   signed char p1;     /* First operand */
7402   signed char p2;     /* Second parameter (often the jump destination) */
7403   signed char p3;     /* Third parameter */
7404 };
7405 typedef struct VdbeOpList VdbeOpList;
7406
7407 /*
7408 ** Allowed values of VdbeOp.p4type
7409 */
7410 #define P4_NOTUSED    0   /* The P4 parameter is not used */
7411 #define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
7412 #define P4_STATIC   (-2)  /* Pointer to a static string */
7413 #define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
7414 #define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
7415 #define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
7416 #define P4_VDBEFUNC (-7)  /* P4 is a pointer to a VdbeFunc structure */
7417 #define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
7418 #define P4_TRANSIENT (-9) /* P4 is a pointer to a transient string */
7419 #define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */
7420 #define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */
7421 #define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
7422 #define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
7423 #define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
7424 #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
7425 #define P4_SUBPROGRAM  (-18) /* P4 is a pointer to a SubProgram structure */
7426
7427 /* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
7428 ** is made.  That copy is freed when the Vdbe is finalized.  But if the
7429 ** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used.  It still
7430 ** gets freed when the Vdbe is finalized so it still should be obtained
7431 ** from a single sqliteMalloc().  But no copy is made and the calling
7432 ** function should *not* try to free the KeyInfo.
7433 */
7434 #define P4_KEYINFO_HANDOFF (-16)
7435 #define P4_KEYINFO_STATIC  (-17)
7436
7437 /*
7438 ** The Vdbe.aColName array contains 5n Mem structures, where n is the 
7439 ** number of columns of data returned by the statement.
7440 */
7441 #define COLNAME_NAME     0
7442 #define COLNAME_DECLTYPE 1
7443 #define COLNAME_DATABASE 2
7444 #define COLNAME_TABLE    3
7445 #define COLNAME_COLUMN   4
7446 #ifdef SQLITE_ENABLE_COLUMN_METADATA
7447 # define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
7448 #else
7449 # ifdef SQLITE_OMIT_DECLTYPE
7450 #   define COLNAME_N      1      /* Store only the name */
7451 # else
7452 #   define COLNAME_N      2      /* Store the name and decltype */
7453 # endif
7454 #endif
7455
7456 /*
7457 ** The following macro converts a relative address in the p2 field
7458 ** of a VdbeOp structure into a negative number so that 
7459 ** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
7460 ** the macro again restores the address.
7461 */
7462 #define ADDR(X)  (-1-(X))
7463
7464 /*
7465 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
7466 ** header file that defines a number for each opcode used by the VDBE.
7467 */
7468 /************** Include opcodes.h in the middle of vdbe.h ********************/
7469 /************** Begin file opcodes.h *****************************************/
7470 /* Automatically generated.  Do not edit */
7471 /* See the mkopcodeh.awk script for details */
7472 #define OP_Goto                                 1
7473 #define OP_Gosub                                2
7474 #define OP_Return                               3
7475 #define OP_Yield                                4
7476 #define OP_HaltIfNull                           5
7477 #define OP_Halt                                 6
7478 #define OP_Integer                              7
7479 #define OP_Int64                                8
7480 #define OP_Real                               130   /* same as TK_FLOAT    */
7481 #define OP_String8                             94   /* same as TK_STRING   */
7482 #define OP_String                               9
7483 #define OP_Null                                10
7484 #define OP_Blob                                11
7485 #define OP_Variable                            12
7486 #define OP_Move                                13
7487 #define OP_Copy                                14
7488 #define OP_SCopy                               15
7489 #define OP_ResultRow                           16
7490 #define OP_Concat                              91   /* same as TK_CONCAT   */
7491 #define OP_Add                                 86   /* same as TK_PLUS     */
7492 #define OP_Subtract                            87   /* same as TK_MINUS    */
7493 #define OP_Multiply                            88   /* same as TK_STAR     */
7494 #define OP_Divide                              89   /* same as TK_SLASH    */
7495 #define OP_Remainder                           90   /* same as TK_REM      */
7496 #define OP_CollSeq                             17
7497 #define OP_Function                            18
7498 #define OP_BitAnd                              82   /* same as TK_BITAND   */
7499 #define OP_BitOr                               83   /* same as TK_BITOR    */
7500 #define OP_ShiftLeft                           84   /* same as TK_LSHIFT   */
7501 #define OP_ShiftRight                          85   /* same as TK_RSHIFT   */
7502 #define OP_AddImm                              20
7503 #define OP_MustBeInt                           21
7504 #define OP_RealAffinity                        22
7505 #define OP_ToText                             141   /* same as TK_TO_TEXT  */
7506 #define OP_ToBlob                             142   /* same as TK_TO_BLOB  */
7507 #define OP_ToNumeric                          143   /* same as TK_TO_NUMERIC*/
7508 #define OP_ToInt                              144   /* same as TK_TO_INT   */
7509 #define OP_ToReal                             145   /* same as TK_TO_REAL  */
7510 #define OP_Eq                                  76   /* same as TK_EQ       */
7511 #define OP_Ne                                  75   /* same as TK_NE       */
7512 #define OP_Lt                                  79   /* same as TK_LT       */
7513 #define OP_Le                                  78   /* same as TK_LE       */
7514 #define OP_Gt                                  77   /* same as TK_GT       */
7515 #define OP_Ge                                  80   /* same as TK_GE       */
7516 #define OP_Permutation                         23
7517 #define OP_Compare                             24
7518 #define OP_Jump                                25
7519 #define OP_And                                 69   /* same as TK_AND      */
7520 #define OP_Or                                  68   /* same as TK_OR       */
7521 #define OP_Not                                 19   /* same as TK_NOT      */
7522 #define OP_BitNot                              93   /* same as TK_BITNOT   */
7523 #define OP_If                                  26
7524 #define OP_IfNot                               27
7525 #define OP_IsNull                              73   /* same as TK_ISNULL   */
7526 #define OP_NotNull                             74   /* same as TK_NOTNULL  */
7527 #define OP_Column                              28
7528 #define OP_Affinity                            29
7529 #define OP_MakeRecord                          30
7530 #define OP_Count                               31
7531 #define OP_Savepoint                           32
7532 #define OP_AutoCommit                          33
7533 #define OP_Transaction                         34
7534 #define OP_ReadCookie                          35
7535 #define OP_SetCookie                           36
7536 #define OP_VerifyCookie                        37
7537 #define OP_OpenRead                            38
7538 #define OP_OpenWrite                           39
7539 #define OP_OpenAutoindex                       40
7540 #define OP_OpenEphemeral                       41
7541 #define OP_OpenPseudo                          42
7542 #define OP_Close                               43
7543 #define OP_SeekLt                              44
7544 #define OP_SeekLe                              45
7545 #define OP_SeekGe                              46
7546 #define OP_SeekGt                              47
7547 #define OP_Seek                                48
7548 #define OP_NotFound                            49
7549 #define OP_Found                               50
7550 #define OP_IsUnique                            51
7551 #define OP_NotExists                           52
7552 #define OP_Sequence                            53
7553 #define OP_NewRowid                            54
7554 #define OP_Insert                              55
7555 #define OP_InsertInt                           56
7556 #define OP_Delete                              57
7557 #define OP_ResetCount                          58
7558 #define OP_RowKey                              59
7559 #define OP_RowData                             60
7560 #define OP_Rowid                               61
7561 #define OP_NullRow                             62
7562 #define OP_Last                                63
7563 #define OP_Sort                                64
7564 #define OP_Rewind                              65
7565 #define OP_Prev                                66
7566 #define OP_Next                                67
7567 #define OP_IdxInsert                           70
7568 #define OP_IdxDelete                           71
7569 #define OP_IdxRowid                            72
7570 #define OP_IdxLT                               81
7571 #define OP_IdxGE                               92
7572 #define OP_Destroy                             95
7573 #define OP_Clear                               96
7574 #define OP_CreateIndex                         97
7575 #define OP_CreateTable                         98
7576 #define OP_ParseSchema                         99
7577 #define OP_LoadAnalysis                       100
7578 #define OP_DropTable                          101
7579 #define OP_DropIndex                          102
7580 #define OP_DropTrigger                        103
7581 #define OP_IntegrityCk                        104
7582 #define OP_RowSetAdd                          105
7583 #define OP_RowSetRead                         106
7584 #define OP_RowSetTest                         107
7585 #define OP_Program                            108
7586 #define OP_Param                              109
7587 #define OP_FkCounter                          110
7588 #define OP_FkIfZero                           111
7589 #define OP_MemMax                             112
7590 #define OP_IfPos                              113
7591 #define OP_IfNeg                              114
7592 #define OP_IfZero                             115
7593 #define OP_AggStep                            116
7594 #define OP_AggFinal                           117
7595 #define OP_Checkpoint                         118
7596 #define OP_JournalMode                        119
7597 #define OP_Vacuum                             120
7598 #define OP_IncrVacuum                         121
7599 #define OP_Expire                             122
7600 #define OP_TableLock                          123
7601 #define OP_VBegin                             124
7602 #define OP_VCreate                            125
7603 #define OP_VDestroy                           126
7604 #define OP_VOpen                              127
7605 #define OP_VFilter                            128
7606 #define OP_VColumn                            129
7607 #define OP_VNext                              131
7608 #define OP_VRename                            132
7609 #define OP_VUpdate                            133
7610 #define OP_Pagecount                          134
7611 #define OP_Trace                              135
7612 #define OP_Noop                               136
7613 #define OP_Explain                            137
7614
7615 /* The following opcode values are never used */
7616 #define OP_NotUsed_138                        138
7617 #define OP_NotUsed_139                        139
7618 #define OP_NotUsed_140                        140
7619
7620
7621 /* Properties such as "out2" or "jump" that are specified in
7622 ** comments following the "case" for each opcode in the vdbe.c
7623 ** are encoded into bitvectors as follows:
7624 */
7625 #define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */
7626 #define OPFLG_OUT2_PRERELEASE 0x0002  /* out2-prerelease: */
7627 #define OPFLG_IN1             0x0004  /* in1:   P1 is an input */
7628 #define OPFLG_IN2             0x0008  /* in2:   P2 is an input */
7629 #define OPFLG_IN3             0x0010  /* in3:   P3 is an input */
7630 #define OPFLG_OUT2            0x0020  /* out2:  P2 is an output */
7631 #define OPFLG_OUT3            0x0040  /* out3:  P3 is an output */
7632 #define OPFLG_INITIALIZER {\
7633 /*   0 */ 0x00, 0x01, 0x05, 0x04, 0x04, 0x10, 0x00, 0x02,\
7634 /*   8 */ 0x02, 0x02, 0x02, 0x02, 0x02, 0x00, 0x24, 0x24,\
7635 /*  16 */ 0x00, 0x00, 0x00, 0x24, 0x04, 0x05, 0x04, 0x00,\
7636 /*  24 */ 0x00, 0x01, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02,\
7637 /*  32 */ 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00, 0x00,\
7638 /*  40 */ 0x00, 0x00, 0x00, 0x00, 0x11, 0x11, 0x11, 0x11,\
7639 /*  48 */ 0x08, 0x11, 0x11, 0x11, 0x11, 0x02, 0x02, 0x00,\
7640 /*  56 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01,\
7641 /*  64 */ 0x01, 0x01, 0x01, 0x01, 0x4c, 0x4c, 0x08, 0x00,\
7642 /*  72 */ 0x02, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
7643 /*  80 */ 0x15, 0x01, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\
7644 /*  88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x01, 0x24, 0x02, 0x02,\
7645 /*  96 */ 0x00, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,\
7646 /* 104 */ 0x00, 0x0c, 0x45, 0x15, 0x01, 0x02, 0x00, 0x01,\
7647 /* 112 */ 0x08, 0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02,\
7648 /* 120 */ 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
7649 /* 128 */ 0x01, 0x00, 0x02, 0x01, 0x00, 0x00, 0x02, 0x00,\
7650 /* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04,\
7651 /* 144 */ 0x04, 0x04,}
7652
7653 /************** End of opcodes.h *********************************************/
7654 /************** Continuing where we left off in vdbe.h ***********************/
7655
7656 /*
7657 ** Prototypes for the VDBE interface.  See comments on the implementation
7658 ** for a description of what each of these routines does.
7659 */
7660 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
7661 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
7662 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
7663 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
7664 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
7665 SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
7666 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
7667 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
7668 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);
7669 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
7670 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3);
7671 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
7672 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
7673 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N);
7674 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
7675 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
7676 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
7677 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
7678 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
7679 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
7680 SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int,int,int);
7681 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
7682 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
7683 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
7684 #ifdef SQLITE_DEBUG
7685 SQLITE_PRIVATE   int sqlite3VdbeAssertMayAbort(Vdbe *, int);
7686 SQLITE_PRIVATE   void sqlite3VdbeTrace(Vdbe*,FILE*);
7687 #endif
7688 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
7689 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
7690 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
7691 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
7692 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
7693 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
7694 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
7695 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
7696 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
7697 SQLITE_PRIVATE void sqlite3VdbeProgramDelete(sqlite3 *, SubProgram *, int);
7698 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8);
7699 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
7700 #ifndef SQLITE_OMIT_TRACE
7701 SQLITE_PRIVATE   char *sqlite3VdbeExpandSql(Vdbe*, const char*);
7702 #endif
7703
7704 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,char*,int);
7705 SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord*);
7706 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
7707
7708
7709 #ifndef NDEBUG
7710 SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
7711 # define VdbeComment(X)  sqlite3VdbeComment X
7712 SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
7713 # define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
7714 #else
7715 # define VdbeComment(X)
7716 # define VdbeNoopComment(X)
7717 #endif
7718
7719 #endif
7720
7721 /************** End of vdbe.h ************************************************/
7722 /************** Continuing where we left off in sqliteInt.h ******************/
7723 /************** Include pager.h in the middle of sqliteInt.h *****************/
7724 /************** Begin file pager.h *******************************************/
7725 /*
7726 ** 2001 September 15
7727 **
7728 ** The author disclaims copyright to this source code.  In place of
7729 ** a legal notice, here is a blessing:
7730 **
7731 **    May you do good and not evil.
7732 **    May you find forgiveness for yourself and forgive others.
7733 **    May you share freely, never taking more than you give.
7734 **
7735 *************************************************************************
7736 ** This header file defines the interface that the sqlite page cache
7737 ** subsystem.  The page cache subsystem reads and writes a file a page
7738 ** at a time and provides a journal for rollback.
7739 */
7740
7741 #ifndef _PAGER_H_
7742 #define _PAGER_H_
7743
7744 /*
7745 ** Default maximum size for persistent journal files. A negative 
7746 ** value means no limit. This value may be overridden using the 
7747 ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
7748 */
7749 #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
7750   #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
7751 #endif
7752
7753 /*
7754 ** The type used to represent a page number.  The first page in a file
7755 ** is called page 1.  0 is used to represent "not a page".
7756 */
7757 typedef u32 Pgno;
7758
7759 /*
7760 ** Each open file is managed by a separate instance of the "Pager" structure.
7761 */
7762 typedef struct Pager Pager;
7763
7764 /*
7765 ** Handle type for pages.
7766 */
7767 typedef struct PgHdr DbPage;
7768
7769 /*
7770 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
7771 ** reserved for working around a windows/posix incompatibility). It is
7772 ** used in the journal to signify that the remainder of the journal file 
7773 ** is devoted to storing a master journal name - there are no more pages to
7774 ** roll back. See comments for function writeMasterJournal() in pager.c 
7775 ** for details.
7776 */
7777 #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
7778
7779 /*
7780 ** Allowed values for the flags parameter to sqlite3PagerOpen().
7781 **
7782 ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
7783 */
7784 #define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
7785 #define PAGER_NO_READLOCK   0x0002    /* Omit readlocks on readonly files */
7786
7787 /*
7788 ** Valid values for the second argument to sqlite3PagerLockingMode().
7789 */
7790 #define PAGER_LOCKINGMODE_QUERY      -1
7791 #define PAGER_LOCKINGMODE_NORMAL      0
7792 #define PAGER_LOCKINGMODE_EXCLUSIVE   1
7793
7794 /*
7795 ** Numeric constants that encode the journalmode.  
7796 */
7797 #define PAGER_JOURNALMODE_QUERY     (-1)  /* Query the value of journalmode */
7798 #define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
7799 #define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
7800 #define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
7801 #define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
7802 #define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
7803 #define PAGER_JOURNALMODE_WAL         5   /* Use write-ahead logging */
7804
7805 /*
7806 ** The remainder of this file contains the declarations of the functions
7807 ** that make up the Pager sub-system API. See source code comments for 
7808 ** a detailed description of each routine.
7809 */
7810
7811 /* Open and close a Pager connection. */ 
7812 SQLITE_PRIVATE int sqlite3PagerOpen(
7813   sqlite3_vfs*,
7814   Pager **ppPager,
7815   const char*,
7816   int,
7817   int,
7818   int,
7819   void(*)(DbPage*)
7820 );
7821 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
7822 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
7823
7824 /* Functions used to configure a Pager object. */
7825 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
7826 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u16*, int);
7827 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
7828 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
7829 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int);
7830 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
7831 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
7832 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
7833 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
7834 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
7835 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
7836
7837 /* Functions used to obtain and release page references. */ 
7838 SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
7839 #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
7840 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
7841 SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
7842 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
7843
7844 /* Operations on page references. */
7845 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
7846 SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
7847 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
7848 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
7849 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *); 
7850 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *); 
7851
7852 /* Functions used to manage pager transactions and savepoints. */
7853 SQLITE_PRIVATE int sqlite3PagerPagecount(Pager*, int*);
7854 SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
7855 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
7856 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
7857 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
7858 SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
7859 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
7860 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
7861 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
7862
7863 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager);
7864 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
7865 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
7866 SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
7867 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager);
7868
7869 /* Functions used to query pager state and configuration. */
7870 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
7871 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
7872 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
7873 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*);
7874 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
7875 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
7876 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
7877 SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
7878 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
7879 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
7880
7881 /* Functions used to truncate the database file. */
7882 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
7883
7884 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
7885 SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
7886 #endif
7887
7888 /* Functions to support testing and debugging. */
7889 #if !defined(NDEBUG) || defined(SQLITE_TEST)
7890 SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
7891 SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
7892 #endif
7893 #ifdef SQLITE_TEST
7894 SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
7895 SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
7896   void disable_simulated_io_errors(void);
7897   void enable_simulated_io_errors(void);
7898 #else
7899 # define disable_simulated_io_errors()
7900 # define enable_simulated_io_errors()
7901 #endif
7902
7903 #endif /* _PAGER_H_ */
7904
7905 /************** End of pager.h ***********************************************/
7906 /************** Continuing where we left off in sqliteInt.h ******************/
7907 /************** Include pcache.h in the middle of sqliteInt.h ****************/
7908 /************** Begin file pcache.h ******************************************/
7909 /*
7910 ** 2008 August 05
7911 **
7912 ** The author disclaims copyright to this source code.  In place of
7913 ** a legal notice, here is a blessing:
7914 **
7915 **    May you do good and not evil.
7916 **    May you find forgiveness for yourself and forgive others.
7917 **    May you share freely, never taking more than you give.
7918 **
7919 *************************************************************************
7920 ** This header file defines the interface that the sqlite page cache
7921 ** subsystem. 
7922 */
7923
7924 #ifndef _PCACHE_H_
7925
7926 typedef struct PgHdr PgHdr;
7927 typedef struct PCache PCache;
7928
7929 /*
7930 ** Every page in the cache is controlled by an instance of the following
7931 ** structure.
7932 */
7933 struct PgHdr {
7934   void *pData;                   /* Content of this page */
7935   void *pExtra;                  /* Extra content */
7936   PgHdr *pDirty;                 /* Transient list of dirty pages */
7937   Pgno pgno;                     /* Page number for this page */
7938   Pager *pPager;                 /* The pager this page is part of */
7939 #ifdef SQLITE_CHECK_PAGES
7940   u32 pageHash;                  /* Hash of page content */
7941 #endif
7942   u16 flags;                     /* PGHDR flags defined below */
7943
7944   /**********************************************************************
7945   ** Elements above are public.  All that follows is private to pcache.c
7946   ** and should not be accessed by other modules.
7947   */
7948   i16 nRef;                      /* Number of users of this page */
7949   PCache *pCache;                /* Cache that owns this page */
7950
7951   PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
7952   PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
7953 };
7954
7955 /* Bit values for PgHdr.flags */
7956 #define PGHDR_DIRTY             0x002  /* Page has changed */
7957 #define PGHDR_NEED_SYNC         0x004  /* Fsync the rollback journal before
7958                                        ** writing this page to the database */
7959 #define PGHDR_NEED_READ         0x008  /* Content is unread */
7960 #define PGHDR_REUSE_UNLIKELY    0x010  /* A hint that reuse is unlikely */
7961 #define PGHDR_DONT_WRITE        0x020  /* Do not write content to disk */
7962
7963 /* Initialize and shutdown the page cache subsystem */
7964 SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
7965 SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
7966
7967 /* Page cache buffer management:
7968 ** These routines implement SQLITE_CONFIG_PAGECACHE.
7969 */
7970 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
7971
7972 /* Create a new pager cache.
7973 ** Under memory stress, invoke xStress to try to make pages clean.
7974 ** Only clean and unpinned pages can be reclaimed.
7975 */
7976 SQLITE_PRIVATE void sqlite3PcacheOpen(
7977   int szPage,                    /* Size of every page */
7978   int szExtra,                   /* Extra space associated with each page */
7979   int bPurgeable,                /* True if pages are on backing store */
7980   int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
7981   void *pStress,                 /* Argument to xStress */
7982   PCache *pToInit                /* Preallocated space for the PCache */
7983 );
7984
7985 /* Modify the page-size after the cache has been created. */
7986 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
7987
7988 /* Return the size in bytes of a PCache object.  Used to preallocate
7989 ** storage space.
7990 */
7991 SQLITE_PRIVATE int sqlite3PcacheSize(void);
7992
7993 /* One release per successful fetch.  Page is pinned until released.
7994 ** Reference counted. 
7995 */
7996 SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
7997 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
7998
7999 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
8000 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
8001 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
8002 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
8003
8004 /* Change a page number.  Used by incr-vacuum. */
8005 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
8006
8007 /* Remove all pages with pgno>x.  Reset the cache if x==0 */
8008 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
8009
8010 /* Get a list of all dirty pages in the cache, sorted by page number */
8011 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
8012
8013 /* Reset and close the cache object */
8014 SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
8015
8016 /* Clear flags from pages of the page cache */
8017 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
8018
8019 /* Discard the contents of the cache */
8020 SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
8021
8022 /* Return the total number of outstanding page references */
8023 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
8024
8025 /* Increment the reference count of an existing page */
8026 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
8027
8028 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
8029
8030 /* Return the total number of pages stored in the cache */
8031 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
8032
8033 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
8034 /* Iterate through all dirty pages currently stored in the cache. This
8035 ** interface is only available if SQLITE_CHECK_PAGES is defined when the 
8036 ** library is built.
8037 */
8038 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
8039 #endif
8040
8041 /* Set and get the suggested cache-size for the specified pager-cache.
8042 **
8043 ** If no global maximum is configured, then the system attempts to limit
8044 ** the total number of pages cached by purgeable pager-caches to the sum
8045 ** of the suggested cache-sizes.
8046 */
8047 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
8048 #ifdef SQLITE_TEST
8049 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
8050 #endif
8051
8052 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
8053 /* Try to return memory used by the pcache module to the main memory heap */
8054 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
8055 #endif
8056
8057 #ifdef SQLITE_TEST
8058 SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
8059 #endif
8060
8061 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
8062
8063 #endif /* _PCACHE_H_ */
8064
8065 /************** End of pcache.h **********************************************/
8066 /************** Continuing where we left off in sqliteInt.h ******************/
8067
8068 /************** Include os.h in the middle of sqliteInt.h ********************/
8069 /************** Begin file os.h **********************************************/
8070 /*
8071 ** 2001 September 16
8072 **
8073 ** The author disclaims copyright to this source code.  In place of
8074 ** a legal notice, here is a blessing:
8075 **
8076 **    May you do good and not evil.
8077 **    May you find forgiveness for yourself and forgive others.
8078 **    May you share freely, never taking more than you give.
8079 **
8080 ******************************************************************************
8081 **
8082 ** This header file (together with is companion C source-code file
8083 ** "os.c") attempt to abstract the underlying operating system so that
8084 ** the SQLite library will work on both POSIX and windows systems.
8085 **
8086 ** This header file is #include-ed by sqliteInt.h and thus ends up
8087 ** being included by every source file.
8088 */
8089 #ifndef _SQLITE_OS_H_
8090 #define _SQLITE_OS_H_
8091
8092 /*
8093 ** Figure out if we are dealing with Unix, Windows, or some other
8094 ** operating system.  After the following block of preprocess macros,
8095 ** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, SQLITE_OS_OS2, and SQLITE_OS_OTHER 
8096 ** will defined to either 1 or 0.  One of the four will be 1.  The other 
8097 ** three will be 0.
8098 */
8099 #if defined(SQLITE_OS_OTHER)
8100 # if SQLITE_OS_OTHER==1
8101 #   undef SQLITE_OS_UNIX
8102 #   define SQLITE_OS_UNIX 0
8103 #   undef SQLITE_OS_WIN
8104 #   define SQLITE_OS_WIN 0
8105 #   undef SQLITE_OS_OS2
8106 #   define SQLITE_OS_OS2 0
8107 # else
8108 #   undef SQLITE_OS_OTHER
8109 # endif
8110 #endif
8111 #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
8112 # define SQLITE_OS_OTHER 0
8113 # ifndef SQLITE_OS_WIN
8114 #   if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
8115 #     define SQLITE_OS_WIN 1
8116 #     define SQLITE_OS_UNIX 0
8117 #     define SQLITE_OS_OS2 0
8118 #   elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__)
8119 #     define SQLITE_OS_WIN 0
8120 #     define SQLITE_OS_UNIX 0
8121 #     define SQLITE_OS_OS2 1
8122 #   else
8123 #     define SQLITE_OS_WIN 0
8124 #     define SQLITE_OS_UNIX 1
8125 #     define SQLITE_OS_OS2 0
8126 #  endif
8127 # else
8128 #  define SQLITE_OS_UNIX 0
8129 #  define SQLITE_OS_OS2 0
8130 # endif
8131 #else
8132 # ifndef SQLITE_OS_WIN
8133 #  define SQLITE_OS_WIN 0
8134 # endif
8135 #endif
8136
8137 /*
8138 ** Determine if we are dealing with WindowsCE - which has a much
8139 ** reduced API.
8140 */
8141 #if defined(_WIN32_WCE)
8142 # define SQLITE_OS_WINCE 1
8143 #else
8144 # define SQLITE_OS_WINCE 0
8145 #endif
8146
8147
8148 /*
8149 ** Define the maximum size of a temporary filename
8150 */
8151 #if SQLITE_OS_WIN
8152 # include <windows.h>
8153 # define SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
8154 #elif SQLITE_OS_OS2
8155 # if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY)
8156 #  include <os2safe.h> /* has to be included before os2.h for linking to work */
8157 # endif
8158 # define INCL_DOSDATETIME
8159 # define INCL_DOSFILEMGR
8160 # define INCL_DOSERRORS
8161 # define INCL_DOSMISC
8162 # define INCL_DOSPROCESS
8163 # define INCL_DOSMODULEMGR
8164 # define INCL_DOSSEMAPHORES
8165 # include <os2.h>
8166 # include <uconv.h>
8167 # define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP)
8168 #else
8169 # define SQLITE_TEMPNAME_SIZE 200
8170 #endif
8171
8172 /* If the SET_FULLSYNC macro is not defined above, then make it
8173 ** a no-op
8174 */
8175 #ifndef SET_FULLSYNC
8176 # define SET_FULLSYNC(x,y)
8177 #endif
8178
8179 /*
8180 ** The default size of a disk sector
8181 */
8182 #ifndef SQLITE_DEFAULT_SECTOR_SIZE
8183 # define SQLITE_DEFAULT_SECTOR_SIZE 512
8184 #endif
8185
8186 /*
8187 ** Temporary files are named starting with this prefix followed by 16 random
8188 ** alphanumeric characters, and no file extension. They are stored in the
8189 ** OS's standard temporary file directory, and are deleted prior to exit.
8190 ** If sqlite is being embedded in another program, you may wish to change the
8191 ** prefix to reflect your program's name, so that if your program exits
8192 ** prematurely, old temporary files can be easily identified. This can be done
8193 ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
8194 **
8195 ** 2006-10-31:  The default prefix used to be "sqlite_".  But then
8196 ** Mcafee started using SQLite in their anti-virus product and it
8197 ** started putting files with the "sqlite" name in the c:/temp folder.
8198 ** This annoyed many windows users.  Those users would then do a 
8199 ** Google search for "sqlite", find the telephone numbers of the
8200 ** developers and call to wake them up at night and complain.
8201 ** For this reason, the default name prefix is changed to be "sqlite" 
8202 ** spelled backwards.  So the temp files are still identified, but
8203 ** anybody smart enough to figure out the code is also likely smart
8204 ** enough to know that calling the developer will not help get rid
8205 ** of the file.
8206 */
8207 #ifndef SQLITE_TEMP_FILE_PREFIX
8208 # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
8209 #endif
8210
8211 /*
8212 ** The following values may be passed as the second argument to
8213 ** sqlite3OsLock(). The various locks exhibit the following semantics:
8214 **
8215 ** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
8216 ** RESERVED:  A single process may hold a RESERVED lock on a file at
8217 **            any time. Other processes may hold and obtain new SHARED locks.
8218 ** PENDING:   A single process may hold a PENDING lock on a file at
8219 **            any one time. Existing SHARED locks may persist, but no new
8220 **            SHARED locks may be obtained by other processes.
8221 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
8222 **
8223 ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
8224 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
8225 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
8226 ** sqlite3OsLock().
8227 */
8228 #define NO_LOCK         0
8229 #define SHARED_LOCK     1
8230 #define RESERVED_LOCK   2
8231 #define PENDING_LOCK    3
8232 #define EXCLUSIVE_LOCK  4
8233
8234 /*
8235 ** File Locking Notes:  (Mostly about windows but also some info for Unix)
8236 **
8237 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
8238 ** those functions are not available.  So we use only LockFile() and
8239 ** UnlockFile().
8240 **
8241 ** LockFile() prevents not just writing but also reading by other processes.
8242 ** A SHARED_LOCK is obtained by locking a single randomly-chosen 
8243 ** byte out of a specific range of bytes. The lock byte is obtained at 
8244 ** random so two separate readers can probably access the file at the 
8245 ** same time, unless they are unlucky and choose the same lock byte.
8246 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
8247 ** There can only be one writer.  A RESERVED_LOCK is obtained by locking
8248 ** a single byte of the file that is designated as the reserved lock byte.
8249 ** A PENDING_LOCK is obtained by locking a designated byte different from
8250 ** the RESERVED_LOCK byte.
8251 **
8252 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
8253 ** which means we can use reader/writer locks.  When reader/writer locks
8254 ** are used, the lock is placed on the same range of bytes that is used
8255 ** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
8256 ** will support two or more Win95 readers or two or more WinNT readers.
8257 ** But a single Win95 reader will lock out all WinNT readers and a single
8258 ** WinNT reader will lock out all other Win95 readers.
8259 **
8260 ** The following #defines specify the range of bytes used for locking.
8261 ** SHARED_SIZE is the number of bytes available in the pool from which
8262 ** a random byte is selected for a shared lock.  The pool of bytes for
8263 ** shared locks begins at SHARED_FIRST. 
8264 **
8265 ** The same locking strategy and
8266 ** byte ranges are used for Unix.  This leaves open the possiblity of having
8267 ** clients on win95, winNT, and unix all talking to the same shared file
8268 ** and all locking correctly.  To do so would require that samba (or whatever
8269 ** tool is being used for file sharing) implements locks correctly between
8270 ** windows and unix.  I'm guessing that isn't likely to happen, but by
8271 ** using the same locking range we are at least open to the possibility.
8272 **
8273 ** Locking in windows is manditory.  For this reason, we cannot store
8274 ** actual data in the bytes used for locking.  The pager never allocates
8275 ** the pages involved in locking therefore.  SHARED_SIZE is selected so
8276 ** that all locks will fit on a single page even at the minimum page size.
8277 ** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
8278 ** is set high so that we don't have to allocate an unused page except
8279 ** for very large databases.  But one should test the page skipping logic 
8280 ** by setting PENDING_BYTE low and running the entire regression suite.
8281 **
8282 ** Changing the value of PENDING_BYTE results in a subtly incompatible
8283 ** file format.  Depending on how it is changed, you might not notice
8284 ** the incompatibility right away, even running a full regression test.
8285 ** The default location of PENDING_BYTE is the first byte past the
8286 ** 1GB boundary.
8287 **
8288 */
8289 #ifdef SQLITE_OMIT_WSD
8290 # define PENDING_BYTE     (0x40000000)
8291 #else
8292 # define PENDING_BYTE      sqlite3PendingByte
8293 #endif
8294 #define RESERVED_BYTE     (PENDING_BYTE+1)
8295 #define SHARED_FIRST      (PENDING_BYTE+2)
8296 #define SHARED_SIZE       510
8297
8298 /*
8299 ** Wrapper around OS specific sqlite3_os_init() function.
8300 */
8301 SQLITE_PRIVATE int sqlite3OsInit(void);
8302
8303 /* 
8304 ** Functions for accessing sqlite3_file methods 
8305 */
8306 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
8307 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
8308 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
8309 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
8310 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
8311 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
8312 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
8313 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
8314 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
8315 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
8316 #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
8317 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
8318 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
8319 SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
8320 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
8321 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
8322 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
8323
8324 /* 
8325 ** Functions for accessing sqlite3_vfs methods 
8326 */
8327 SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
8328 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
8329 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
8330 SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
8331 #ifndef SQLITE_OMIT_LOAD_EXTENSION
8332 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
8333 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
8334 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
8335 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
8336 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
8337 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
8338 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
8339 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
8340
8341 /*
8342 ** Convenience functions for opening and closing files using 
8343 ** sqlite3_malloc() to obtain space for the file-handle structure.
8344 */
8345 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
8346 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
8347
8348 #endif /* _SQLITE_OS_H_ */
8349
8350 /************** End of os.h **************************************************/
8351 /************** Continuing where we left off in sqliteInt.h ******************/
8352 /************** Include mutex.h in the middle of sqliteInt.h *****************/
8353 /************** Begin file mutex.h *******************************************/
8354 /*
8355 ** 2007 August 28
8356 **
8357 ** The author disclaims copyright to this source code.  In place of
8358 ** a legal notice, here is a blessing:
8359 **
8360 **    May you do good and not evil.
8361 **    May you find forgiveness for yourself and forgive others.
8362 **    May you share freely, never taking more than you give.
8363 **
8364 *************************************************************************
8365 **
8366 ** This file contains the common header for all mutex implementations.
8367 ** The sqliteInt.h header #includes this file so that it is available
8368 ** to all source files.  We break it out in an effort to keep the code
8369 ** better organized.
8370 **
8371 ** NOTE:  source files should *not* #include this header file directly.
8372 ** Source files should #include the sqliteInt.h file and let that file
8373 ** include this one indirectly.
8374 */
8375
8376
8377 /*
8378 ** Figure out what version of the code to use.  The choices are
8379 **
8380 **   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
8381 **                             mutexes implemention cannot be overridden
8382 **                             at start-time.
8383 **
8384 **   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
8385 **                             mutual exclusion is provided.  But this
8386 **                             implementation can be overridden at
8387 **                             start-time.
8388 **
8389 **   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
8390 **
8391 **   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
8392 **
8393 **   SQLITE_MUTEX_OS2          For multi-threaded applications on OS/2.
8394 */
8395 #if !SQLITE_THREADSAFE
8396 # define SQLITE_MUTEX_OMIT
8397 #endif
8398 #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
8399 #  if SQLITE_OS_UNIX
8400 #    define SQLITE_MUTEX_PTHREADS
8401 #  elif SQLITE_OS_WIN
8402 #    define SQLITE_MUTEX_W32
8403 #  elif SQLITE_OS_OS2
8404 #    define SQLITE_MUTEX_OS2
8405 #  else
8406 #    define SQLITE_MUTEX_NOOP
8407 #  endif
8408 #endif
8409
8410 #ifdef SQLITE_MUTEX_OMIT
8411 /*
8412 ** If this is a no-op implementation, implement everything as macros.
8413 */
8414 #define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
8415 #define sqlite3_mutex_free(X)
8416 #define sqlite3_mutex_enter(X)
8417 #define sqlite3_mutex_try(X)      SQLITE_OK
8418 #define sqlite3_mutex_leave(X)
8419 #define sqlite3_mutex_held(X)     1
8420 #define sqlite3_mutex_notheld(X)  1
8421 #define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
8422 #define sqlite3MutexInit()        SQLITE_OK
8423 #define sqlite3MutexEnd()
8424 #endif /* defined(SQLITE_MUTEX_OMIT) */
8425
8426 /************** End of mutex.h ***********************************************/
8427 /************** Continuing where we left off in sqliteInt.h ******************/
8428
8429
8430 /*
8431 ** Each database file to be accessed by the system is an instance
8432 ** of the following structure.  There are normally two of these structures
8433 ** in the sqlite.aDb[] array.  aDb[0] is the main database file and
8434 ** aDb[1] is the database file used to hold temporary tables.  Additional
8435 ** databases may be attached.
8436 */
8437 struct Db {
8438   char *zName;         /* Name of this database */
8439   Btree *pBt;          /* The B*Tree structure for this database file */
8440   u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
8441   u8 safety_level;     /* How aggressive at syncing data to disk */
8442   Schema *pSchema;     /* Pointer to database schema (possibly shared) */
8443 };
8444
8445 /*
8446 ** An instance of the following structure stores a database schema.
8447 **
8448 ** If there are no virtual tables configured in this schema, the
8449 ** Schema.db variable is set to NULL. After the first virtual table
8450 ** has been added, it is set to point to the database connection 
8451 ** used to create the connection. Once a virtual table has been
8452 ** added to the Schema structure and the Schema.db variable populated, 
8453 ** only that database connection may use the Schema to prepare 
8454 ** statements.
8455 */
8456 struct Schema {
8457   int schema_cookie;   /* Database schema version number for this file */
8458   Hash tblHash;        /* All tables indexed by name */
8459   Hash idxHash;        /* All (named) indices indexed by name */
8460   Hash trigHash;       /* All triggers indexed by name */
8461   Hash fkeyHash;       /* All foreign keys by referenced table name */
8462   Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
8463   u8 file_format;      /* Schema format version for this file */
8464   u8 enc;              /* Text encoding used by this database */
8465   u16 flags;           /* Flags associated with this schema */
8466   int cache_size;      /* Number of pages to use in the cache */
8467 #ifndef SQLITE_OMIT_VIRTUALTABLE
8468   sqlite3 *db;         /* "Owner" connection. See comment above */
8469 #endif
8470 };
8471
8472 /*
8473 ** These macros can be used to test, set, or clear bits in the 
8474 ** Db.pSchema->flags field.
8475 */
8476 #define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
8477 #define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
8478 #define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
8479 #define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)
8480
8481 /*
8482 ** Allowed values for the DB.pSchema->flags field.
8483 **
8484 ** The DB_SchemaLoaded flag is set after the database schema has been
8485 ** read into internal hash tables.
8486 **
8487 ** DB_UnresetViews means that one or more views have column names that
8488 ** have been filled out.  If the schema changes, these column names might
8489 ** changes and so the view will need to be reset.
8490 */
8491 #define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
8492 #define DB_UnresetViews    0x0002  /* Some views have defined column names */
8493 #define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
8494
8495 /*
8496 ** The number of different kinds of things that can be limited
8497 ** using the sqlite3_limit() interface.
8498 */
8499 #define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
8500
8501 /*
8502 ** Lookaside malloc is a set of fixed-size buffers that can be used
8503 ** to satisfy small transient memory allocation requests for objects
8504 ** associated with a particular database connection.  The use of
8505 ** lookaside malloc provides a significant performance enhancement
8506 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
8507 ** SQL statements.
8508 **
8509 ** The Lookaside structure holds configuration information about the
8510 ** lookaside malloc subsystem.  Each available memory allocation in
8511 ** the lookaside subsystem is stored on a linked list of LookasideSlot
8512 ** objects.
8513 **
8514 ** Lookaside allocations are only allowed for objects that are associated
8515 ** with a particular database connection.  Hence, schema information cannot
8516 ** be stored in lookaside because in shared cache mode the schema information
8517 ** is shared by multiple database connections.  Therefore, while parsing
8518 ** schema information, the Lookaside.bEnabled flag is cleared so that
8519 ** lookaside allocations are not used to construct the schema objects.
8520 */
8521 struct Lookaside {
8522   u16 sz;                 /* Size of each buffer in bytes */
8523   u8 bEnabled;            /* False to disable new lookaside allocations */
8524   u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
8525   int nOut;               /* Number of buffers currently checked out */
8526   int mxOut;              /* Highwater mark for nOut */
8527   LookasideSlot *pFree;   /* List of available buffers */
8528   void *pStart;           /* First byte of available memory space */
8529   void *pEnd;             /* First byte past end of available space */
8530 };
8531 struct LookasideSlot {
8532   LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
8533 };
8534
8535 /*
8536 ** A hash table for function definitions.
8537 **
8538 ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
8539 ** Collisions are on the FuncDef.pHash chain.
8540 */
8541 struct FuncDefHash {
8542   FuncDef *a[23];       /* Hash table for functions */
8543 };
8544
8545 /*
8546 ** Each database connection is an instance of the following structure.
8547 **
8548 ** The sqlite.lastRowid records the last insert rowid generated by an
8549 ** insert statement.  Inserts on views do not affect its value.  Each
8550 ** trigger has its own context, so that lastRowid can be updated inside
8551 ** triggers as usual.  The previous value will be restored once the trigger
8552 ** exits.  Upon entering a before or instead of trigger, lastRowid is no
8553 ** longer (since after version 2.8.12) reset to -1.
8554 **
8555 ** The sqlite.nChange does not count changes within triggers and keeps no
8556 ** context.  It is reset at start of sqlite3_exec.
8557 ** The sqlite.lsChange represents the number of changes made by the last
8558 ** insert, update, or delete statement.  It remains constant throughout the
8559 ** length of a statement and is then updated by OP_SetCounts.  It keeps a
8560 ** context stack just like lastRowid so that the count of changes
8561 ** within a trigger is not seen outside the trigger.  Changes to views do not
8562 ** affect the value of lsChange.
8563 ** The sqlite.csChange keeps track of the number of current changes (since
8564 ** the last statement) and is used to update sqlite_lsChange.
8565 **
8566 ** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16
8567 ** store the most recent error code and, if applicable, string. The
8568 ** internal function sqlite3Error() is used to set these variables
8569 ** consistently.
8570 */
8571 struct sqlite3 {
8572   sqlite3_vfs *pVfs;            /* OS Interface */
8573   int nDb;                      /* Number of backends currently in use */
8574   Db *aDb;                      /* All backends */
8575   int flags;                    /* Miscellaneous flags. See below */
8576   int openFlags;                /* Flags passed to sqlite3_vfs.xOpen() */
8577   int errCode;                  /* Most recent error code (SQLITE_*) */
8578   int errMask;                  /* & result codes with this before returning */
8579   u8 autoCommit;                /* The auto-commit flag. */
8580   u8 temp_store;                /* 1: file 2: memory 0: default */
8581   u8 mallocFailed;              /* True if we have seen a malloc failure */
8582   u8 dfltLockMode;              /* Default locking-mode for attached dbs */
8583   signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
8584   u8 suppressErr;               /* Do not issue error messages if true */
8585   int nextPagesize;             /* Pagesize after VACUUM if >0 */
8586   int nTable;                   /* Number of tables in the database */
8587   CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
8588   i64 lastRowid;                /* ROWID of most recent insert (see above) */
8589   u32 magic;                    /* Magic number for detect library misuse */
8590   int nChange;                  /* Value returned by sqlite3_changes() */
8591   int nTotalChange;             /* Value returned by sqlite3_total_changes() */
8592   sqlite3_mutex *mutex;         /* Connection mutex */
8593   int aLimit[SQLITE_N_LIMIT];   /* Limits */
8594   struct sqlite3InitInfo {      /* Information used during initialization */
8595     int iDb;                    /* When back is being initialized */
8596     int newTnum;                /* Rootpage of table being initialized */
8597     u8 busy;                    /* TRUE if currently initializing */
8598     u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */
8599   } init;
8600   int nExtension;               /* Number of loaded extensions */
8601   void **aExtension;            /* Array of shared library handles */
8602   struct Vdbe *pVdbe;           /* List of active virtual machines */
8603   int activeVdbeCnt;            /* Number of VDBEs currently executing */
8604   int writeVdbeCnt;             /* Number of active VDBEs that are writing */
8605   void (*xTrace)(void*,const char*);        /* Trace function */
8606   void *pTraceArg;                          /* Argument to the trace function */
8607   void (*xProfile)(void*,const char*,u64);  /* Profiling function */
8608   void *pProfileArg;                        /* Argument to profile function */
8609   void *pCommitArg;                 /* Argument to xCommitCallback() */   
8610   int (*xCommitCallback)(void*);    /* Invoked at every commit. */
8611   void *pRollbackArg;               /* Argument to xRollbackCallback() */   
8612   void (*xRollbackCallback)(void*); /* Invoked at every commit. */
8613   void *pUpdateArg;
8614   void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
8615 #ifndef SQLITE_OMIT_WAL
8616   int (*xWalCallback)(void *, sqlite3 *, const char *, int);
8617   void *pWalArg;
8618 #endif
8619   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
8620   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
8621   void *pCollNeededArg;
8622   sqlite3_value *pErr;          /* Most recent error message */
8623   char *zErrMsg;                /* Most recent error message (UTF-8 encoded) */
8624   char *zErrMsg16;              /* Most recent error message (UTF-16 encoded) */
8625   union {
8626     volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
8627     double notUsed1;            /* Spacer */
8628   } u1;
8629   Lookaside lookaside;          /* Lookaside malloc configuration */
8630 #ifndef SQLITE_OMIT_AUTHORIZATION
8631   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
8632                                 /* Access authorization function */
8633   void *pAuthArg;               /* 1st argument to the access auth function */
8634 #endif
8635 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
8636   int (*xProgress)(void *);     /* The progress callback */
8637   void *pProgressArg;           /* Argument to the progress callback */
8638   int nProgressOps;             /* Number of opcodes for progress callback */
8639 #endif
8640 #ifndef SQLITE_OMIT_VIRTUALTABLE
8641   Hash aModule;                 /* populated by sqlite3_create_module() */
8642   Table *pVTab;                 /* vtab with active Connect/Create method */
8643   VTable **aVTrans;             /* Virtual tables with open transactions */
8644   int nVTrans;                  /* Allocated size of aVTrans */
8645   VTable *pDisconnect;    /* Disconnect these in next sqlite3_prepare() */
8646 #endif
8647   FuncDefHash aFunc;            /* Hash table of connection functions */
8648   Hash aCollSeq;                /* All collating sequences */
8649   BusyHandler busyHandler;      /* Busy callback */
8650   int busyTimeout;              /* Busy handler timeout, in msec */
8651   Db aDbStatic[2];              /* Static space for the 2 default backends */
8652   Savepoint *pSavepoint;        /* List of active savepoints */
8653   int nSavepoint;               /* Number of non-transaction savepoints */
8654   int nStatement;               /* Number of nested statement-transactions  */
8655   u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
8656   i64 nDeferredCons;            /* Net deferred constraints this transaction. */
8657
8658 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
8659   /* The following variables are all protected by the STATIC_MASTER 
8660   ** mutex, not by sqlite3.mutex. They are used by code in notify.c. 
8661   **
8662   ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
8663   ** unlock so that it can proceed.
8664   **
8665   ** When X.pBlockingConnection==Y, that means that something that X tried
8666   ** tried to do recently failed with an SQLITE_LOCKED error due to locks
8667   ** held by Y.
8668   */
8669   sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
8670   sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
8671   void *pUnlockArg;                     /* Argument to xUnlockNotify */
8672   void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
8673   sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
8674 #endif
8675 };
8676
8677 /*
8678 ** A macro to discover the encoding of a database.
8679 */
8680 #define ENC(db) ((db)->aDb[0].pSchema->enc)
8681
8682 /*
8683 ** Possible values for the sqlite3.flags.
8684 */
8685 #define SQLITE_VdbeTrace      0x00000100  /* True to trace VDBE execution */
8686 #define SQLITE_InternChanges  0x00000200  /* Uncommitted Hash table changes */
8687 #define SQLITE_FullColNames   0x00000400  /* Show full column names on SELECT */
8688 #define SQLITE_ShortColNames  0x00000800  /* Show short columns names */
8689 #define SQLITE_CountRows      0x00001000  /* Count rows changed by INSERT, */
8690                                           /*   DELETE, or UPDATE and return */
8691                                           /*   the count using a callback. */
8692 #define SQLITE_NullCallback   0x00002000  /* Invoke the callback once if the */
8693                                           /*   result set is empty */
8694 #define SQLITE_SqlTrace       0x00004000  /* Debug print SQL as it executes */
8695 #define SQLITE_VdbeListing    0x00008000  /* Debug listings of VDBE programs */
8696 #define SQLITE_WriteSchema    0x00010000  /* OK to update SQLITE_MASTER */
8697 #define SQLITE_NoReadlock     0x00020000  /* Readlocks are omitted when 
8698                                           ** accessing read-only databases */
8699 #define SQLITE_IgnoreChecks   0x00040000  /* Do not enforce check constraints */
8700 #define SQLITE_ReadUncommitted 0x0080000  /* For shared-cache mode */
8701 #define SQLITE_LegacyFileFmt  0x00100000  /* Create new databases in format 1 */
8702 #define SQLITE_FullFSync      0x00200000  /* Use full fsync on the backend */
8703 #define SQLITE_LoadExtension  0x00400000  /* Enable load_extension */
8704 #define SQLITE_RecoveryMode   0x00800000  /* Ignore schema errors */
8705 #define SQLITE_ReverseOrder   0x01000000  /* Reverse unordered SELECTs */
8706 #define SQLITE_RecTriggers    0x02000000  /* Enable recursive triggers */
8707 #define SQLITE_ForeignKeys    0x04000000  /* Enforce foreign key constraints  */
8708 #define SQLITE_AutoIndex      0x08000000  /* Enable automatic indexes */
8709 #define SQLITE_PreferBuiltin  0x10000000  /* Preference to built-in funcs */
8710
8711 /*
8712 ** Bits of the sqlite3.flags field that are used by the
8713 ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface.
8714 ** These must be the low-order bits of the flags field.
8715 */
8716 #define SQLITE_QueryFlattener 0x01        /* Disable query flattening */
8717 #define SQLITE_ColumnCache    0x02        /* Disable the column cache */
8718 #define SQLITE_IndexSort      0x04        /* Disable indexes for sorting */
8719 #define SQLITE_IndexSearch    0x08        /* Disable indexes for searching */
8720 #define SQLITE_IndexCover     0x10        /* Disable index covering table */
8721 #define SQLITE_GroupByOrder   0x20        /* Disable GROUPBY cover of ORDERBY */
8722 #define SQLITE_OptMask        0xff        /* Mask of all disablable opts */
8723
8724 /*
8725 ** Possible values for the sqlite.magic field.
8726 ** The numbers are obtained at random and have no special meaning, other
8727 ** than being distinct from one another.
8728 */
8729 #define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
8730 #define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
8731 #define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
8732 #define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
8733 #define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
8734
8735 /*
8736 ** Each SQL function is defined by an instance of the following
8737 ** structure.  A pointer to this structure is stored in the sqlite.aFunc
8738 ** hash table.  When multiple functions have the same name, the hash table
8739 ** points to a linked list of these structures.
8740 */
8741 struct FuncDef {
8742   i16 nArg;            /* Number of arguments.  -1 means unlimited */
8743   u8 iPrefEnc;         /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
8744   u8 flags;            /* Some combination of SQLITE_FUNC_* */
8745   void *pUserData;     /* User data parameter */
8746   FuncDef *pNext;      /* Next function with same name */
8747   void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
8748   void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
8749   void (*xFinalize)(sqlite3_context*);                /* Aggregate finalizer */
8750   char *zName;         /* SQL name of the function. */
8751   FuncDef *pHash;      /* Next with a different name but the same hash */
8752 };
8753
8754 /*
8755 ** Possible values for FuncDef.flags
8756 */
8757 #define SQLITE_FUNC_LIKE     0x01 /* Candidate for the LIKE optimization */
8758 #define SQLITE_FUNC_CASE     0x02 /* Case-sensitive LIKE-type function */
8759 #define SQLITE_FUNC_EPHEM    0x04 /* Ephemeral.  Delete with VDBE */
8760 #define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */
8761 #define SQLITE_FUNC_PRIVATE  0x10 /* Allowed for internal use only */
8762 #define SQLITE_FUNC_COUNT    0x20 /* Built-in count(*) aggregate */
8763 #define SQLITE_FUNC_COALESCE 0x40 /* Built-in coalesce() or ifnull() function */
8764
8765 /*
8766 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
8767 ** used to create the initializers for the FuncDef structures.
8768 **
8769 **   FUNCTION(zName, nArg, iArg, bNC, xFunc)
8770 **     Used to create a scalar function definition of a function zName 
8771 **     implemented by C function xFunc that accepts nArg arguments. The
8772 **     value passed as iArg is cast to a (void*) and made available
8773 **     as the user-data (sqlite3_user_data()) for the function. If 
8774 **     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
8775 **
8776 **   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
8777 **     Used to create an aggregate function definition implemented by
8778 **     the C functions xStep and xFinal. The first four parameters
8779 **     are interpreted in the same way as the first 4 parameters to
8780 **     FUNCTION().
8781 **
8782 **   LIKEFUNC(zName, nArg, pArg, flags)
8783 **     Used to create a scalar function definition of a function zName 
8784 **     that accepts nArg arguments and is implemented by a call to C 
8785 **     function likeFunc. Argument pArg is cast to a (void *) and made
8786 **     available as the function user-data (sqlite3_user_data()). The
8787 **     FuncDef.flags variable is set to the value passed as the flags
8788 **     parameter.
8789 */
8790 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
8791   {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
8792    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0}
8793 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
8794   {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
8795    pArg, 0, xFunc, 0, 0, #zName, 0}
8796 #define LIKEFUNC(zName, nArg, arg, flags) \
8797   {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0}
8798 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
8799   {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \
8800    SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0}
8801
8802 /*
8803 ** All current savepoints are stored in a linked list starting at
8804 ** sqlite3.pSavepoint. The first element in the list is the most recently
8805 ** opened savepoint. Savepoints are added to the list by the vdbe
8806 ** OP_Savepoint instruction.
8807 */
8808 struct Savepoint {
8809   char *zName;                        /* Savepoint name (nul-terminated) */
8810   i64 nDeferredCons;                  /* Number of deferred fk violations */
8811   Savepoint *pNext;                   /* Parent savepoint (if any) */
8812 };
8813
8814 /*
8815 ** The following are used as the second parameter to sqlite3Savepoint(),
8816 ** and as the P1 argument to the OP_Savepoint instruction.
8817 */
8818 #define SAVEPOINT_BEGIN      0
8819 #define SAVEPOINT_RELEASE    1
8820 #define SAVEPOINT_ROLLBACK   2
8821
8822
8823 /*
8824 ** Each SQLite module (virtual table definition) is defined by an
8825 ** instance of the following structure, stored in the sqlite3.aModule
8826 ** hash table.
8827 */
8828 struct Module {
8829   const sqlite3_module *pModule;       /* Callback pointers */
8830   const char *zName;                   /* Name passed to create_module() */
8831   void *pAux;                          /* pAux passed to create_module() */
8832   void (*xDestroy)(void *);            /* Module destructor function */
8833 };
8834
8835 /*
8836 ** information about each column of an SQL table is held in an instance
8837 ** of this structure.
8838 */
8839 struct Column {
8840   char *zName;     /* Name of this column */
8841   Expr *pDflt;     /* Default value of this column */
8842   char *zDflt;     /* Original text of the default value */
8843   char *zType;     /* Data type for this column */
8844   char *zColl;     /* Collating sequence.  If NULL, use the default */
8845   u8 notNull;      /* True if there is a NOT NULL constraint */
8846   u8 isPrimKey;    /* True if this column is part of the PRIMARY KEY */
8847   char affinity;   /* One of the SQLITE_AFF_... values */
8848 #ifndef SQLITE_OMIT_VIRTUALTABLE
8849   u8 isHidden;     /* True if this column is 'hidden' */
8850 #endif
8851 };
8852
8853 /*
8854 ** A "Collating Sequence" is defined by an instance of the following
8855 ** structure. Conceptually, a collating sequence consists of a name and
8856 ** a comparison routine that defines the order of that sequence.
8857 **
8858 ** There may two separate implementations of the collation function, one
8859 ** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
8860 ** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
8861 ** native byte order. When a collation sequence is invoked, SQLite selects
8862 ** the version that will require the least expensive encoding
8863 ** translations, if any.
8864 **
8865 ** The CollSeq.pUser member variable is an extra parameter that passed in
8866 ** as the first argument to the UTF-8 comparison function, xCmp.
8867 ** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
8868 ** xCmp16.
8869 **
8870 ** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
8871 ** collating sequence is undefined.  Indices built on an undefined
8872 ** collating sequence may not be read or written.
8873 */
8874 struct CollSeq {
8875   char *zName;          /* Name of the collating sequence, UTF-8 encoded */
8876   u8 enc;               /* Text encoding handled by xCmp() */
8877   u8 type;              /* One of the SQLITE_COLL_... values below */
8878   void *pUser;          /* First argument to xCmp() */
8879   int (*xCmp)(void*,int, const void*, int, const void*);
8880   void (*xDel)(void*);  /* Destructor for pUser */
8881 };
8882
8883 /*
8884 ** Allowed values of CollSeq.type:
8885 */
8886 #define SQLITE_COLL_BINARY  1  /* The default memcmp() collating sequence */
8887 #define SQLITE_COLL_NOCASE  2  /* The built-in NOCASE collating sequence */
8888 #define SQLITE_COLL_REVERSE 3  /* The built-in REVERSE collating sequence */
8889 #define SQLITE_COLL_USER    0  /* Any other user-defined collating sequence */
8890
8891 /*
8892 ** A sort order can be either ASC or DESC.
8893 */
8894 #define SQLITE_SO_ASC       0  /* Sort in ascending order */
8895 #define SQLITE_SO_DESC      1  /* Sort in ascending order */
8896
8897 /*
8898 ** Column affinity types.
8899 **
8900 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
8901 ** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
8902 ** the speed a little by numbering the values consecutively.  
8903 **
8904 ** But rather than start with 0 or 1, we begin with 'a'.  That way,
8905 ** when multiple affinity types are concatenated into a string and
8906 ** used as the P4 operand, they will be more readable.
8907 **
8908 ** Note also that the numeric types are grouped together so that testing
8909 ** for a numeric type is a single comparison.
8910 */
8911 #define SQLITE_AFF_TEXT     'a'
8912 #define SQLITE_AFF_NONE     'b'
8913 #define SQLITE_AFF_NUMERIC  'c'
8914 #define SQLITE_AFF_INTEGER  'd'
8915 #define SQLITE_AFF_REAL     'e'
8916
8917 #define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
8918
8919 /*
8920 ** The SQLITE_AFF_MASK values masks off the significant bits of an
8921 ** affinity value. 
8922 */
8923 #define SQLITE_AFF_MASK     0x67
8924
8925 /*
8926 ** Additional bit values that can be ORed with an affinity without
8927 ** changing the affinity.
8928 */
8929 #define SQLITE_JUMPIFNULL   0x08  /* jumps if either operand is NULL */
8930 #define SQLITE_STOREP2      0x10  /* Store result in reg[P2] rather than jump */
8931 #define SQLITE_NULLEQ       0x80  /* NULL=NULL */
8932
8933 /*
8934 ** An object of this type is created for each virtual table present in
8935 ** the database schema. 
8936 **
8937 ** If the database schema is shared, then there is one instance of this
8938 ** structure for each database connection (sqlite3*) that uses the shared
8939 ** schema. This is because each database connection requires its own unique
8940 ** instance of the sqlite3_vtab* handle used to access the virtual table 
8941 ** implementation. sqlite3_vtab* handles can not be shared between 
8942 ** database connections, even when the rest of the in-memory database 
8943 ** schema is shared, as the implementation often stores the database
8944 ** connection handle passed to it via the xConnect() or xCreate() method
8945 ** during initialization internally. This database connection handle may
8946 ** then used by the virtual table implementation to access real tables 
8947 ** within the database. So that they appear as part of the callers 
8948 ** transaction, these accesses need to be made via the same database 
8949 ** connection as that used to execute SQL operations on the virtual table.
8950 **
8951 ** All VTable objects that correspond to a single table in a shared
8952 ** database schema are initially stored in a linked-list pointed to by
8953 ** the Table.pVTable member variable of the corresponding Table object.
8954 ** When an sqlite3_prepare() operation is required to access the virtual
8955 ** table, it searches the list for the VTable that corresponds to the
8956 ** database connection doing the preparing so as to use the correct
8957 ** sqlite3_vtab* handle in the compiled query.
8958 **
8959 ** When an in-memory Table object is deleted (for example when the
8960 ** schema is being reloaded for some reason), the VTable objects are not 
8961 ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed 
8962 ** immediately. Instead, they are moved from the Table.pVTable list to
8963 ** another linked list headed by the sqlite3.pDisconnect member of the
8964 ** corresponding sqlite3 structure. They are then deleted/xDisconnected 
8965 ** next time a statement is prepared using said sqlite3*. This is done
8966 ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
8967 ** Refer to comments above function sqlite3VtabUnlockList() for an
8968 ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
8969 ** list without holding the corresponding sqlite3.mutex mutex.
8970 **
8971 ** The memory for objects of this type is always allocated by 
8972 ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as 
8973 ** the first argument.
8974 */
8975 struct VTable {
8976   sqlite3 *db;              /* Database connection associated with this table */
8977   Module *pMod;             /* Pointer to module implementation */
8978   sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
8979   int nRef;                 /* Number of pointers to this structure */
8980   VTable *pNext;            /* Next in linked list (see above) */
8981 };
8982
8983 /*
8984 ** Each SQL table is represented in memory by an instance of the
8985 ** following structure.
8986 **
8987 ** Table.zName is the name of the table.  The case of the original
8988 ** CREATE TABLE statement is stored, but case is not significant for
8989 ** comparisons.
8990 **
8991 ** Table.nCol is the number of columns in this table.  Table.aCol is a
8992 ** pointer to an array of Column structures, one for each column.
8993 **
8994 ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
8995 ** the column that is that key.   Otherwise Table.iPKey is negative.  Note
8996 ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
8997 ** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
8998 ** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
8999 ** is generated for each row of the table.  TF_HasPrimaryKey is set if
9000 ** the table has any PRIMARY KEY, INTEGER or otherwise.
9001 **
9002 ** Table.tnum is the page number for the root BTree page of the table in the
9003 ** database file.  If Table.iDb is the index of the database table backend
9004 ** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
9005 ** holds temporary tables and indices.  If TF_Ephemeral is set
9006 ** then the table is stored in a file that is automatically deleted
9007 ** when the VDBE cursor to the table is closed.  In this case Table.tnum 
9008 ** refers VDBE cursor number that holds the table open, not to the root
9009 ** page number.  Transient tables are used to hold the results of a
9010 ** sub-query that appears instead of a real table name in the FROM clause 
9011 ** of a SELECT statement.
9012 */
9013 struct Table {
9014   sqlite3 *dbMem;      /* DB connection used for lookaside allocations. */
9015   char *zName;         /* Name of the table or view */
9016   int iPKey;           /* If not negative, use aCol[iPKey] as the primary key */
9017   int nCol;            /* Number of columns in this table */
9018   Column *aCol;        /* Information about each column */
9019   Index *pIndex;       /* List of SQL indexes on this table. */
9020   int tnum;            /* Root BTree node for this table (see note above) */
9021   Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
9022   u16 nRef;            /* Number of pointers to this Table */
9023   u8 tabFlags;         /* Mask of TF_* values */
9024   u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
9025   FKey *pFKey;         /* Linked list of all foreign keys in this table */
9026   char *zColAff;       /* String defining the affinity of each column */
9027 #ifndef SQLITE_OMIT_CHECK
9028   Expr *pCheck;        /* The AND of all CHECK constraints */
9029 #endif
9030 #ifndef SQLITE_OMIT_ALTERTABLE
9031   int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
9032 #endif
9033 #ifndef SQLITE_OMIT_VIRTUALTABLE
9034   VTable *pVTable;     /* List of VTable objects. */
9035   int nModuleArg;      /* Number of arguments to the module */
9036   char **azModuleArg;  /* Text of all module args. [0] is module name */
9037 #endif
9038   Trigger *pTrigger;   /* List of triggers stored in pSchema */
9039   Schema *pSchema;     /* Schema that contains this table */
9040   Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
9041 };
9042
9043 /*
9044 ** Allowed values for Tabe.tabFlags.
9045 */
9046 #define TF_Readonly        0x01    /* Read-only system table */
9047 #define TF_Ephemeral       0x02    /* An ephemeral table */
9048 #define TF_HasPrimaryKey   0x04    /* Table has a primary key */
9049 #define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
9050 #define TF_Virtual         0x10    /* Is a virtual table */
9051 #define TF_NeedMetadata    0x20    /* aCol[].zType and aCol[].pColl missing */
9052
9053
9054
9055 /*
9056 ** Test to see whether or not a table is a virtual table.  This is
9057 ** done as a macro so that it will be optimized out when virtual
9058 ** table support is omitted from the build.
9059 */
9060 #ifndef SQLITE_OMIT_VIRTUALTABLE
9061 #  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
9062 #  define IsHiddenColumn(X) ((X)->isHidden)
9063 #else
9064 #  define IsVirtual(X)      0
9065 #  define IsHiddenColumn(X) 0
9066 #endif
9067
9068 /*
9069 ** Each foreign key constraint is an instance of the following structure.
9070 **
9071 ** A foreign key is associated with two tables.  The "from" table is
9072 ** the table that contains the REFERENCES clause that creates the foreign
9073 ** key.  The "to" table is the table that is named in the REFERENCES clause.
9074 ** Consider this example:
9075 **
9076 **     CREATE TABLE ex1(
9077 **       a INTEGER PRIMARY KEY,
9078 **       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
9079 **     );
9080 **
9081 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
9082 **
9083 ** Each REFERENCES clause generates an instance of the following structure
9084 ** which is attached to the from-table.  The to-table need not exist when
9085 ** the from-table is created.  The existence of the to-table is not checked.
9086 */
9087 struct FKey {
9088   Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
9089   FKey *pNextFrom;  /* Next foreign key in pFrom */
9090   char *zTo;        /* Name of table that the key points to (aka: Parent) */
9091   FKey *pNextTo;    /* Next foreign key on table named zTo */
9092   FKey *pPrevTo;    /* Previous foreign key on table named zTo */
9093   int nCol;         /* Number of columns in this key */
9094   /* EV: R-30323-21917 */
9095   u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */
9096   u8 aAction[2];          /* ON DELETE and ON UPDATE actions, respectively */
9097   Trigger *apTrigger[2];  /* Triggers for aAction[] actions */
9098   struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */
9099     int iFrom;         /* Index of column in pFrom */
9100     char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */
9101   } aCol[1];        /* One entry for each of nCol column s */
9102 };
9103
9104 /*
9105 ** SQLite supports many different ways to resolve a constraint
9106 ** error.  ROLLBACK processing means that a constraint violation
9107 ** causes the operation in process to fail and for the current transaction
9108 ** to be rolled back.  ABORT processing means the operation in process
9109 ** fails and any prior changes from that one operation are backed out,
9110 ** but the transaction is not rolled back.  FAIL processing means that
9111 ** the operation in progress stops and returns an error code.  But prior
9112 ** changes due to the same operation are not backed out and no rollback
9113 ** occurs.  IGNORE means that the particular row that caused the constraint
9114 ** error is not inserted or updated.  Processing continues and no error
9115 ** is returned.  REPLACE means that preexisting database rows that caused
9116 ** a UNIQUE constraint violation are removed so that the new insert or
9117 ** update can proceed.  Processing continues and no error is reported.
9118 **
9119 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
9120 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
9121 ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
9122 ** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
9123 ** referenced table row is propagated into the row that holds the
9124 ** foreign key.
9125 ** 
9126 ** The following symbolic values are used to record which type
9127 ** of action to take.
9128 */
9129 #define OE_None     0   /* There is no constraint to check */
9130 #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
9131 #define OE_Abort    2   /* Back out changes but do no rollback transaction */
9132 #define OE_Fail     3   /* Stop the operation but leave all prior changes */
9133 #define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
9134 #define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
9135
9136 #define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
9137 #define OE_SetNull  7   /* Set the foreign key value to NULL */
9138 #define OE_SetDflt  8   /* Set the foreign key value to its default */
9139 #define OE_Cascade  9   /* Cascade the changes */
9140
9141 #define OE_Default  99  /* Do whatever the default action is */
9142
9143
9144 /*
9145 ** An instance of the following structure is passed as the first
9146 ** argument to sqlite3VdbeKeyCompare and is used to control the 
9147 ** comparison of the two index keys.
9148 */
9149 struct KeyInfo {
9150   sqlite3 *db;        /* The database connection */
9151   u8 enc;             /* Text encoding - one of the TEXT_Utf* values */
9152   u16 nField;         /* Number of entries in aColl[] */
9153   u8 *aSortOrder;     /* If defined an aSortOrder[i] is true, sort DESC */
9154   CollSeq *aColl[1];  /* Collating sequence for each term of the key */
9155 };
9156
9157 /*
9158 ** An instance of the following structure holds information about a
9159 ** single index record that has already been parsed out into individual
9160 ** values.
9161 **
9162 ** A record is an object that contains one or more fields of data.
9163 ** Records are used to store the content of a table row and to store
9164 ** the key of an index.  A blob encoding of a record is created by
9165 ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
9166 ** OP_Column opcode.
9167 **
9168 ** This structure holds a record that has already been disassembled
9169 ** into its constituent fields.
9170 */
9171 struct UnpackedRecord {
9172   KeyInfo *pKeyInfo;  /* Collation and sort-order information */
9173   u16 nField;         /* Number of entries in apMem[] */
9174   u16 flags;          /* Boolean settings.  UNPACKED_... below */
9175   i64 rowid;          /* Used by UNPACKED_PREFIX_SEARCH */
9176   Mem *aMem;          /* Values */
9177 };
9178
9179 /*
9180 ** Allowed values of UnpackedRecord.flags
9181 */
9182 #define UNPACKED_NEED_FREE     0x0001  /* Memory is from sqlite3Malloc() */
9183 #define UNPACKED_NEED_DESTROY  0x0002  /* apMem[]s should all be destroyed */
9184 #define UNPACKED_IGNORE_ROWID  0x0004  /* Ignore trailing rowid on key1 */
9185 #define UNPACKED_INCRKEY       0x0008  /* Make this key an epsilon larger */
9186 #define UNPACKED_PREFIX_MATCH  0x0010  /* A prefix match is considered OK */
9187 #define UNPACKED_PREFIX_SEARCH 0x0020  /* A prefix match is considered OK */
9188
9189 /*
9190 ** Each SQL index is represented in memory by an
9191 ** instance of the following structure.
9192 **
9193 ** The columns of the table that are to be indexed are described
9194 ** by the aiColumn[] field of this structure.  For example, suppose
9195 ** we have the following table and index:
9196 **
9197 **     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
9198 **     CREATE INDEX Ex2 ON Ex1(c3,c1);
9199 **
9200 ** In the Table structure describing Ex1, nCol==3 because there are
9201 ** three columns in the table.  In the Index structure describing
9202 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
9203 ** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the 
9204 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
9205 ** The second column to be indexed (c1) has an index of 0 in
9206 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
9207 **
9208 ** The Index.onError field determines whether or not the indexed columns
9209 ** must be unique and what to do if they are not.  When Index.onError=OE_None,
9210 ** it means this is not a unique index.  Otherwise it is a unique index
9211 ** and the value of Index.onError indicate the which conflict resolution 
9212 ** algorithm to employ whenever an attempt is made to insert a non-unique
9213 ** element.
9214 */
9215 struct Index {
9216   char *zName;     /* Name of this index */
9217   int nColumn;     /* Number of columns in the table used by this index */
9218   int *aiColumn;   /* Which columns are used by this index.  1st is 0 */
9219   unsigned *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
9220   Table *pTable;   /* The SQL table being indexed */
9221   int tnum;        /* Page containing root of this index in database file */
9222   u8 onError;      /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
9223   u8 autoIndex;    /* True if is automatically created (ex: by UNIQUE) */
9224   char *zColAff;   /* String defining the affinity of each column */
9225   Index *pNext;    /* The next index associated with the same table */
9226   Schema *pSchema; /* Schema containing this index */
9227   u8 *aSortOrder;  /* Array of size Index.nColumn. True==DESC, False==ASC */
9228   char **azColl;   /* Array of collation sequence names for index */
9229   IndexSample *aSample;    /* Array of SQLITE_INDEX_SAMPLES samples */
9230 };
9231
9232 /*
9233 ** Each sample stored in the sqlite_stat2 table is represented in memory 
9234 ** using a structure of this type.
9235 */
9236 struct IndexSample {
9237   union {
9238     char *z;        /* Value if eType is SQLITE_TEXT or SQLITE_BLOB */
9239     double r;       /* Value if eType is SQLITE_FLOAT or SQLITE_INTEGER */
9240   } u;
9241   u8 eType;         /* SQLITE_NULL, SQLITE_INTEGER ... etc. */
9242   u8 nByte;         /* Size in byte of text or blob. */
9243 };
9244
9245 /*
9246 ** Each token coming out of the lexer is an instance of
9247 ** this structure.  Tokens are also used as part of an expression.
9248 **
9249 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
9250 ** may contain random values.  Do not make any assumptions about Token.dyn
9251 ** and Token.n when Token.z==0.
9252 */
9253 struct Token {
9254   const char *z;     /* Text of the token.  Not NULL-terminated! */
9255   unsigned int n;    /* Number of characters in this token */
9256 };
9257
9258 /*
9259 ** An instance of this structure contains information needed to generate
9260 ** code for a SELECT that contains aggregate functions.
9261 **
9262 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
9263 ** pointer to this structure.  The Expr.iColumn field is the index in
9264 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
9265 ** code for that node.
9266 **
9267 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
9268 ** original Select structure that describes the SELECT statement.  These
9269 ** fields do not need to be freed when deallocating the AggInfo structure.
9270 */
9271 struct AggInfo {
9272   u8 directMode;          /* Direct rendering mode means take data directly
9273                           ** from source tables rather than from accumulators */
9274   u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
9275                           ** than the source table */
9276   int sortingIdx;         /* Cursor number of the sorting index */
9277   ExprList *pGroupBy;     /* The group by clause */
9278   int nSortingColumn;     /* Number of columns in the sorting index */
9279   struct AggInfo_col {    /* For each column used in source tables */
9280     Table *pTab;             /* Source table */
9281     int iTable;              /* Cursor number of the source table */
9282     int iColumn;             /* Column number within the source table */
9283     int iSorterColumn;       /* Column number in the sorting index */
9284     int iMem;                /* Memory location that acts as accumulator */
9285     Expr *pExpr;             /* The original expression */
9286   } *aCol;
9287   int nColumn;            /* Number of used entries in aCol[] */
9288   int nColumnAlloc;       /* Number of slots allocated for aCol[] */
9289   int nAccumulator;       /* Number of columns that show through to the output.
9290                           ** Additional columns are used only as parameters to
9291                           ** aggregate functions */
9292   struct AggInfo_func {   /* For each aggregate function */
9293     Expr *pExpr;             /* Expression encoding the function */
9294     FuncDef *pFunc;          /* The aggregate function implementation */
9295     int iMem;                /* Memory location that acts as accumulator */
9296     int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
9297   } *aFunc;
9298   int nFunc;              /* Number of entries in aFunc[] */
9299   int nFuncAlloc;         /* Number of slots allocated for aFunc[] */
9300 };
9301
9302 /*
9303 ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
9304 ** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
9305 ** than 32767 we have to make it 32-bit.  16-bit is preferred because
9306 ** it uses less memory in the Expr object, which is a big memory user
9307 ** in systems with lots of prepared statements.  And few applications
9308 ** need more than about 10 or 20 variables.  But some extreme users want
9309 ** to have prepared statements with over 32767 variables, and for them
9310 ** the option is available (at compile-time).
9311 */
9312 #if SQLITE_MAX_VARIABLE_NUMBER<=32767
9313 typedef i16 ynVar;
9314 #else
9315 typedef int ynVar;
9316 #endif
9317
9318 /*
9319 ** Each node of an expression in the parse tree is an instance
9320 ** of this structure.
9321 **
9322 ** Expr.op is the opcode. The integer parser token codes are reused
9323 ** as opcodes here. For example, the parser defines TK_GE to be an integer
9324 ** code representing the ">=" operator. This same integer code is reused
9325 ** to represent the greater-than-or-equal-to operator in the expression
9326 ** tree.
9327 **
9328 ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB, 
9329 ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
9330 ** the expression is a variable (TK_VARIABLE), then Expr.token contains the 
9331 ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
9332 ** then Expr.token contains the name of the function.
9333 **
9334 ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
9335 ** binary operator. Either or both may be NULL.
9336 **
9337 ** Expr.x.pList is a list of arguments if the expression is an SQL function,
9338 ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
9339 ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
9340 ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
9341 ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is 
9342 ** valid.
9343 **
9344 ** An expression of the form ID or ID.ID refers to a column in a table.
9345 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
9346 ** the integer cursor number of a VDBE cursor pointing to that table and
9347 ** Expr.iColumn is the column number for the specific column.  If the
9348 ** expression is used as a result in an aggregate SELECT, then the
9349 ** value is also stored in the Expr.iAgg column in the aggregate so that
9350 ** it can be accessed after all aggregates are computed.
9351 **
9352 ** If the expression is an unbound variable marker (a question mark 
9353 ** character '?' in the original SQL) then the Expr.iTable holds the index 
9354 ** number for that variable.
9355 **
9356 ** If the expression is a subquery then Expr.iColumn holds an integer
9357 ** register number containing the result of the subquery.  If the
9358 ** subquery gives a constant result, then iTable is -1.  If the subquery
9359 ** gives a different answer at different times during statement processing
9360 ** then iTable is the address of a subroutine that computes the subquery.
9361 **
9362 ** If the Expr is of type OP_Column, and the table it is selecting from
9363 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
9364 ** corresponding table definition.
9365 **
9366 ** ALLOCATION NOTES:
9367 **
9368 ** Expr objects can use a lot of memory space in database schema.  To
9369 ** help reduce memory requirements, sometimes an Expr object will be
9370 ** truncated.  And to reduce the number of memory allocations, sometimes
9371 ** two or more Expr objects will be stored in a single memory allocation,
9372 ** together with Expr.zToken strings.
9373 **
9374 ** If the EP_Reduced and EP_TokenOnly flags are set when
9375 ** an Expr object is truncated.  When EP_Reduced is set, then all
9376 ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
9377 ** are contained within the same memory allocation.  Note, however, that
9378 ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
9379 ** allocated, regardless of whether or not EP_Reduced is set.
9380 */
9381 struct Expr {
9382   u8 op;                 /* Operation performed by this node */
9383   char affinity;         /* The affinity of the column or 0 if not a column */
9384   u16 flags;             /* Various flags.  EP_* See below */
9385   union {
9386     char *zToken;          /* Token value. Zero terminated and dequoted */
9387     int iValue;            /* Integer value if EP_IntValue */
9388   } u;
9389
9390   /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
9391   ** space is allocated for the fields below this point. An attempt to
9392   ** access them will result in a segfault or malfunction. 
9393   *********************************************************************/
9394
9395   Expr *pLeft;           /* Left subnode */
9396   Expr *pRight;          /* Right subnode */
9397   union {
9398     ExprList *pList;     /* Function arguments or in "<expr> IN (<expr-list)" */
9399     Select *pSelect;     /* Used for sub-selects and "<expr> IN (<select>)" */
9400   } x;
9401   CollSeq *pColl;        /* The collation type of the column or 0 */
9402
9403   /* If the EP_Reduced flag is set in the Expr.flags mask, then no
9404   ** space is allocated for the fields below this point. An attempt to
9405   ** access them will result in a segfault or malfunction.
9406   *********************************************************************/
9407
9408   int iTable;            /* TK_COLUMN: cursor number of table holding column
9409                          ** TK_REGISTER: register number
9410                          ** TK_TRIGGER: 1 -> new, 0 -> old */
9411   ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
9412                          ** TK_VARIABLE: variable number (always >= 1). */
9413   i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
9414   i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
9415   u8 flags2;             /* Second set of flags.  EP2_... */
9416   u8 op2;                /* If a TK_REGISTER, the original value of Expr.op */
9417   AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
9418   Table *pTab;           /* Table for TK_COLUMN expressions. */
9419 #if SQLITE_MAX_EXPR_DEPTH>0
9420   int nHeight;           /* Height of the tree headed by this node */
9421 #endif
9422 };
9423
9424 /*
9425 ** The following are the meanings of bits in the Expr.flags field.
9426 */
9427 #define EP_FromJoin   0x0001  /* Originated in ON or USING clause of a join */
9428 #define EP_Agg        0x0002  /* Contains one or more aggregate functions */
9429 #define EP_Resolved   0x0004  /* IDs have been resolved to COLUMNs */
9430 #define EP_Error      0x0008  /* Expression contains one or more errors */
9431 #define EP_Distinct   0x0010  /* Aggregate function with DISTINCT keyword */
9432 #define EP_VarSelect  0x0020  /* pSelect is correlated, not constant */
9433 #define EP_DblQuoted  0x0040  /* token.z was originally in "..." */
9434 #define EP_InfixFunc  0x0080  /* True for an infix function: LIKE, GLOB, etc */
9435 #define EP_ExpCollate 0x0100  /* Collating sequence specified explicitly */
9436 #define EP_FixedDest  0x0200  /* Result needed in a specific register */
9437 #define EP_IntValue   0x0400  /* Integer value contained in u.iValue */
9438 #define EP_xIsSelect  0x0800  /* x.pSelect is valid (otherwise x.pList is) */
9439
9440 #define EP_Reduced    0x1000  /* Expr struct is EXPR_REDUCEDSIZE bytes only */
9441 #define EP_TokenOnly  0x2000  /* Expr struct is EXPR_TOKENONLYSIZE bytes only */
9442 #define EP_Static     0x4000  /* Held in memory not obtained from malloc() */
9443
9444 /*
9445 ** The following are the meanings of bits in the Expr.flags2 field.
9446 */
9447 #define EP2_MallocedToken  0x0001  /* Need to sqlite3DbFree() Expr.zToken */
9448 #define EP2_Irreducible    0x0002  /* Cannot EXPRDUP_REDUCE this Expr */
9449
9450 /*
9451 ** The pseudo-routine sqlite3ExprSetIrreducible sets the EP2_Irreducible
9452 ** flag on an expression structure.  This flag is used for VV&A only.  The
9453 ** routine is implemented as a macro that only works when in debugging mode,
9454 ** so as not to burden production code.
9455 */
9456 #ifdef SQLITE_DEBUG
9457 # define ExprSetIrreducible(X)  (X)->flags2 |= EP2_Irreducible
9458 #else
9459 # define ExprSetIrreducible(X)
9460 #endif
9461
9462 /*
9463 ** These macros can be used to test, set, or clear bits in the 
9464 ** Expr.flags field.
9465 */
9466 #define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
9467 #define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
9468 #define ExprSetProperty(E,P)     (E)->flags|=(P)
9469 #define ExprClearProperty(E,P)   (E)->flags&=~(P)
9470
9471 /*
9472 ** Macros to determine the number of bytes required by a normal Expr 
9473 ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags 
9474 ** and an Expr struct with the EP_TokenOnly flag set.
9475 */
9476 #define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
9477 #define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
9478 #define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
9479
9480 /*
9481 ** Flags passed to the sqlite3ExprDup() function. See the header comment 
9482 ** above sqlite3ExprDup() for details.
9483 */
9484 #define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
9485
9486 /*
9487 ** A list of expressions.  Each expression may optionally have a
9488 ** name.  An expr/name combination can be used in several ways, such
9489 ** as the list of "expr AS ID" fields following a "SELECT" or in the
9490 ** list of "ID = expr" items in an UPDATE.  A list of expressions can
9491 ** also be used as the argument to a function, in which case the a.zName
9492 ** field is not used.
9493 */
9494 struct ExprList {
9495   int nExpr;             /* Number of expressions on the list */
9496   int nAlloc;            /* Number of entries allocated below */
9497   int iECursor;          /* VDBE Cursor associated with this ExprList */
9498   struct ExprList_item {
9499     Expr *pExpr;           /* The list of expressions */
9500     char *zName;           /* Token associated with this expression */
9501     char *zSpan;           /* Original text of the expression */
9502     u8 sortOrder;          /* 1 for DESC or 0 for ASC */
9503     u8 done;               /* A flag to indicate when processing is finished */
9504     u16 iCol;              /* For ORDER BY, column number in result set */
9505     u16 iAlias;            /* Index into Parse.aAlias[] for zName */
9506   } *a;                  /* One entry for each expression */
9507 };
9508
9509 /*
9510 ** An instance of this structure is used by the parser to record both
9511 ** the parse tree for an expression and the span of input text for an
9512 ** expression.
9513 */
9514 struct ExprSpan {
9515   Expr *pExpr;          /* The expression parse tree */
9516   const char *zStart;   /* First character of input text */
9517   const char *zEnd;     /* One character past the end of input text */
9518 };
9519
9520 /*
9521 ** An instance of this structure can hold a simple list of identifiers,
9522 ** such as the list "a,b,c" in the following statements:
9523 **
9524 **      INSERT INTO t(a,b,c) VALUES ...;
9525 **      CREATE INDEX idx ON t(a,b,c);
9526 **      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
9527 **
9528 ** The IdList.a.idx field is used when the IdList represents the list of
9529 ** column names after a table name in an INSERT statement.  In the statement
9530 **
9531 **     INSERT INTO t(a,b,c) ...
9532 **
9533 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
9534 */
9535 struct IdList {
9536   struct IdList_item {
9537     char *zName;      /* Name of the identifier */
9538     int idx;          /* Index in some Table.aCol[] of a column named zName */
9539   } *a;
9540   int nId;         /* Number of identifiers on the list */
9541   int nAlloc;      /* Number of entries allocated for a[] below */
9542 };
9543
9544 /*
9545 ** The bitmask datatype defined below is used for various optimizations.
9546 **
9547 ** Changing this from a 64-bit to a 32-bit type limits the number of
9548 ** tables in a join to 32 instead of 64.  But it also reduces the size
9549 ** of the library by 738 bytes on ix86.
9550 */
9551 typedef u64 Bitmask;
9552
9553 /*
9554 ** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
9555 */
9556 #define BMS  ((int)(sizeof(Bitmask)*8))
9557
9558 /*
9559 ** The following structure describes the FROM clause of a SELECT statement.
9560 ** Each table or subquery in the FROM clause is a separate element of
9561 ** the SrcList.a[] array.
9562 **
9563 ** With the addition of multiple database support, the following structure
9564 ** can also be used to describe a particular table such as the table that
9565 ** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
9566 ** such a table must be a simple name: ID.  But in SQLite, the table can
9567 ** now be identified by a database name, a dot, then the table name: ID.ID.
9568 **
9569 ** The jointype starts out showing the join type between the current table
9570 ** and the next table on the list.  The parser builds the list this way.
9571 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
9572 ** jointype expresses the join between the table and the previous table.
9573 **
9574 ** In the colUsed field, the high-order bit (bit 63) is set if the table
9575 ** contains more than 63 columns and the 64-th or later column is used.
9576 */
9577 struct SrcList {
9578   i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
9579   i16 nAlloc;      /* Number of entries allocated in a[] below */
9580   struct SrcList_item {
9581     char *zDatabase;  /* Name of database holding this table */
9582     char *zName;      /* Name of the table */
9583     char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
9584     Table *pTab;      /* An SQL table corresponding to zName */
9585     Select *pSelect;  /* A SELECT statement used in place of a table name */
9586     u8 isPopulated;   /* Temporary table associated with SELECT is populated */
9587     u8 jointype;      /* Type of join between this able and the previous */
9588     u8 notIndexed;    /* True if there is a NOT INDEXED clause */
9589     int iCursor;      /* The VDBE cursor number used to access this table */
9590     Expr *pOn;        /* The ON clause of a join */
9591     IdList *pUsing;   /* The USING clause of a join */
9592     Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
9593     char *zIndex;     /* Identifier from "INDEXED BY <zIndex>" clause */
9594     Index *pIndex;    /* Index structure corresponding to zIndex, if any */
9595   } a[1];             /* One entry for each identifier on the list */
9596 };
9597
9598 /*
9599 ** Permitted values of the SrcList.a.jointype field
9600 */
9601 #define JT_INNER     0x0001    /* Any kind of inner or cross join */
9602 #define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
9603 #define JT_NATURAL   0x0004    /* True for a "natural" join */
9604 #define JT_LEFT      0x0008    /* Left outer join */
9605 #define JT_RIGHT     0x0010    /* Right outer join */
9606 #define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
9607 #define JT_ERROR     0x0040    /* unknown or unsupported join type */
9608
9609
9610 /*
9611 ** A WherePlan object holds information that describes a lookup
9612 ** strategy.
9613 **
9614 ** This object is intended to be opaque outside of the where.c module.
9615 ** It is included here only so that that compiler will know how big it
9616 ** is.  None of the fields in this object should be used outside of
9617 ** the where.c module.
9618 **
9619 ** Within the union, pIdx is only used when wsFlags&WHERE_INDEXED is true.
9620 ** pTerm is only used when wsFlags&WHERE_MULTI_OR is true.  And pVtabIdx
9621 ** is only used when wsFlags&WHERE_VIRTUALTABLE is true.  It is never the
9622 ** case that more than one of these conditions is true.
9623 */
9624 struct WherePlan {
9625   u32 wsFlags;                   /* WHERE_* flags that describe the strategy */
9626   u32 nEq;                       /* Number of == constraints */
9627   union {
9628     Index *pIdx;                   /* Index when WHERE_INDEXED is true */
9629     struct WhereTerm *pTerm;       /* WHERE clause term for OR-search */
9630     sqlite3_index_info *pVtabIdx;  /* Virtual table index to use */
9631   } u;
9632 };
9633
9634 /*
9635 ** For each nested loop in a WHERE clause implementation, the WhereInfo
9636 ** structure contains a single instance of this structure.  This structure
9637 ** is intended to be private the the where.c module and should not be
9638 ** access or modified by other modules.
9639 **
9640 ** The pIdxInfo field is used to help pick the best index on a
9641 ** virtual table.  The pIdxInfo pointer contains indexing
9642 ** information for the i-th table in the FROM clause before reordering.
9643 ** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
9644 ** All other information in the i-th WhereLevel object for the i-th table
9645 ** after FROM clause ordering.
9646 */
9647 struct WhereLevel {
9648   WherePlan plan;       /* query plan for this element of the FROM clause */
9649   int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
9650   int iTabCur;          /* The VDBE cursor used to access the table */
9651   int iIdxCur;          /* The VDBE cursor used to access pIdx */
9652   int addrBrk;          /* Jump here to break out of the loop */
9653   int addrNxt;          /* Jump here to start the next IN combination */
9654   int addrCont;         /* Jump here to continue with the next loop cycle */
9655   int addrFirst;        /* First instruction of interior of the loop */
9656   u8 iFrom;             /* Which entry in the FROM clause */
9657   u8 op, p5;            /* Opcode and P5 of the opcode that ends the loop */
9658   int p1, p2;           /* Operands of the opcode used to ends the loop */
9659   union {               /* Information that depends on plan.wsFlags */
9660     struct {
9661       int nIn;              /* Number of entries in aInLoop[] */
9662       struct InLoop {
9663         int iCur;              /* The VDBE cursor used by this IN operator */
9664         int addrInTop;         /* Top of the IN loop */
9665       } *aInLoop;           /* Information about each nested IN operator */
9666     } in;                 /* Used when plan.wsFlags&WHERE_IN_ABLE */
9667   } u;
9668
9669   /* The following field is really not part of the current level.  But
9670   ** we need a place to cache virtual table index information for each
9671   ** virtual table in the FROM clause and the WhereLevel structure is
9672   ** a convenient place since there is one WhereLevel for each FROM clause
9673   ** element.
9674   */
9675   sqlite3_index_info *pIdxInfo;  /* Index info for n-th source table */
9676 };
9677
9678 /*
9679 ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
9680 ** and the WhereInfo.wctrlFlags member.
9681 */
9682 #define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
9683 #define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
9684 #define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
9685 #define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
9686 #define WHERE_DUPLICATES_OK    0x0008 /* Ok to return a row more than once */
9687 #define WHERE_OMIT_OPEN        0x0010 /* Table cursors are already open */
9688 #define WHERE_OMIT_CLOSE       0x0020 /* Omit close of table & index cursors */
9689 #define WHERE_FORCE_TABLE      0x0040 /* Do not use an index-only search */
9690 #define WHERE_ONETABLE_ONLY    0x0080 /* Only code the 1st table in pTabList */
9691
9692 /*
9693 ** The WHERE clause processing routine has two halves.  The
9694 ** first part does the start of the WHERE loop and the second
9695 ** half does the tail of the WHERE loop.  An instance of
9696 ** this structure is returned by the first half and passed
9697 ** into the second half to give some continuity.
9698 */
9699 struct WhereInfo {
9700   Parse *pParse;       /* Parsing and code generating context */
9701   u16 wctrlFlags;      /* Flags originally passed to sqlite3WhereBegin() */
9702   u8 okOnePass;        /* Ok to use one-pass algorithm for UPDATE or DELETE */
9703   u8 untestedTerms;    /* Not all WHERE terms resolved by outer loop */
9704   SrcList *pTabList;             /* List of tables in the join */
9705   int iTop;                      /* The very beginning of the WHERE loop */
9706   int iContinue;                 /* Jump here to continue with next record */
9707   int iBreak;                    /* Jump here to break out of the loop */
9708   int nLevel;                    /* Number of nested loop */
9709   struct WhereClause *pWC;       /* Decomposition of the WHERE clause */
9710   double savedNQueryLoop;        /* pParse->nQueryLoop outside the WHERE loop */
9711   WhereLevel a[1];               /* Information about each nest loop in WHERE */
9712 };
9713
9714 /*
9715 ** A NameContext defines a context in which to resolve table and column
9716 ** names.  The context consists of a list of tables (the pSrcList) field and
9717 ** a list of named expression (pEList).  The named expression list may
9718 ** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
9719 ** to the table being operated on by INSERT, UPDATE, or DELETE.  The
9720 ** pEList corresponds to the result set of a SELECT and is NULL for
9721 ** other statements.
9722 **
9723 ** NameContexts can be nested.  When resolving names, the inner-most 
9724 ** context is searched first.  If no match is found, the next outer
9725 ** context is checked.  If there is still no match, the next context
9726 ** is checked.  This process continues until either a match is found
9727 ** or all contexts are check.  When a match is found, the nRef member of
9728 ** the context containing the match is incremented. 
9729 **
9730 ** Each subquery gets a new NameContext.  The pNext field points to the
9731 ** NameContext in the parent query.  Thus the process of scanning the
9732 ** NameContext list corresponds to searching through successively outer
9733 ** subqueries looking for a match.
9734 */
9735 struct NameContext {
9736   Parse *pParse;       /* The parser */
9737   SrcList *pSrcList;   /* One or more tables used to resolve names */
9738   ExprList *pEList;    /* Optional list of named expressions */
9739   int nRef;            /* Number of names resolved by this context */
9740   int nErr;            /* Number of errors encountered while resolving names */
9741   u8 allowAgg;         /* Aggregate functions allowed here */
9742   u8 hasAgg;           /* True if aggregates are seen */
9743   u8 isCheck;          /* True if resolving names in a CHECK constraint */
9744   int nDepth;          /* Depth of subquery recursion. 1 for no recursion */
9745   AggInfo *pAggInfo;   /* Information about aggregates at this level */
9746   NameContext *pNext;  /* Next outer name context.  NULL for outermost */
9747 };
9748
9749 /*
9750 ** An instance of the following structure contains all information
9751 ** needed to generate code for a single SELECT statement.
9752 **
9753 ** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
9754 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
9755 ** limit and nOffset to the value of the offset (or 0 if there is not
9756 ** offset).  But later on, nLimit and nOffset become the memory locations
9757 ** in the VDBE that record the limit and offset counters.
9758 **
9759 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
9760 ** These addresses must be stored so that we can go back and fill in
9761 ** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
9762 ** the number of columns in P2 can be computed at the same time
9763 ** as the OP_OpenEphm instruction is coded because not
9764 ** enough information about the compound query is known at that point.
9765 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
9766 ** for the result set.  The KeyInfo for addrOpenTran[2] contains collating
9767 ** sequences for the ORDER BY clause.
9768 */
9769 struct Select {
9770   ExprList *pEList;      /* The fields of the result */
9771   u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
9772   char affinity;         /* MakeRecord with this affinity for SRT_Set */
9773   u16 selFlags;          /* Various SF_* values */
9774   SrcList *pSrc;         /* The FROM clause */
9775   Expr *pWhere;          /* The WHERE clause */
9776   ExprList *pGroupBy;    /* The GROUP BY clause */
9777   Expr *pHaving;         /* The HAVING clause */
9778   ExprList *pOrderBy;    /* The ORDER BY clause */
9779   Select *pPrior;        /* Prior select in a compound select statement */
9780   Select *pNext;         /* Next select to the left in a compound */
9781   Select *pRightmost;    /* Right-most select in a compound select statement */
9782   Expr *pLimit;          /* LIMIT expression. NULL means not used. */
9783   Expr *pOffset;         /* OFFSET expression. NULL means not used. */
9784   int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
9785   int addrOpenEphm[3];   /* OP_OpenEphem opcodes related to this select */
9786 };
9787
9788 /*
9789 ** Allowed values for Select.selFlags.  The "SF" prefix stands for
9790 ** "Select Flag".
9791 */
9792 #define SF_Distinct        0x0001  /* Output should be DISTINCT */
9793 #define SF_Resolved        0x0002  /* Identifiers have been resolved */
9794 #define SF_Aggregate       0x0004  /* Contains aggregate functions */
9795 #define SF_UsesEphemeral   0x0008  /* Uses the OpenEphemeral opcode */
9796 #define SF_Expanded        0x0010  /* sqlite3SelectExpand() called on this */
9797 #define SF_HasTypeInfo     0x0020  /* FROM subqueries have Table metadata */
9798
9799
9800 /*
9801 ** The results of a select can be distributed in several ways.  The
9802 ** "SRT" prefix means "SELECT Result Type".
9803 */
9804 #define SRT_Union        1  /* Store result as keys in an index */
9805 #define SRT_Except       2  /* Remove result from a UNION index */
9806 #define SRT_Exists       3  /* Store 1 if the result is not empty */
9807 #define SRT_Discard      4  /* Do not save the results anywhere */
9808
9809 /* The ORDER BY clause is ignored for all of the above */
9810 #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
9811
9812 #define SRT_Output       5  /* Output each row of result */
9813 #define SRT_Mem          6  /* Store result in a memory cell */
9814 #define SRT_Set          7  /* Store results as keys in an index */
9815 #define SRT_Table        8  /* Store result as data with an automatic rowid */
9816 #define SRT_EphemTab     9  /* Create transient tab and store like SRT_Table */
9817 #define SRT_Coroutine   10  /* Generate a single row of result */
9818
9819 /*
9820 ** A structure used to customize the behavior of sqlite3Select(). See
9821 ** comments above sqlite3Select() for details.
9822 */
9823 typedef struct SelectDest SelectDest;
9824 struct SelectDest {
9825   u8 eDest;         /* How to dispose of the results */
9826   u8 affinity;      /* Affinity used when eDest==SRT_Set */
9827   int iParm;        /* A parameter used by the eDest disposal method */
9828   int iMem;         /* Base register where results are written */
9829   int nMem;         /* Number of registers allocated */
9830 };
9831
9832 /*
9833 ** During code generation of statements that do inserts into AUTOINCREMENT 
9834 ** tables, the following information is attached to the Table.u.autoInc.p
9835 ** pointer of each autoincrement table to record some side information that
9836 ** the code generator needs.  We have to keep per-table autoincrement
9837 ** information in case inserts are down within triggers.  Triggers do not
9838 ** normally coordinate their activities, but we do need to coordinate the
9839 ** loading and saving of autoincrement information.
9840 */
9841 struct AutoincInfo {
9842   AutoincInfo *pNext;   /* Next info block in a list of them all */
9843   Table *pTab;          /* Table this info block refers to */
9844   int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
9845   int regCtr;           /* Memory register holding the rowid counter */
9846 };
9847
9848 /*
9849 ** Size of the column cache
9850 */
9851 #ifndef SQLITE_N_COLCACHE
9852 # define SQLITE_N_COLCACHE 10
9853 #endif
9854
9855 /*
9856 ** At least one instance of the following structure is created for each 
9857 ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
9858 ** statement. All such objects are stored in the linked list headed at
9859 ** Parse.pTriggerPrg and deleted once statement compilation has been
9860 ** completed.
9861 **
9862 ** A Vdbe sub-program that implements the body and WHEN clause of trigger
9863 ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
9864 ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
9865 ** The Parse.pTriggerPrg list never contains two entries with the same
9866 ** values for both pTrigger and orconf.
9867 **
9868 ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
9869 ** accessed (or set to 0 for triggers fired as a result of INSERT 
9870 ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
9871 ** a mask of new.* columns used by the program.
9872 */
9873 struct TriggerPrg {
9874   Trigger *pTrigger;      /* Trigger this program was coded from */
9875   int orconf;             /* Default ON CONFLICT policy */
9876   SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
9877   u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
9878   TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
9879 };
9880
9881 /*
9882 ** An SQL parser context.  A copy of this structure is passed through
9883 ** the parser and down into all the parser action routine in order to
9884 ** carry around information that is global to the entire parse.
9885 **
9886 ** The structure is divided into two parts.  When the parser and code
9887 ** generate call themselves recursively, the first part of the structure
9888 ** is constant but the second part is reset at the beginning and end of
9889 ** each recursion.
9890 **
9891 ** The nTableLock and aTableLock variables are only used if the shared-cache 
9892 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
9893 ** used to store the set of table-locks required by the statement being
9894 ** compiled. Function sqlite3TableLock() is used to add entries to the
9895 ** list.
9896 */
9897 struct Parse {
9898   sqlite3 *db;         /* The main database structure */
9899   int rc;              /* Return code from execution */
9900   char *zErrMsg;       /* An error message */
9901   Vdbe *pVdbe;         /* An engine for executing database bytecode */
9902   u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
9903   u8 nameClash;        /* A permanent table name clashes with temp table name */
9904   u8 checkSchema;      /* Causes schema cookie check after an error */
9905   u8 nested;           /* Number of nested calls to the parser/code generator */
9906   u8 parseError;       /* True after a parsing error.  Ticket #1794 */
9907   u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
9908   u8 nTempInUse;       /* Number of aTempReg[] currently checked out */
9909   int aTempReg[8];     /* Holding area for temporary registers */
9910   int nRangeReg;       /* Size of the temporary register block */
9911   int iRangeReg;       /* First register in temporary register block */
9912   int nErr;            /* Number of errors seen */
9913   int nTab;            /* Number of previously allocated VDBE cursors */
9914   int nMem;            /* Number of memory cells used so far */
9915   int nSet;            /* Number of sets used so far */
9916   int ckBase;          /* Base register of data during check constraints */
9917   int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
9918   int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
9919   u8 nColCache;        /* Number of entries in the column cache */
9920   u8 iColCache;        /* Next entry of the cache to replace */
9921   struct yColCache {
9922     int iTable;           /* Table cursor number */
9923     int iColumn;          /* Table column number */
9924     u8 tempReg;           /* iReg is a temp register that needs to be freed */
9925     int iLevel;           /* Nesting level */
9926     int iReg;             /* Reg with value of this column. 0 means none. */
9927     int lru;              /* Least recently used entry has the smallest value */
9928   } aColCache[SQLITE_N_COLCACHE];  /* One for each column cache entry */
9929   u32 writeMask;       /* Start a write transaction on these databases */
9930   u32 cookieMask;      /* Bitmask of schema verified databases */
9931   u8 isMultiWrite;     /* True if statement may affect/insert multiple rows */
9932   u8 mayAbort;         /* True if statement may throw an ABORT exception */
9933   int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
9934   int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
9935 #ifndef SQLITE_OMIT_SHARED_CACHE
9936   int nTableLock;        /* Number of locks in aTableLock */
9937   TableLock *aTableLock; /* Required table locks for shared-cache mode */
9938 #endif
9939   int regRowid;        /* Register holding rowid of CREATE TABLE entry */
9940   int regRoot;         /* Register holding root page number for new objects */
9941   AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
9942   int nMaxArg;         /* Max args passed to user function by sub-program */
9943
9944   /* Information used while coding trigger programs. */
9945   Parse *pToplevel;    /* Parse structure for main program (or NULL) */
9946   Table *pTriggerTab;  /* Table triggers are being coded for */
9947   u32 oldmask;         /* Mask of old.* columns referenced */
9948   u32 newmask;         /* Mask of new.* columns referenced */
9949   u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
9950   u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
9951   u8 disableTriggers;  /* True to disable triggers */
9952   double nQueryLoop;   /* Estimated number of iterations of a query */
9953
9954   /* Above is constant between recursions.  Below is reset before and after
9955   ** each recursion */
9956
9957   int nVar;            /* Number of '?' variables seen in the SQL so far */
9958   int nVarExpr;        /* Number of used slots in apVarExpr[] */
9959   int nVarExprAlloc;   /* Number of allocated slots in apVarExpr[] */
9960   Expr **apVarExpr;    /* Pointers to :aaa and $aaaa wildcard expressions */
9961   Vdbe *pReprepare;    /* VM being reprepared (sqlite3Reprepare()) */
9962   int nAlias;          /* Number of aliased result set columns */
9963   int nAliasAlloc;     /* Number of allocated slots for aAlias[] */
9964   int *aAlias;         /* Register used to hold aliased result */
9965   u8 explain;          /* True if the EXPLAIN flag is found on the query */
9966   Token sNameToken;    /* Token with unqualified schema object name */
9967   Token sLastToken;    /* The last token parsed */
9968   const char *zTail;   /* All SQL text past the last semicolon parsed */
9969   Table *pNewTable;    /* A table being constructed by CREATE TABLE */
9970   Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
9971   const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
9972 #ifndef SQLITE_OMIT_VIRTUALTABLE
9973   Token sArg;                /* Complete text of a module argument */
9974   u8 declareVtab;            /* True if inside sqlite3_declare_vtab() */
9975   int nVtabLock;             /* Number of virtual tables to lock */
9976   Table **apVtabLock;        /* Pointer to virtual tables needing locking */
9977 #endif
9978   int nHeight;            /* Expression tree height of current sub-select */
9979   Table *pZombieTab;      /* List of Table objects to delete after code gen */
9980   TriggerPrg *pTriggerPrg;    /* Linked list of coded triggers */
9981 };
9982
9983 #ifdef SQLITE_OMIT_VIRTUALTABLE
9984   #define IN_DECLARE_VTAB 0
9985 #else
9986   #define IN_DECLARE_VTAB (pParse->declareVtab)
9987 #endif
9988
9989 /*
9990 ** An instance of the following structure can be declared on a stack and used
9991 ** to save the Parse.zAuthContext value so that it can be restored later.
9992 */
9993 struct AuthContext {
9994   const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
9995   Parse *pParse;              /* The Parse structure */
9996 };
9997
9998 /*
9999 ** Bitfield flags for P5 value in OP_Insert and OP_Delete
10000 */
10001 #define OPFLAG_NCHANGE       0x01    /* Set to update db->nChange */
10002 #define OPFLAG_LASTROWID     0x02    /* Set to update db->lastRowid */
10003 #define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
10004 #define OPFLAG_APPEND        0x08    /* This is likely to be an append */
10005 #define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
10006 #define OPFLAG_CLEARCACHE    0x20    /* Clear pseudo-table cache in OP_Column */
10007
10008 /*
10009  * Each trigger present in the database schema is stored as an instance of
10010  * struct Trigger. 
10011  *
10012  * Pointers to instances of struct Trigger are stored in two ways.
10013  * 1. In the "trigHash" hash table (part of the sqlite3* that represents the 
10014  *    database). This allows Trigger structures to be retrieved by name.
10015  * 2. All triggers associated with a single table form a linked list, using the
10016  *    pNext member of struct Trigger. A pointer to the first element of the
10017  *    linked list is stored as the "pTrigger" member of the associated
10018  *    struct Table.
10019  *
10020  * The "step_list" member points to the first element of a linked list
10021  * containing the SQL statements specified as the trigger program.
10022  */
10023 struct Trigger {
10024   char *zName;            /* The name of the trigger                        */
10025   char *table;            /* The table or view to which the trigger applies */
10026   u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
10027   u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
10028   Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
10029   IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
10030                              the <column-list> is stored here */
10031   Schema *pSchema;        /* Schema containing the trigger */
10032   Schema *pTabSchema;     /* Schema containing the table */
10033   TriggerStep *step_list; /* Link list of trigger program steps             */
10034   Trigger *pNext;         /* Next trigger associated with the table */
10035 };
10036
10037 /*
10038 ** A trigger is either a BEFORE or an AFTER trigger.  The following constants
10039 ** determine which. 
10040 **
10041 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
10042 ** In that cases, the constants below can be ORed together.
10043 */
10044 #define TRIGGER_BEFORE  1
10045 #define TRIGGER_AFTER   2
10046
10047 /*
10048  * An instance of struct TriggerStep is used to store a single SQL statement
10049  * that is a part of a trigger-program. 
10050  *
10051  * Instances of struct TriggerStep are stored in a singly linked list (linked
10052  * using the "pNext" member) referenced by the "step_list" member of the 
10053  * associated struct Trigger instance. The first element of the linked list is
10054  * the first step of the trigger-program.
10055  * 
10056  * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
10057  * "SELECT" statement. The meanings of the other members is determined by the 
10058  * value of "op" as follows:
10059  *
10060  * (op == TK_INSERT)
10061  * orconf    -> stores the ON CONFLICT algorithm
10062  * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
10063  *              this stores a pointer to the SELECT statement. Otherwise NULL.
10064  * target    -> A token holding the quoted name of the table to insert into.
10065  * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
10066  *              this stores values to be inserted. Otherwise NULL.
10067  * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ... 
10068  *              statement, then this stores the column-names to be
10069  *              inserted into.
10070  *
10071  * (op == TK_DELETE)
10072  * target    -> A token holding the quoted name of the table to delete from.
10073  * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
10074  *              Otherwise NULL.
10075  * 
10076  * (op == TK_UPDATE)
10077  * target    -> A token holding the quoted name of the table to update rows of.
10078  * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
10079  *              Otherwise NULL.
10080  * pExprList -> A list of the columns to update and the expressions to update
10081  *              them to. See sqlite3Update() documentation of "pChanges"
10082  *              argument.
10083  * 
10084  */
10085 struct TriggerStep {
10086   u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
10087   u8 orconf;           /* OE_Rollback etc. */
10088   Trigger *pTrig;      /* The trigger that this step is a part of */
10089   Select *pSelect;     /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
10090   Token target;        /* Target table for DELETE, UPDATE, INSERT */
10091   Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
10092   ExprList *pExprList; /* SET clause for UPDATE.  VALUES clause for INSERT */
10093   IdList *pIdList;     /* Column names for INSERT */
10094   TriggerStep *pNext;  /* Next in the link-list */
10095   TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
10096 };
10097
10098 /*
10099 ** The following structure contains information used by the sqliteFix...
10100 ** routines as they walk the parse tree to make database references
10101 ** explicit.  
10102 */
10103 typedef struct DbFixer DbFixer;
10104 struct DbFixer {
10105   Parse *pParse;      /* The parsing context.  Error messages written here */
10106   const char *zDb;    /* Make sure all objects are contained in this database */
10107   const char *zType;  /* Type of the container - used for error messages */
10108   const Token *pName; /* Name of the container - used for error messages */
10109 };
10110
10111 /*
10112 ** An objected used to accumulate the text of a string where we
10113 ** do not necessarily know how big the string will be in the end.
10114 */
10115 struct StrAccum {
10116   sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
10117   char *zBase;         /* A base allocation.  Not from malloc. */
10118   char *zText;         /* The string collected so far */
10119   int  nChar;          /* Length of the string so far */
10120   int  nAlloc;         /* Amount of space allocated in zText */
10121   int  mxAlloc;        /* Maximum allowed string length */
10122   u8   mallocFailed;   /* Becomes true if any memory allocation fails */
10123   u8   useMalloc;      /* True if zText is enlargeable using realloc */
10124   u8   tooBig;         /* Becomes true if string size exceeds limits */
10125 };
10126
10127 /*
10128 ** A pointer to this structure is used to communicate information
10129 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
10130 */
10131 typedef struct {
10132   sqlite3 *db;        /* The database being initialized */
10133   int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
10134   char **pzErrMsg;    /* Error message stored here */
10135   int rc;             /* Result code stored here */
10136 } InitData;
10137
10138 /*
10139 ** Structure containing global configuration data for the SQLite library.
10140 **
10141 ** This structure also contains some state information.
10142 */
10143 struct Sqlite3Config {
10144   int bMemstat;                     /* True to enable memory status */
10145   int bCoreMutex;                   /* True to enable core mutexing */
10146   int bFullMutex;                   /* True to enable full mutexing */
10147   int mxStrlen;                     /* Maximum string length */
10148   int szLookaside;                  /* Default lookaside buffer size */
10149   int nLookaside;                   /* Default lookaside buffer count */
10150   sqlite3_mem_methods m;            /* Low-level memory allocation interface */
10151   sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
10152   sqlite3_pcache_methods pcache;    /* Low-level page-cache interface */
10153   void *pHeap;                      /* Heap storage space */
10154   int nHeap;                        /* Size of pHeap[] */
10155   int mnReq, mxReq;                 /* Min and max heap requests sizes */
10156   void *pScratch;                   /* Scratch memory */
10157   int szScratch;                    /* Size of each scratch buffer */
10158   int nScratch;                     /* Number of scratch buffers */
10159   void *pPage;                      /* Page cache memory */
10160   int szPage;                       /* Size of each page in pPage[] */
10161   int nPage;                        /* Number of pages in pPage[] */
10162   int mxParserStack;                /* maximum depth of the parser stack */
10163   int sharedCacheEnabled;           /* true if shared-cache mode enabled */
10164   /* The above might be initialized to non-zero.  The following need to always
10165   ** initially be zero, however. */
10166   int isInit;                       /* True after initialization has finished */
10167   int inProgress;                   /* True while initialization in progress */
10168   int isMutexInit;                  /* True after mutexes are initialized */
10169   int isMallocInit;                 /* True after malloc is initialized */
10170   int isPCacheInit;                 /* True after malloc is initialized */
10171   sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
10172   int nRefInitMutex;                /* Number of users of pInitMutex */
10173   void (*xLog)(void*,int,const char*); /* Function for logging */
10174   void *pLogArg;                       /* First argument to xLog() */
10175 };
10176
10177 /*
10178 ** Context pointer passed down through the tree-walk.
10179 */
10180 struct Walker {
10181   int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
10182   int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
10183   Parse *pParse;                            /* Parser context.  */
10184   union {                                   /* Extra data for callback */
10185     NameContext *pNC;                          /* Naming context */
10186     int i;                                     /* Integer value */
10187   } u;
10188 };
10189
10190 /* Forward declarations */
10191 SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
10192 SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
10193 SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
10194 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
10195 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
10196
10197 /*
10198 ** Return code from the parse-tree walking primitives and their
10199 ** callbacks.
10200 */
10201 #define WRC_Continue    0   /* Continue down into children */
10202 #define WRC_Prune       1   /* Omit children but continue walking siblings */
10203 #define WRC_Abort       2   /* Abandon the tree walk */
10204
10205 /*
10206 ** Assuming zIn points to the first byte of a UTF-8 character,
10207 ** advance zIn to point to the first byte of the next UTF-8 character.
10208 */
10209 #define SQLITE_SKIP_UTF8(zIn) {                        \
10210   if( (*(zIn++))>=0xc0 ){                              \
10211     while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
10212   }                                                    \
10213 }
10214
10215 /*
10216 ** The SQLITE_*_BKPT macros are substitutes for the error codes with
10217 ** the same name but without the _BKPT suffix.  These macros invoke
10218 ** routines that report the line-number on which the error originated
10219 ** using sqlite3_log().  The routines also provide a convenient place
10220 ** to set a debugger breakpoint.
10221 */
10222 SQLITE_PRIVATE int sqlite3CorruptError(int);
10223 SQLITE_PRIVATE int sqlite3MisuseError(int);
10224 SQLITE_PRIVATE int sqlite3CantopenError(int);
10225 #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
10226 #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
10227 #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
10228
10229
10230 /*
10231 ** FTS4 is really an extension for FTS3.  It is enabled using the
10232 ** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
10233 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
10234 */
10235 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
10236 # define SQLITE_ENABLE_FTS3
10237 #endif
10238
10239 /*
10240 ** The ctype.h header is needed for non-ASCII systems.  It is also
10241 ** needed by FTS3 when FTS3 is included in the amalgamation.
10242 */
10243 #if !defined(SQLITE_ASCII) || \
10244     (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
10245 # include <ctype.h>
10246 #endif
10247
10248 /*
10249 ** The following macros mimic the standard library functions toupper(),
10250 ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
10251 ** sqlite versions only work for ASCII characters, regardless of locale.
10252 */
10253 #ifdef SQLITE_ASCII
10254 # define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
10255 # define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
10256 # define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
10257 # define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
10258 # define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
10259 # define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
10260 # define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
10261 #else
10262 # define sqlite3Toupper(x)   toupper((unsigned char)(x))
10263 # define sqlite3Isspace(x)   isspace((unsigned char)(x))
10264 # define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
10265 # define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
10266 # define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
10267 # define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
10268 # define sqlite3Tolower(x)   tolower((unsigned char)(x))
10269 #endif
10270
10271 /*
10272 ** Internal function prototypes
10273 */
10274 SQLITE_PRIVATE int sqlite3StrICmp(const char *, const char *);
10275 SQLITE_PRIVATE int sqlite3IsNumber(const char*, int*, u8);
10276 SQLITE_PRIVATE int sqlite3Strlen30(const char*);
10277 #define sqlite3StrNICmp sqlite3_strnicmp
10278
10279 SQLITE_PRIVATE int sqlite3MallocInit(void);
10280 SQLITE_PRIVATE void sqlite3MallocEnd(void);
10281 SQLITE_PRIVATE void *sqlite3Malloc(int);
10282 SQLITE_PRIVATE void *sqlite3MallocZero(int);
10283 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
10284 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
10285 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
10286 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
10287 SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
10288 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
10289 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
10290 SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
10291 SQLITE_PRIVATE int sqlite3MallocSize(void*);
10292 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
10293 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
10294 SQLITE_PRIVATE void sqlite3ScratchFree(void*);
10295 SQLITE_PRIVATE void *sqlite3PageMalloc(int);
10296 SQLITE_PRIVATE void sqlite3PageFree(void*);
10297 SQLITE_PRIVATE void sqlite3MemSetDefault(void);
10298 SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
10299 SQLITE_PRIVATE int sqlite3MemoryAlarm(void (*)(void*, sqlite3_int64, int), void*, sqlite3_int64);
10300
10301 /*
10302 ** On systems with ample stack space and that support alloca(), make
10303 ** use of alloca() to obtain space for large automatic objects.  By default,
10304 ** obtain space from malloc().
10305 **
10306 ** The alloca() routine never returns NULL.  This will cause code paths
10307 ** that deal with sqlite3StackAlloc() failures to be unreachable.
10308 */
10309 #ifdef SQLITE_USE_ALLOCA
10310 # define sqlite3StackAllocRaw(D,N)   alloca(N)
10311 # define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)
10312 # define sqlite3StackFree(D,P)       
10313 #else
10314 # define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
10315 # define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)
10316 # define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
10317 #endif
10318
10319 #ifdef SQLITE_ENABLE_MEMSYS3
10320 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
10321 #endif
10322 #ifdef SQLITE_ENABLE_MEMSYS5
10323 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
10324 #endif
10325
10326
10327 #ifndef SQLITE_MUTEX_OMIT
10328 SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
10329 SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3NoopMutex(void);
10330 SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
10331 SQLITE_PRIVATE   int sqlite3MutexInit(void);
10332 SQLITE_PRIVATE   int sqlite3MutexEnd(void);
10333 #endif
10334
10335 SQLITE_PRIVATE int sqlite3StatusValue(int);
10336 SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
10337 SQLITE_PRIVATE void sqlite3StatusSet(int, int);
10338
10339 #ifndef SQLITE_OMIT_FLOATING_POINT
10340 SQLITE_PRIVATE   int sqlite3IsNaN(double);
10341 #else
10342 # define sqlite3IsNaN(X)  0
10343 #endif
10344
10345 SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
10346 #ifndef SQLITE_OMIT_TRACE
10347 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
10348 #endif
10349 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
10350 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
10351 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
10352 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
10353 SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
10354 #endif
10355 #if defined(SQLITE_TEST)
10356 SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
10357 #endif
10358 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
10359 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
10360 SQLITE_PRIVATE int sqlite3Dequote(char*);
10361 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
10362 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
10363 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
10364 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
10365 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
10366 SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
10367 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
10368 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
10369 SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
10370 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
10371 SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
10372 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
10373 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
10374 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
10375 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
10376 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
10377 SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
10378 SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
10379 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
10380 SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
10381 SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
10382 SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
10383 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3*, int);
10384 SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
10385 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
10386 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
10387 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
10388 SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
10389 SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
10390 SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
10391 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
10392 SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
10393 SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
10394 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
10395 SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
10396 SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
10397
10398 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
10399 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
10400 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
10401 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
10402 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
10403 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
10404 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
10405
10406 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
10407 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
10408 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
10409 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
10410 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
10411
10412 SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
10413
10414 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
10415 SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
10416 #else
10417 # define sqlite3ViewGetColumnNames(A,B) 0
10418 #endif
10419
10420 SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
10421 SQLITE_PRIVATE void sqlite3DeleteTable(Table*);
10422 #ifndef SQLITE_OMIT_AUTOINCREMENT
10423 SQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);
10424 SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);
10425 #else
10426 # define sqlite3AutoincrementBegin(X)
10427 # define sqlite3AutoincrementEnd(X)
10428 #endif
10429 SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
10430 SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int,int*,int*,int*);
10431 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
10432 SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
10433 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
10434 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
10435 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
10436                                       Token*, Select*, Expr*, IdList*);
10437 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
10438 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
10439 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
10440 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
10441 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
10442 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
10443 SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
10444                         Token*, int, int);
10445 SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
10446 SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
10447 SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
10448                          Expr*,ExprList*,int,Expr*,Expr*);
10449 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
10450 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
10451 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
10452 SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
10453 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
10454 SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse *, SrcList *, Expr *, ExprList *, Expr *, Expr *, char *);
10455 #endif
10456 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
10457 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
10458 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**, u16);
10459 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
10460 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int);
10461 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
10462 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
10463 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, int, int, int);
10464 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
10465 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
10466 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
10467 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
10468 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
10469 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
10470 SQLITE_PRIVATE void sqlite3ExprHardCopy(Parse*,int,int);
10471 SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
10472 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
10473 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
10474 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
10475 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
10476 SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
10477 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
10478 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
10479 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
10480 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
10481 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
10482 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
10483 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
10484 SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
10485 SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
10486 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
10487 SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
10488 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*);
10489 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
10490 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
10491 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
10492 SQLITE_PRIVATE void sqlite3PrngSaveState(void);
10493 SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
10494 SQLITE_PRIVATE void sqlite3PrngResetState(void);
10495 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*);
10496 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
10497 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
10498 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
10499 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
10500 SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
10501 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
10502 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
10503 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
10504 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
10505 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
10506 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
10507 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
10508 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
10509 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
10510 SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int);
10511 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
10512 SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
10513 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
10514                                      int*,int,int,int,int,int*);
10515 SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
10516 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
10517 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
10518 SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
10519 SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
10520 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, char*, int);
10521 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
10522 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
10523 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
10524 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
10525 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
10526 SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
10527 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int);
10528 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
10529 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
10530 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
10531 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
10532 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
10533 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
10534
10535 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
10536 SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
10537 #endif
10538
10539 #ifndef SQLITE_OMIT_TRIGGER
10540 SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
10541                            Expr*,int, int);
10542 SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
10543 SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
10544 SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
10545 SQLITE_PRIVATE   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
10546 SQLITE_PRIVATE   Trigger *sqlite3TriggerList(Parse *, Table *);
10547 SQLITE_PRIVATE   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
10548                             int, int, int);
10549 SQLITE_PRIVATE   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
10550   void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
10551 SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
10552 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
10553 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
10554                                         ExprList*,Select*,u8);
10555 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
10556 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
10557 SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
10558 SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
10559 SQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
10560 # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
10561 #else
10562 # define sqlite3TriggersExist(B,C,D,E,F) 0
10563 # define sqlite3DeleteTrigger(A,B)
10564 # define sqlite3DropTriggerPtr(A,B)
10565 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
10566 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
10567 # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
10568 # define sqlite3TriggerList(X, Y) 0
10569 # define sqlite3ParseToplevel(p) p
10570 # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
10571 #endif
10572
10573 SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
10574 SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
10575 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
10576 #ifndef SQLITE_OMIT_AUTHORIZATION
10577 SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
10578 SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
10579 SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
10580 SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
10581 SQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
10582 #else
10583 # define sqlite3AuthRead(a,b,c,d)
10584 # define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
10585 # define sqlite3AuthContextPush(a,b,c)
10586 # define sqlite3AuthContextPop(a)  ((void)(a))
10587 #endif
10588 SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
10589 SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
10590 SQLITE_PRIVATE int sqlite3BtreeFactory(sqlite3 *db, const char *zFilename,
10591                        int omitJournal, int nCache, int flags, Btree **ppBtree);
10592 SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
10593 SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
10594 SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
10595 SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
10596 SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
10597 SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
10598 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*);
10599 SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
10600 SQLITE_PRIVATE int sqlite3FitsIn64Bits(const char *, int);
10601 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
10602 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
10603 SQLITE_PRIVATE int sqlite3Utf8Read(const u8*, const u8**);
10604
10605 /*
10606 ** Routines to read and write variable-length integers.  These used to
10607 ** be defined locally, but now we use the varint routines in the util.c
10608 ** file.  Code should use the MACRO forms below, as the Varint32 versions
10609 ** are coded to assume the single byte case is already handled (which 
10610 ** the MACRO form does).
10611 */
10612 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
10613 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
10614 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
10615 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
10616 SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
10617
10618 /*
10619 ** The header of a record consists of a sequence variable-length integers.
10620 ** These integers are almost always small and are encoded as a single byte.
10621 ** The following macros take advantage this fact to provide a fast encode
10622 ** and decode of the integers in a record header.  It is faster for the common
10623 ** case where the integer is a single byte.  It is a little slower when the
10624 ** integer is two or more bytes.  But overall it is faster.
10625 **
10626 ** The following expressions are equivalent:
10627 **
10628 **     x = sqlite3GetVarint32( A, &B );
10629 **     x = sqlite3PutVarint32( A, B );
10630 **
10631 **     x = getVarint32( A, B );
10632 **     x = putVarint32( A, B );
10633 **
10634 */
10635 #define getVarint32(A,B)  (u8)((*(A)<(u8)0x80) ? ((B) = (u32)*(A)),1 : sqlite3GetVarint32((A), (u32 *)&(B)))
10636 #define putVarint32(A,B)  (u8)(((u32)(B)<(u32)0x80) ? (*(A) = (unsigned char)(B)),1 : sqlite3PutVarint32((A), (B)))
10637 #define getVarint    sqlite3GetVarint
10638 #define putVarint    sqlite3PutVarint
10639
10640
10641 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
10642 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
10643 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
10644 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
10645 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
10646 SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*);
10647 SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
10648 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
10649 SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
10650 SQLITE_PRIVATE const char *sqlite3ErrStr(int);
10651 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
10652 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
10653 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
10654 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
10655 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Parse *pParse, Expr *, Token *);
10656 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
10657 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
10658 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
10659
10660 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
10661 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
10662 SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8, 
10663                         void(*)(void*));
10664 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
10665 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
10666 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
10667 #ifdef SQLITE_ENABLE_STAT2
10668 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *, u8, char *, int, int *);
10669 #endif
10670 SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
10671 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
10672 #ifndef SQLITE_AMALGAMATION
10673 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
10674 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
10675 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
10676 SQLITE_PRIVATE const Token sqlite3IntTokens[];
10677 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
10678 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
10679 #ifndef SQLITE_OMIT_WSD
10680 SQLITE_PRIVATE int sqlite3PendingByte;
10681 #endif
10682 #endif
10683 SQLITE_PRIVATE void sqlite3RootPageMoved(Db*, int, int);
10684 SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
10685 SQLITE_PRIVATE void sqlite3AlterFunctions(void);
10686 SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
10687 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
10688 SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
10689 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
10690 SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
10691 SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
10692 SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
10693 SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
10694 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
10695 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
10696 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
10697 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
10698 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(sqlite3*, u8, CollSeq *, const char*);
10699 SQLITE_PRIVATE char sqlite3AffinityType(const char*);
10700 SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
10701 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
10702 SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
10703 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
10704 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
10705 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(Index*);
10706 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
10707 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
10708 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
10709 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
10710 SQLITE_PRIVATE void sqlite3SchemaFree(void *);
10711 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
10712 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
10713 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
10714 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *, 
10715   void (*)(sqlite3_context*,int,sqlite3_value **),
10716   void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*));
10717 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
10718 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
10719
10720 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
10721 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
10722 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
10723 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
10724 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
10725 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
10726
10727 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
10728 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
10729
10730 /*
10731 ** The interface to the LEMON-generated parser
10732 */
10733 SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
10734 SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
10735 SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
10736 #ifdef YYTRACKMAXSTACKDEPTH
10737 SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
10738 #endif
10739
10740 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
10741 #ifndef SQLITE_OMIT_LOAD_EXTENSION
10742 SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
10743 #else
10744 # define sqlite3CloseExtensions(X)
10745 #endif
10746
10747 #ifndef SQLITE_OMIT_SHARED_CACHE
10748 SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
10749 #else
10750   #define sqlite3TableLock(v,w,x,y,z)
10751 #endif
10752
10753 #ifdef SQLITE_TEST
10754 SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
10755 #endif
10756
10757 #ifdef SQLITE_OMIT_VIRTUALTABLE
10758 #  define sqlite3VtabClear(Y)
10759 #  define sqlite3VtabSync(X,Y) SQLITE_OK
10760 #  define sqlite3VtabRollback(X)
10761 #  define sqlite3VtabCommit(X)
10762 #  define sqlite3VtabInSync(db) 0
10763 #  define sqlite3VtabLock(X) 
10764 #  define sqlite3VtabUnlock(X)
10765 #  define sqlite3VtabUnlockList(X)
10766 #else
10767 SQLITE_PRIVATE    void sqlite3VtabClear(Table*);
10768 SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, char **);
10769 SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
10770 SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
10771 SQLITE_PRIVATE    void sqlite3VtabLock(VTable *);
10772 SQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);
10773 SQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);
10774 #  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
10775 #endif
10776 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
10777 SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*);
10778 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
10779 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
10780 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
10781 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
10782 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
10783 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
10784 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
10785 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
10786 SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
10787 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
10788 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
10789 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
10790 SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
10791 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
10792 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
10793 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
10794 SQLITE_PRIVATE const char *sqlite3JournalModename(int);
10795 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int);
10796 SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
10797
10798 /* Declarations for functions in fkey.c. All of these are replaced by
10799 ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
10800 ** key functionality is available. If OMIT_TRIGGER is defined but
10801 ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
10802 ** this case foreign keys are parsed, but no other functionality is 
10803 ** provided (enforcement of FK constraints requires the triggers sub-system).
10804 */
10805 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
10806 SQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int);
10807 SQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);
10808 SQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int);
10809 SQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);
10810 SQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);
10811 SQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);
10812 #else
10813   #define sqlite3FkActions(a,b,c,d)
10814   #define sqlite3FkCheck(a,b,c,d)
10815   #define sqlite3FkDropTable(a,b,c)
10816   #define sqlite3FkOldmask(a,b)      0
10817   #define sqlite3FkRequired(a,b,c,d) 0
10818 #endif
10819 #ifndef SQLITE_OMIT_FOREIGN_KEY
10820 SQLITE_PRIVATE   void sqlite3FkDelete(Table*);
10821 #else
10822   #define sqlite3FkDelete(a)
10823 #endif
10824
10825
10826 /*
10827 ** Available fault injectors.  Should be numbered beginning with 0.
10828 */
10829 #define SQLITE_FAULTINJECTOR_MALLOC     0
10830 #define SQLITE_FAULTINJECTOR_COUNT      1
10831
10832 /*
10833 ** The interface to the code in fault.c used for identifying "benign"
10834 ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
10835 ** is not defined.
10836 */
10837 #ifndef SQLITE_OMIT_BUILTIN_TEST
10838 SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
10839 SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
10840 #else
10841   #define sqlite3BeginBenignMalloc()
10842   #define sqlite3EndBenignMalloc()
10843 #endif
10844
10845 #define IN_INDEX_ROWID           1
10846 #define IN_INDEX_EPH             2
10847 #define IN_INDEX_INDEX           3
10848 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
10849
10850 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
10851 SQLITE_PRIVATE   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
10852 SQLITE_PRIVATE   int sqlite3JournalSize(sqlite3_vfs *);
10853 SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
10854 #else
10855   #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
10856 #endif
10857
10858 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
10859 SQLITE_PRIVATE int sqlite3MemJournalSize(void);
10860 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
10861
10862 #if SQLITE_MAX_EXPR_DEPTH>0
10863 SQLITE_PRIVATE   void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
10864 SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
10865 SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
10866 #else
10867   #define sqlite3ExprSetHeight(x,y)
10868   #define sqlite3SelectExprHeight(x) 0
10869   #define sqlite3ExprCheckHeight(x,y)
10870 #endif
10871
10872 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
10873 SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
10874
10875 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
10876 SQLITE_PRIVATE   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
10877 SQLITE_PRIVATE   void sqlite3ConnectionUnlocked(sqlite3 *db);
10878 SQLITE_PRIVATE   void sqlite3ConnectionClosed(sqlite3 *db);
10879 #else
10880   #define sqlite3ConnectionBlocked(x,y)
10881   #define sqlite3ConnectionUnlocked(x)
10882   #define sqlite3ConnectionClosed(x)
10883 #endif
10884
10885 #ifdef SQLITE_DEBUG
10886 SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
10887 #endif
10888
10889 /*
10890 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
10891 ** sqlite3IoTrace is a pointer to a printf-like routine used to
10892 ** print I/O tracing messages. 
10893 */
10894 #ifdef SQLITE_ENABLE_IOTRACE
10895 # define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
10896 SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
10897 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
10898 #else
10899 # define IOTRACE(A)
10900 # define sqlite3VdbeIOTraceSql(X)
10901 #endif
10902
10903 /*
10904 ** These routines are available for the mem2.c debugging memory allocator
10905 ** only.  They are used to verify that different "types" of memory
10906 ** allocations are properly tracked by the system.
10907 **
10908 ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
10909 ** the MEMTYPE_* macros defined below.  The type must be a bitmask with
10910 ** a single bit set.
10911 **
10912 ** sqlite3MemdebugHasType() returns true if any of the bits in its second
10913 ** argument match the type set by the previous sqlite3MemdebugSetType().
10914 ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
10915 ** For example:
10916 **
10917 **     assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
10918 **
10919 ** Perhaps the most important point is the difference between MEMTYPE_HEAP
10920 ** and MEMTYPE_DB.  If an allocation is MEMTYPE_DB, that means it might have
10921 ** been allocated by lookaside, except the allocation was too large or
10922 ** lookaside was already full.  It is important to verify that allocations
10923 ** that might have been satisfied by lookaside are not passed back to 
10924 ** non-lookaside free() routines.  Asserts such as the example above are
10925 ** placed on the non-lookaside free() routines to verify this constraint. 
10926 **
10927 ** All of this is no-op for a production build.  It only comes into
10928 ** play when the SQLITE_MEMDEBUG compile-time option is used.
10929 */
10930 #ifdef SQLITE_MEMDEBUG
10931 SQLITE_PRIVATE   void sqlite3MemdebugSetType(void*,u8);
10932 SQLITE_PRIVATE   int sqlite3MemdebugHasType(void*,u8);
10933 #else
10934 # define sqlite3MemdebugSetType(X,Y)  /* no-op */
10935 # define sqlite3MemdebugHasType(X,Y)  1
10936 #endif
10937 #define MEMTYPE_HEAP     0x01    /* General heap allocations */
10938 #define MEMTYPE_DB       0x02    /* Associated with a database connection */
10939 #define MEMTYPE_SCRATCH  0x04    /* Scratch allocations */
10940 #define MEMTYPE_PCACHE   0x08    /* Page cache allocations */
10941
10942 #endif /* _SQLITEINT_H_ */
10943
10944 /************** End of sqliteInt.h *******************************************/
10945 /************** Begin file global.c ******************************************/
10946 /*
10947 ** 2008 June 13
10948 **
10949 ** The author disclaims copyright to this source code.  In place of
10950 ** a legal notice, here is a blessing:
10951 **
10952 **    May you do good and not evil.
10953 **    May you find forgiveness for yourself and forgive others.
10954 **    May you share freely, never taking more than you give.
10955 **
10956 *************************************************************************
10957 **
10958 ** This file contains definitions of global variables and contants.
10959 */
10960
10961 /* An array to map all upper-case characters into their corresponding
10962 ** lower-case character. 
10963 **
10964 ** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
10965 ** handle case conversions for the UTF character set since the tables
10966 ** involved are nearly as big or bigger than SQLite itself.
10967 */
10968 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
10969 #ifdef SQLITE_ASCII
10970       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
10971      18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
10972      36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
10973      54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
10974     104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
10975     122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
10976     108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
10977     126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
10978     144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
10979     162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
10980     180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
10981     198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
10982     216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
10983     234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
10984     252,253,254,255
10985 #endif
10986 #ifdef SQLITE_EBCDIC
10987       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
10988      16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
10989      32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
10990      48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
10991      64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
10992      80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
10993      96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
10994     112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
10995     128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
10996     144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
10997     160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
10998     176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
10999     192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
11000     208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
11001     224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
11002     239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
11003 #endif
11004 };
11005
11006 /*
11007 ** The following 256 byte lookup table is used to support SQLites built-in
11008 ** equivalents to the following standard library functions:
11009 **
11010 **   isspace()                        0x01
11011 **   isalpha()                        0x02
11012 **   isdigit()                        0x04
11013 **   isalnum()                        0x06
11014 **   isxdigit()                       0x08
11015 **   toupper()                        0x20
11016 **   SQLite identifier character      0x40
11017 **
11018 ** Bit 0x20 is set if the mapped character requires translation to upper
11019 ** case. i.e. if the character is a lower-case ASCII character.
11020 ** If x is a lower-case ASCII character, then its upper-case equivalent
11021 ** is (x - 0x20). Therefore toupper() can be implemented as:
11022 **
11023 **   (x & ~(map[x]&0x20))
11024 **
11025 ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
11026 ** array. tolower() is used more often than toupper() by SQLite.
11027 **
11028 ** Bit 0x40 is set if the character non-alphanumeric and can be used in an 
11029 ** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
11030 ** non-ASCII UTF character. Hence the test for whether or not a character is
11031 ** part of an identifier is 0x46.
11032 **
11033 ** SQLite's versions are identical to the standard versions assuming a
11034 ** locale of "C". They are implemented as macros in sqliteInt.h.
11035 */
11036 #ifdef SQLITE_ASCII
11037 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
11038   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
11039   0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
11040   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
11041   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
11042   0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,  /* 20..27     !"#$%&' */
11043   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
11044   0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
11045   0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
11046
11047   0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
11048   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
11049   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
11050   0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\]^_ */
11051   0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
11052   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
11053   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
11054   0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
11055
11056   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */
11057   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */
11058   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */
11059   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */
11060   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */
11061   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */
11062   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */
11063   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */
11064
11065   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */
11066   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */
11067   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */
11068   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */
11069   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
11070   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
11071   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
11072   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
11073 };
11074 #endif
11075
11076
11077
11078 /*
11079 ** The following singleton contains the global configuration for
11080 ** the SQLite library.
11081 */
11082 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
11083    SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
11084    1,                         /* bCoreMutex */
11085    SQLITE_THREADSAFE==1,      /* bFullMutex */
11086    0x7ffffffe,                /* mxStrlen */
11087    100,                       /* szLookaside */
11088    500,                       /* nLookaside */
11089    {0,0,0,0,0,0,0,0},         /* m */
11090    {0,0,0,0,0,0,0,0,0},       /* mutex */
11091    {0,0,0,0,0,0,0,0,0,0,0},   /* pcache */
11092    (void*)0,                  /* pHeap */
11093    0,                         /* nHeap */
11094    0, 0,                      /* mnHeap, mxHeap */
11095    (void*)0,                  /* pScratch */
11096    0,                         /* szScratch */
11097    0,                         /* nScratch */
11098    (void*)0,                  /* pPage */
11099    0,                         /* szPage */
11100    0,                         /* nPage */
11101    0,                         /* mxParserStack */
11102    0,                         /* sharedCacheEnabled */
11103    /* All the rest should always be initialized to zero */
11104    0,                         /* isInit */
11105    0,                         /* inProgress */
11106    0,                         /* isMutexInit */
11107    0,                         /* isMallocInit */
11108    0,                         /* isPCacheInit */
11109    0,                         /* pInitMutex */
11110    0,                         /* nRefInitMutex */
11111    0,                         /* xLog */
11112    0,                         /* pLogArg */
11113 };
11114
11115
11116 /*
11117 ** Hash table for global functions - functions common to all
11118 ** database connections.  After initialization, this table is
11119 ** read-only.
11120 */
11121 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
11122
11123 /*
11124 ** Constant tokens for values 0 and 1.
11125 */
11126 SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
11127    { "0", 1 },
11128    { "1", 1 }
11129 };
11130
11131
11132 /*
11133 ** The value of the "pending" byte must be 0x40000000 (1 byte past the
11134 ** 1-gibabyte boundary) in a compatible database.  SQLite never uses
11135 ** the database page that contains the pending byte.  It never attempts
11136 ** to read or write that page.  The pending byte page is set assign
11137 ** for use by the VFS layers as space for managing file locks.
11138 **
11139 ** During testing, it is often desirable to move the pending byte to
11140 ** a different position in the file.  This allows code that has to
11141 ** deal with the pending byte to run on files that are much smaller
11142 ** than 1 GiB.  The sqlite3_test_control() interface can be used to
11143 ** move the pending byte.
11144 **
11145 ** IMPORTANT:  Changing the pending byte to any value other than
11146 ** 0x40000000 results in an incompatible database file format!
11147 ** Changing the pending byte during operating results in undefined
11148 ** and dileterious behavior.
11149 */
11150 #ifndef SQLITE_OMIT_WSD
11151 SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
11152 #endif
11153
11154 /*
11155 ** Properties of opcodes.  The OPFLG_INITIALIZER macro is
11156 ** created by mkopcodeh.awk during compilation.  Data is obtained
11157 ** from the comments following the "case OP_xxxx:" statements in
11158 ** the vdbe.c file.  
11159 */
11160 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
11161
11162 /************** End of global.c **********************************************/
11163 /************** Begin file ctime.c *******************************************/
11164 /*
11165 ** 2010 February 23
11166 **
11167 ** The author disclaims copyright to this source code.  In place of
11168 ** a legal notice, here is a blessing:
11169 **
11170 **    May you do good and not evil.
11171 **    May you find forgiveness for yourself and forgive others.
11172 **    May you share freely, never taking more than you give.
11173 **
11174 *************************************************************************
11175 **
11176 ** This file implements routines used to report what compile-time options
11177 ** SQLite was built with.
11178 */
11179
11180 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
11181
11182
11183 /*
11184 ** An array of names of all compile-time options.  This array should 
11185 ** be sorted A-Z.
11186 **
11187 ** This array looks large, but in a typical installation actually uses
11188 ** only a handful of compile-time options, so most times this array is usually
11189 ** rather short and uses little memory space.
11190 */
11191 static const char * const azCompileOpt[] = {
11192
11193 /* These macros are provided to "stringify" the value of the define
11194 ** for those options in which the value is meaningful. */
11195 #define CTIMEOPT_VAL_(opt) #opt
11196 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
11197
11198 #ifdef SQLITE_32BIT_ROWID
11199   "32BIT_ROWID",
11200 #endif
11201 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
11202   "4_BYTE_ALIGNED_MALLOC",
11203 #endif
11204 #ifdef SQLITE_CASE_SENSITIVE_LIKE
11205   "CASE_SENSITIVE_LIKE",
11206 #endif
11207 #ifdef SQLITE_CHECK_PAGES
11208   "CHECK_PAGES",
11209 #endif
11210 #ifdef SQLITE_COVERAGE_TEST
11211   "COVERAGE_TEST",
11212 #endif
11213 #ifdef SQLITE_DEBUG
11214   "DEBUG",
11215 #endif
11216 #ifdef SQLITE_DEFAULT_LOCKING_MODE
11217   "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
11218 #endif
11219 #ifdef SQLITE_DISABLE_DIRSYNC
11220   "DISABLE_DIRSYNC",
11221 #endif
11222 #ifdef SQLITE_DISABLE_LFS
11223   "DISABLE_LFS",
11224 #endif
11225 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
11226   "ENABLE_ATOMIC_WRITE",
11227 #endif
11228 #ifdef SQLITE_ENABLE_CEROD
11229   "ENABLE_CEROD",
11230 #endif
11231 #ifdef SQLITE_ENABLE_COLUMN_METADATA
11232   "ENABLE_COLUMN_METADATA",
11233 #endif
11234 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
11235   "ENABLE_EXPENSIVE_ASSERT",
11236 #endif
11237 #ifdef SQLITE_ENABLE_FTS1
11238   "ENABLE_FTS1",
11239 #endif
11240 #ifdef SQLITE_ENABLE_FTS2
11241   "ENABLE_FTS2",
11242 #endif
11243 #ifdef SQLITE_ENABLE_FTS3
11244   "ENABLE_FTS3",
11245 #endif
11246 #ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
11247   "ENABLE_FTS3_PARENTHESIS",
11248 #endif
11249 #ifdef SQLITE_ENABLE_FTS4
11250   "ENABLE_FTS4",
11251 #endif
11252 #ifdef SQLITE_ENABLE_ICU
11253   "ENABLE_ICU",
11254 #endif
11255 #ifdef SQLITE_ENABLE_IOTRACE
11256   "ENABLE_IOTRACE",
11257 #endif
11258 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
11259   "ENABLE_LOAD_EXTENSION",
11260 #endif
11261 #ifdef SQLITE_ENABLE_LOCKING_STYLE
11262   "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
11263 #endif
11264 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
11265   "ENABLE_MEMORY_MANAGEMENT",
11266 #endif
11267 #ifdef SQLITE_ENABLE_MEMSYS3
11268   "ENABLE_MEMSYS3",
11269 #endif
11270 #ifdef SQLITE_ENABLE_MEMSYS5
11271   "ENABLE_MEMSYS5",
11272 #endif
11273 #ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
11274   "ENABLE_OVERSIZE_CELL_CHECK",
11275 #endif
11276 #ifdef SQLITE_ENABLE_RTREE
11277   "ENABLE_RTREE",
11278 #endif
11279 #ifdef SQLITE_ENABLE_STAT2
11280   "ENABLE_STAT2",
11281 #endif
11282 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
11283   "ENABLE_UNLOCK_NOTIFY",
11284 #endif
11285 #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
11286   "ENABLE_UPDATE_DELETE_LIMIT",
11287 #endif
11288 #ifdef SQLITE_HAS_CODEC
11289   "HAS_CODEC",
11290 #endif
11291 #ifdef SQLITE_HAVE_ISNAN
11292   "HAVE_ISNAN",
11293 #endif
11294 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
11295   "HOMEGROWN_RECURSIVE_MUTEX",
11296 #endif
11297 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
11298   "IGNORE_AFP_LOCK_ERRORS",
11299 #endif
11300 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
11301   "IGNORE_FLOCK_LOCK_ERRORS",
11302 #endif
11303 #ifdef SQLITE_INT64_TYPE
11304   "INT64_TYPE",
11305 #endif
11306 #ifdef SQLITE_LOCK_TRACE
11307   "LOCK_TRACE",
11308 #endif
11309 #ifdef SQLITE_MEMDEBUG
11310   "MEMDEBUG",
11311 #endif
11312 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
11313   "MIXED_ENDIAN_64BIT_FLOAT",
11314 #endif
11315 #ifdef SQLITE_NO_SYNC
11316   "NO_SYNC",
11317 #endif
11318 #ifdef SQLITE_OMIT_ALTERTABLE
11319   "OMIT_ALTERTABLE",
11320 #endif
11321 #ifdef SQLITE_OMIT_ANALYZE
11322   "OMIT_ANALYZE",
11323 #endif
11324 #ifdef SQLITE_OMIT_ATTACH
11325   "OMIT_ATTACH",
11326 #endif
11327 #ifdef SQLITE_OMIT_AUTHORIZATION
11328   "OMIT_AUTHORIZATION",
11329 #endif
11330 #ifdef SQLITE_OMIT_AUTOINCREMENT
11331   "OMIT_AUTOINCREMENT",
11332 #endif
11333 #ifdef SQLITE_OMIT_AUTOINIT
11334   "OMIT_AUTOINIT",
11335 #endif
11336 #ifdef SQLITE_OMIT_AUTOMATIC_INDEX
11337   "OMIT_AUTOMATIC_INDEX",
11338 #endif
11339 #ifdef SQLITE_OMIT_AUTOVACUUM
11340   "OMIT_AUTOVACUUM",
11341 #endif
11342 #ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
11343   "OMIT_BETWEEN_OPTIMIZATION",
11344 #endif
11345 #ifdef SQLITE_OMIT_BLOB_LITERAL
11346   "OMIT_BLOB_LITERAL",
11347 #endif
11348 #ifdef SQLITE_OMIT_BTREECOUNT
11349   "OMIT_BTREECOUNT",
11350 #endif
11351 #ifdef SQLITE_OMIT_BUILTIN_TEST
11352   "OMIT_BUILTIN_TEST",
11353 #endif
11354 #ifdef SQLITE_OMIT_CAST
11355   "OMIT_CAST",
11356 #endif
11357 #ifdef SQLITE_OMIT_CHECK
11358   "OMIT_CHECK",
11359 #endif
11360 /* // redundant
11361 ** #ifdef SQLITE_OMIT_COMPILEOPTION_DIAGS
11362 **   "OMIT_COMPILEOPTION_DIAGS",
11363 ** #endif
11364 */
11365 #ifdef SQLITE_OMIT_COMPLETE
11366   "OMIT_COMPLETE",
11367 #endif
11368 #ifdef SQLITE_OMIT_COMPOUND_SELECT
11369   "OMIT_COMPOUND_SELECT",
11370 #endif
11371 #ifdef SQLITE_OMIT_DATETIME_FUNCS
11372   "OMIT_DATETIME_FUNCS",
11373 #endif
11374 #ifdef SQLITE_OMIT_DECLTYPE
11375   "OMIT_DECLTYPE",
11376 #endif
11377 #ifdef SQLITE_OMIT_DEPRECATED
11378   "OMIT_DEPRECATED",
11379 #endif
11380 #ifdef SQLITE_OMIT_DISKIO
11381   "OMIT_DISKIO",
11382 #endif
11383 #ifdef SQLITE_OMIT_EXPLAIN
11384   "OMIT_EXPLAIN",
11385 #endif
11386 #ifdef SQLITE_OMIT_FLAG_PRAGMAS
11387   "OMIT_FLAG_PRAGMAS",
11388 #endif
11389 #ifdef SQLITE_OMIT_FLOATING_POINT
11390   "OMIT_FLOATING_POINT",
11391 #endif
11392 #ifdef SQLITE_OMIT_FOREIGN_KEY
11393   "OMIT_FOREIGN_KEY",
11394 #endif
11395 #ifdef SQLITE_OMIT_GET_TABLE
11396   "OMIT_GET_TABLE",
11397 #endif
11398 #ifdef SQLITE_OMIT_INCRBLOB
11399   "OMIT_INCRBLOB",
11400 #endif
11401 #ifdef SQLITE_OMIT_INTEGRITY_CHECK
11402   "OMIT_INTEGRITY_CHECK",
11403 #endif
11404 #ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
11405   "OMIT_LIKE_OPTIMIZATION",
11406 #endif
11407 #ifdef SQLITE_OMIT_LOAD_EXTENSION
11408   "OMIT_LOAD_EXTENSION",
11409 #endif
11410 #ifdef SQLITE_OMIT_LOCALTIME
11411   "OMIT_LOCALTIME",
11412 #endif
11413 #ifdef SQLITE_OMIT_LOOKASIDE
11414   "OMIT_LOOKASIDE",
11415 #endif
11416 #ifdef SQLITE_OMIT_MEMORYDB
11417   "OMIT_MEMORYDB",
11418 #endif
11419 #ifdef SQLITE_OMIT_OR_OPTIMIZATION
11420   "OMIT_OR_OPTIMIZATION",
11421 #endif
11422 #ifdef SQLITE_OMIT_PAGER_PRAGMAS
11423   "OMIT_PAGER_PRAGMAS",
11424 #endif
11425 #ifdef SQLITE_OMIT_PRAGMA
11426   "OMIT_PRAGMA",
11427 #endif
11428 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
11429   "OMIT_PROGRESS_CALLBACK",
11430 #endif
11431 #ifdef SQLITE_OMIT_QUICKBALANCE
11432   "OMIT_QUICKBALANCE",
11433 #endif
11434 #ifdef SQLITE_OMIT_REINDEX
11435   "OMIT_REINDEX",
11436 #endif
11437 #ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
11438   "OMIT_SCHEMA_PRAGMAS",
11439 #endif
11440 #ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
11441   "OMIT_SCHEMA_VERSION_PRAGMAS",
11442 #endif
11443 #ifdef SQLITE_OMIT_SHARED_CACHE
11444   "OMIT_SHARED_CACHE",
11445 #endif
11446 #ifdef SQLITE_OMIT_SUBQUERY
11447   "OMIT_SUBQUERY",
11448 #endif
11449 #ifdef SQLITE_OMIT_TCL_VARIABLE
11450   "OMIT_TCL_VARIABLE",
11451 #endif
11452 #ifdef SQLITE_OMIT_TEMPDB
11453   "OMIT_TEMPDB",
11454 #endif
11455 #ifdef SQLITE_OMIT_TRACE
11456   "OMIT_TRACE",
11457 #endif
11458 #ifdef SQLITE_OMIT_TRIGGER
11459   "OMIT_TRIGGER",
11460 #endif
11461 #ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
11462   "OMIT_TRUNCATE_OPTIMIZATION",
11463 #endif
11464 #ifdef SQLITE_OMIT_UTF16
11465   "OMIT_UTF16",
11466 #endif
11467 #ifdef SQLITE_OMIT_VACUUM
11468   "OMIT_VACUUM",
11469 #endif
11470 #ifdef SQLITE_OMIT_VIEW
11471   "OMIT_VIEW",
11472 #endif
11473 #ifdef SQLITE_OMIT_VIRTUALTABLE
11474   "OMIT_VIRTUALTABLE",
11475 #endif
11476 #ifdef SQLITE_OMIT_WAL
11477   "OMIT_WAL",
11478 #endif
11479 #ifdef SQLITE_OMIT_WSD
11480   "OMIT_WSD",
11481 #endif
11482 #ifdef SQLITE_OMIT_XFER_OPT
11483   "OMIT_XFER_OPT",
11484 #endif
11485 #ifdef SQLITE_PERFORMANCE_TRACE
11486   "PERFORMANCE_TRACE",
11487 #endif
11488 #ifdef SQLITE_PROXY_DEBUG
11489   "PROXY_DEBUG",
11490 #endif
11491 #ifdef SQLITE_SECURE_DELETE
11492   "SECURE_DELETE",
11493 #endif
11494 #ifdef SQLITE_SMALL_STACK
11495   "SMALL_STACK",
11496 #endif
11497 #ifdef SQLITE_SOUNDEX
11498   "SOUNDEX",
11499 #endif
11500 #ifdef SQLITE_TCL
11501   "TCL",
11502 #endif
11503 #ifdef SQLITE_TEMP_STORE
11504   "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
11505 #endif
11506 #ifdef SQLITE_TEST
11507   "TEST",
11508 #endif
11509 #ifdef SQLITE_THREADSAFE
11510   "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
11511 #endif
11512 #ifdef SQLITE_USE_ALLOCA
11513   "USE_ALLOCA",
11514 #endif
11515 #ifdef SQLITE_ZERO_MALLOC
11516   "ZERO_MALLOC"
11517 #endif
11518 };
11519
11520 /*
11521 ** Given the name of a compile-time option, return true if that option
11522 ** was used and false if not.
11523 **
11524 ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
11525 ** is not required for a match.
11526 */
11527 SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
11528   int i, n;
11529   if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
11530   n = sqlite3Strlen30(zOptName);
11531
11532   /* Since ArraySize(azCompileOpt) is normally in single digits, a
11533   ** linear search is adequate.  No need for a binary search. */
11534   for(i=0; i<ArraySize(azCompileOpt); i++){
11535     if(   (sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0)
11536        && ( (azCompileOpt[i][n]==0) || (azCompileOpt[i][n]=='=') ) ) return 1;
11537   }
11538   return 0;
11539 }
11540
11541 /*
11542 ** Return the N-th compile-time option string.  If N is out of range,
11543 ** return a NULL pointer.
11544 */
11545 SQLITE_API const char *sqlite3_compileoption_get(int N){
11546   if( N>=0 && N<ArraySize(azCompileOpt) ){
11547     return azCompileOpt[N];
11548   }
11549   return 0;
11550 }
11551
11552 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
11553
11554 /************** End of ctime.c ***********************************************/
11555 /************** Begin file status.c ******************************************/
11556 /*
11557 ** 2008 June 18
11558 **
11559 ** The author disclaims copyright to this source code.  In place of
11560 ** a legal notice, here is a blessing:
11561 **
11562 **    May you do good and not evil.
11563 **    May you find forgiveness for yourself and forgive others.
11564 **    May you share freely, never taking more than you give.
11565 **
11566 *************************************************************************
11567 **
11568 ** This module implements the sqlite3_status() interface and related
11569 ** functionality.
11570 */
11571
11572 /*
11573 ** Variables in which to record status information.
11574 */
11575 typedef struct sqlite3StatType sqlite3StatType;
11576 static SQLITE_WSD struct sqlite3StatType {
11577   int nowValue[9];         /* Current value */
11578   int mxValue[9];          /* Maximum value */
11579 } sqlite3Stat = { {0,}, {0,} };
11580
11581
11582 /* The "wsdStat" macro will resolve to the status information
11583 ** state vector.  If writable static data is unsupported on the target,
11584 ** we have to locate the state vector at run-time.  In the more common
11585 ** case where writable static data is supported, wsdStat can refer directly
11586 ** to the "sqlite3Stat" state vector declared above.
11587 */
11588 #ifdef SQLITE_OMIT_WSD
11589 # define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
11590 # define wsdStat x[0]
11591 #else
11592 # define wsdStatInit
11593 # define wsdStat sqlite3Stat
11594 #endif
11595
11596 /*
11597 ** Return the current value of a status parameter.
11598 */
11599 SQLITE_PRIVATE int sqlite3StatusValue(int op){
11600   wsdStatInit;
11601   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
11602   return wsdStat.nowValue[op];
11603 }
11604
11605 /*
11606 ** Add N to the value of a status record.  It is assumed that the
11607 ** caller holds appropriate locks.
11608 */
11609 SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
11610   wsdStatInit;
11611   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
11612   wsdStat.nowValue[op] += N;
11613   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
11614     wsdStat.mxValue[op] = wsdStat.nowValue[op];
11615   }
11616 }
11617
11618 /*
11619 ** Set the value of a status to X.
11620 */
11621 SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
11622   wsdStatInit;
11623   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
11624   wsdStat.nowValue[op] = X;
11625   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
11626     wsdStat.mxValue[op] = wsdStat.nowValue[op];
11627   }
11628 }
11629
11630 /*
11631 ** Query status information.
11632 **
11633 ** This implementation assumes that reading or writing an aligned
11634 ** 32-bit integer is an atomic operation.  If that assumption is not true,
11635 ** then this routine is not threadsafe.
11636 */
11637 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
11638   wsdStatInit;
11639   if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
11640     return SQLITE_MISUSE_BKPT;
11641   }
11642   *pCurrent = wsdStat.nowValue[op];
11643   *pHighwater = wsdStat.mxValue[op];
11644   if( resetFlag ){
11645     wsdStat.mxValue[op] = wsdStat.nowValue[op];
11646   }
11647   return SQLITE_OK;
11648 }
11649
11650 /*
11651 ** Query status information for a single database connection
11652 */
11653 SQLITE_API int sqlite3_db_status(
11654   sqlite3 *db,          /* The database connection whose status is desired */
11655   int op,               /* Status verb */
11656   int *pCurrent,        /* Write current value here */
11657   int *pHighwater,      /* Write high-water mark here */
11658   int resetFlag         /* Reset high-water mark if true */
11659 ){
11660   switch( op ){
11661     case SQLITE_DBSTATUS_LOOKASIDE_USED: {
11662       *pCurrent = db->lookaside.nOut;
11663       *pHighwater = db->lookaside.mxOut;
11664       if( resetFlag ){
11665         db->lookaside.mxOut = db->lookaside.nOut;
11666       }
11667       break;
11668     }
11669
11670     /* 
11671     ** Return an approximation for the amount of memory currently used
11672     ** by all pagers associated with the given database connection.  The
11673     ** highwater mark is meaningless and is returned as zero.
11674     */
11675     case SQLITE_DBSTATUS_CACHE_USED: {
11676       int totalUsed = 0;
11677       int i;
11678       for(i=0; i<db->nDb; i++){
11679         Btree *pBt = db->aDb[i].pBt;
11680         if( pBt ){
11681           Pager *pPager = sqlite3BtreePager(pBt);
11682           totalUsed += sqlite3PagerMemUsed(pPager);
11683         }
11684       }
11685       *pCurrent = totalUsed;
11686       *pHighwater = 0;
11687       break;
11688     }
11689     default: {
11690       return SQLITE_ERROR;
11691     }
11692   }
11693   return SQLITE_OK;
11694 }
11695
11696 /************** End of status.c **********************************************/
11697 /************** Begin file date.c ********************************************/
11698 /*
11699 ** 2003 October 31
11700 **
11701 ** The author disclaims copyright to this source code.  In place of
11702 ** a legal notice, here is a blessing:
11703 **
11704 **    May you do good and not evil.
11705 **    May you find forgiveness for yourself and forgive others.
11706 **    May you share freely, never taking more than you give.
11707 **
11708 *************************************************************************
11709 ** This file contains the C functions that implement date and time
11710 ** functions for SQLite.  
11711 **
11712 ** There is only one exported symbol in this file - the function
11713 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
11714 ** All other code has file scope.
11715 **
11716 ** SQLite processes all times and dates as Julian Day numbers.  The
11717 ** dates and times are stored as the number of days since noon
11718 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
11719 ** calendar system. 
11720 **
11721 ** 1970-01-01 00:00:00 is JD 2440587.5
11722 ** 2000-01-01 00:00:00 is JD 2451544.5
11723 **
11724 ** This implemention requires years to be expressed as a 4-digit number
11725 ** which means that only dates between 0000-01-01 and 9999-12-31 can
11726 ** be represented, even though julian day numbers allow a much wider
11727 ** range of dates.
11728 **
11729 ** The Gregorian calendar system is used for all dates and times,
11730 ** even those that predate the Gregorian calendar.  Historians usually
11731 ** use the Julian calendar for dates prior to 1582-10-15 and for some
11732 ** dates afterwards, depending on locale.  Beware of this difference.
11733 **
11734 ** The conversion algorithms are implemented based on descriptions
11735 ** in the following text:
11736 **
11737 **      Jean Meeus
11738 **      Astronomical Algorithms, 2nd Edition, 1998
11739 **      ISBM 0-943396-61-1
11740 **      Willmann-Bell, Inc
11741 **      Richmond, Virginia (USA)
11742 */
11743 #include <time.h>
11744
11745 #ifndef SQLITE_OMIT_DATETIME_FUNCS
11746
11747 /*
11748 ** On recent Windows platforms, the localtime_s() function is available
11749 ** as part of the "Secure CRT". It is essentially equivalent to 
11750 ** localtime_r() available under most POSIX platforms, except that the 
11751 ** order of the parameters is reversed.
11752 **
11753 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
11754 **
11755 ** If the user has not indicated to use localtime_r() or localtime_s()
11756 ** already, check for an MSVC build environment that provides 
11757 ** localtime_s().
11758 */
11759 #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
11760      defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
11761 #define HAVE_LOCALTIME_S 1
11762 #endif
11763
11764 /*
11765 ** A structure for holding a single date and time.
11766 */
11767 typedef struct DateTime DateTime;
11768 struct DateTime {
11769   sqlite3_int64 iJD; /* The julian day number times 86400000 */
11770   int Y, M, D;       /* Year, month, and day */
11771   int h, m;          /* Hour and minutes */
11772   int tz;            /* Timezone offset in minutes */
11773   double s;          /* Seconds */
11774   char validYMD;     /* True (1) if Y,M,D are valid */
11775   char validHMS;     /* True (1) if h,m,s are valid */
11776   char validJD;      /* True (1) if iJD is valid */
11777   char validTZ;      /* True (1) if tz is valid */
11778 };
11779
11780
11781 /*
11782 ** Convert zDate into one or more integers.  Additional arguments
11783 ** come in groups of 5 as follows:
11784 **
11785 **       N       number of digits in the integer
11786 **       min     minimum allowed value of the integer
11787 **       max     maximum allowed value of the integer
11788 **       nextC   first character after the integer
11789 **       pVal    where to write the integers value.
11790 **
11791 ** Conversions continue until one with nextC==0 is encountered.
11792 ** The function returns the number of successful conversions.
11793 */
11794 static int getDigits(const char *zDate, ...){
11795   va_list ap;
11796   int val;
11797   int N;
11798   int min;
11799   int max;
11800   int nextC;
11801   int *pVal;
11802   int cnt = 0;
11803   va_start(ap, zDate);
11804   do{
11805     N = va_arg(ap, int);
11806     min = va_arg(ap, int);
11807     max = va_arg(ap, int);
11808     nextC = va_arg(ap, int);
11809     pVal = va_arg(ap, int*);
11810     val = 0;
11811     while( N-- ){
11812       if( !sqlite3Isdigit(*zDate) ){
11813         goto end_getDigits;
11814       }
11815       val = val*10 + *zDate - '0';
11816       zDate++;
11817     }
11818     if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
11819       goto end_getDigits;
11820     }
11821     *pVal = val;
11822     zDate++;
11823     cnt++;
11824   }while( nextC );
11825 end_getDigits:
11826   va_end(ap);
11827   return cnt;
11828 }
11829
11830 /*
11831 ** Read text from z[] and convert into a floating point number.  Return
11832 ** the number of digits converted.
11833 */
11834 #define getValue sqlite3AtoF
11835
11836 /*
11837 ** Parse a timezone extension on the end of a date-time.
11838 ** The extension is of the form:
11839 **
11840 **        (+/-)HH:MM
11841 **
11842 ** Or the "zulu" notation:
11843 **
11844 **        Z
11845 **
11846 ** If the parse is successful, write the number of minutes
11847 ** of change in p->tz and return 0.  If a parser error occurs,
11848 ** return non-zero.
11849 **
11850 ** A missing specifier is not considered an error.
11851 */
11852 static int parseTimezone(const char *zDate, DateTime *p){
11853   int sgn = 0;
11854   int nHr, nMn;
11855   int c;
11856   while( sqlite3Isspace(*zDate) ){ zDate++; }
11857   p->tz = 0;
11858   c = *zDate;
11859   if( c=='-' ){
11860     sgn = -1;
11861   }else if( c=='+' ){
11862     sgn = +1;
11863   }else if( c=='Z' || c=='z' ){
11864     zDate++;
11865     goto zulu_time;
11866   }else{
11867     return c!=0;
11868   }
11869   zDate++;
11870   if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
11871     return 1;
11872   }
11873   zDate += 5;
11874   p->tz = sgn*(nMn + nHr*60);
11875 zulu_time:
11876   while( sqlite3Isspace(*zDate) ){ zDate++; }
11877   return *zDate!=0;
11878 }
11879
11880 /*
11881 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
11882 ** The HH, MM, and SS must each be exactly 2 digits.  The
11883 ** fractional seconds FFFF can be one or more digits.
11884 **
11885 ** Return 1 if there is a parsing error and 0 on success.
11886 */
11887 static int parseHhMmSs(const char *zDate, DateTime *p){
11888   int h, m, s;
11889   double ms = 0.0;
11890   if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
11891     return 1;
11892   }
11893   zDate += 5;
11894   if( *zDate==':' ){
11895     zDate++;
11896     if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
11897       return 1;
11898     }
11899     zDate += 2;
11900     if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
11901       double rScale = 1.0;
11902       zDate++;
11903       while( sqlite3Isdigit(*zDate) ){
11904         ms = ms*10.0 + *zDate - '0';
11905         rScale *= 10.0;
11906         zDate++;
11907       }
11908       ms /= rScale;
11909     }
11910   }else{
11911     s = 0;
11912   }
11913   p->validJD = 0;
11914   p->validHMS = 1;
11915   p->h = h;
11916   p->m = m;
11917   p->s = s + ms;
11918   if( parseTimezone(zDate, p) ) return 1;
11919   p->validTZ = (p->tz!=0)?1:0;
11920   return 0;
11921 }
11922
11923 /*
11924 ** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
11925 ** that the YYYY-MM-DD is according to the Gregorian calendar.
11926 **
11927 ** Reference:  Meeus page 61
11928 */
11929 static void computeJD(DateTime *p){
11930   int Y, M, D, A, B, X1, X2;
11931
11932   if( p->validJD ) return;
11933   if( p->validYMD ){
11934     Y = p->Y;
11935     M = p->M;
11936     D = p->D;
11937   }else{
11938     Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
11939     M = 1;
11940     D = 1;
11941   }
11942   if( M<=2 ){
11943     Y--;
11944     M += 12;
11945   }
11946   A = Y/100;
11947   B = 2 - A + (A/4);
11948   X1 = 36525*(Y+4716)/100;
11949   X2 = 306001*(M+1)/10000;
11950   p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
11951   p->validJD = 1;
11952   if( p->validHMS ){
11953     p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
11954     if( p->validTZ ){
11955       p->iJD -= p->tz*60000;
11956       p->validYMD = 0;
11957       p->validHMS = 0;
11958       p->validTZ = 0;
11959     }
11960   }
11961 }
11962
11963 /*
11964 ** Parse dates of the form
11965 **
11966 **     YYYY-MM-DD HH:MM:SS.FFF
11967 **     YYYY-MM-DD HH:MM:SS
11968 **     YYYY-MM-DD HH:MM
11969 **     YYYY-MM-DD
11970 **
11971 ** Write the result into the DateTime structure and return 0
11972 ** on success and 1 if the input string is not a well-formed
11973 ** date.
11974 */
11975 static int parseYyyyMmDd(const char *zDate, DateTime *p){
11976   int Y, M, D, neg;
11977
11978   if( zDate[0]=='-' ){
11979     zDate++;
11980     neg = 1;
11981   }else{
11982     neg = 0;
11983   }
11984   if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
11985     return 1;
11986   }
11987   zDate += 10;
11988   while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
11989   if( parseHhMmSs(zDate, p)==0 ){
11990     /* We got the time */
11991   }else if( *zDate==0 ){
11992     p->validHMS = 0;
11993   }else{
11994     return 1;
11995   }
11996   p->validJD = 0;
11997   p->validYMD = 1;
11998   p->Y = neg ? -Y : Y;
11999   p->M = M;
12000   p->D = D;
12001   if( p->validTZ ){
12002     computeJD(p);
12003   }
12004   return 0;
12005 }
12006
12007 /*
12008 ** Set the time to the current time reported by the VFS
12009 */
12010 static void setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
12011   sqlite3 *db = sqlite3_context_db_handle(context);
12012   sqlite3OsCurrentTimeInt64(db->pVfs, &p->iJD);
12013   p->validJD = 1;
12014 }
12015
12016 /*
12017 ** Attempt to parse the given string into a Julian Day Number.  Return
12018 ** the number of errors.
12019 **
12020 ** The following are acceptable forms for the input string:
12021 **
12022 **      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
12023 **      DDDD.DD 
12024 **      now
12025 **
12026 ** In the first form, the +/-HH:MM is always optional.  The fractional
12027 ** seconds extension (the ".FFF") is optional.  The seconds portion
12028 ** (":SS.FFF") is option.  The year and date can be omitted as long
12029 ** as there is a time string.  The time string can be omitted as long
12030 ** as there is a year and date.
12031 */
12032 static int parseDateOrTime(
12033   sqlite3_context *context, 
12034   const char *zDate, 
12035   DateTime *p
12036 ){
12037   int isRealNum;    /* Return from sqlite3IsNumber().  Not used */
12038   if( parseYyyyMmDd(zDate,p)==0 ){
12039     return 0;
12040   }else if( parseHhMmSs(zDate, p)==0 ){
12041     return 0;
12042   }else if( sqlite3StrICmp(zDate,"now")==0){
12043     setDateTimeToCurrent(context, p);
12044     return 0;
12045   }else if( sqlite3IsNumber(zDate, &isRealNum, SQLITE_UTF8) ){
12046     double r;
12047     getValue(zDate, &r);
12048     p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
12049     p->validJD = 1;
12050     return 0;
12051   }
12052   return 1;
12053 }
12054
12055 /*
12056 ** Compute the Year, Month, and Day from the julian day number.
12057 */
12058 static void computeYMD(DateTime *p){
12059   int Z, A, B, C, D, E, X1;
12060   if( p->validYMD ) return;
12061   if( !p->validJD ){
12062     p->Y = 2000;
12063     p->M = 1;
12064     p->D = 1;
12065   }else{
12066     Z = (int)((p->iJD + 43200000)/86400000);
12067     A = (int)((Z - 1867216.25)/36524.25);
12068     A = Z + 1 + A - (A/4);
12069     B = A + 1524;
12070     C = (int)((B - 122.1)/365.25);
12071     D = (36525*C)/100;
12072     E = (int)((B-D)/30.6001);
12073     X1 = (int)(30.6001*E);
12074     p->D = B - D - X1;
12075     p->M = E<14 ? E-1 : E-13;
12076     p->Y = p->M>2 ? C - 4716 : C - 4715;
12077   }
12078   p->validYMD = 1;
12079 }
12080
12081 /*
12082 ** Compute the Hour, Minute, and Seconds from the julian day number.
12083 */
12084 static void computeHMS(DateTime *p){
12085   int s;
12086   if( p->validHMS ) return;
12087   computeJD(p);
12088   s = (int)((p->iJD + 43200000) % 86400000);
12089   p->s = s/1000.0;
12090   s = (int)p->s;
12091   p->s -= s;
12092   p->h = s/3600;
12093   s -= p->h*3600;
12094   p->m = s/60;
12095   p->s += s - p->m*60;
12096   p->validHMS = 1;
12097 }
12098
12099 /*
12100 ** Compute both YMD and HMS
12101 */
12102 static void computeYMD_HMS(DateTime *p){
12103   computeYMD(p);
12104   computeHMS(p);
12105 }
12106
12107 /*
12108 ** Clear the YMD and HMS and the TZ
12109 */
12110 static void clearYMD_HMS_TZ(DateTime *p){
12111   p->validYMD = 0;
12112   p->validHMS = 0;
12113   p->validTZ = 0;
12114 }
12115
12116 #ifndef SQLITE_OMIT_LOCALTIME
12117 /*
12118 ** Compute the difference (in milliseconds)
12119 ** between localtime and UTC (a.k.a. GMT)
12120 ** for the time value p where p is in UTC.
12121 */
12122 static sqlite3_int64 localtimeOffset(DateTime *p){
12123   DateTime x, y;
12124   time_t t;
12125   x = *p;
12126   computeYMD_HMS(&x);
12127   if( x.Y<1971 || x.Y>=2038 ){
12128     x.Y = 2000;
12129     x.M = 1;
12130     x.D = 1;
12131     x.h = 0;
12132     x.m = 0;
12133     x.s = 0.0;
12134   } else {
12135     int s = (int)(x.s + 0.5);
12136     x.s = s;
12137   }
12138   x.tz = 0;
12139   x.validJD = 0;
12140   computeJD(&x);
12141   t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
12142 #ifdef HAVE_LOCALTIME_R
12143   {
12144     struct tm sLocal;
12145     localtime_r(&t, &sLocal);
12146     y.Y = sLocal.tm_year + 1900;
12147     y.M = sLocal.tm_mon + 1;
12148     y.D = sLocal.tm_mday;
12149     y.h = sLocal.tm_hour;
12150     y.m = sLocal.tm_min;
12151     y.s = sLocal.tm_sec;
12152   }
12153 #elif defined(HAVE_LOCALTIME_S) && HAVE_LOCALTIME_S
12154   {
12155     struct tm sLocal;
12156     localtime_s(&sLocal, &t);
12157     y.Y = sLocal.tm_year + 1900;
12158     y.M = sLocal.tm_mon + 1;
12159     y.D = sLocal.tm_mday;
12160     y.h = sLocal.tm_hour;
12161     y.m = sLocal.tm_min;
12162     y.s = sLocal.tm_sec;
12163   }
12164 #else
12165   {
12166     struct tm *pTm;
12167     sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
12168     pTm = localtime(&t);
12169     y.Y = pTm->tm_year + 1900;
12170     y.M = pTm->tm_mon + 1;
12171     y.D = pTm->tm_mday;
12172     y.h = pTm->tm_hour;
12173     y.m = pTm->tm_min;
12174     y.s = pTm->tm_sec;
12175     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
12176   }
12177 #endif
12178   y.validYMD = 1;
12179   y.validHMS = 1;
12180   y.validJD = 0;
12181   y.validTZ = 0;
12182   computeJD(&y);
12183   return y.iJD - x.iJD;
12184 }
12185 #endif /* SQLITE_OMIT_LOCALTIME */
12186
12187 /*
12188 ** Process a modifier to a date-time stamp.  The modifiers are
12189 ** as follows:
12190 **
12191 **     NNN days
12192 **     NNN hours
12193 **     NNN minutes
12194 **     NNN.NNNN seconds
12195 **     NNN months
12196 **     NNN years
12197 **     start of month
12198 **     start of year
12199 **     start of week
12200 **     start of day
12201 **     weekday N
12202 **     unixepoch
12203 **     localtime
12204 **     utc
12205 **
12206 ** Return 0 on success and 1 if there is any kind of error.
12207 */
12208 static int parseModifier(const char *zMod, DateTime *p){
12209   int rc = 1;
12210   int n;
12211   double r;
12212   char *z, zBuf[30];
12213   z = zBuf;
12214   for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
12215     z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
12216   }
12217   z[n] = 0;
12218   switch( z[0] ){
12219 #ifndef SQLITE_OMIT_LOCALTIME
12220     case 'l': {
12221       /*    localtime
12222       **
12223       ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
12224       ** show local time.
12225       */
12226       if( strcmp(z, "localtime")==0 ){
12227         computeJD(p);
12228         p->iJD += localtimeOffset(p);
12229         clearYMD_HMS_TZ(p);
12230         rc = 0;
12231       }
12232       break;
12233     }
12234 #endif
12235     case 'u': {
12236       /*
12237       **    unixepoch
12238       **
12239       ** Treat the current value of p->iJD as the number of
12240       ** seconds since 1970.  Convert to a real julian day number.
12241       */
12242       if( strcmp(z, "unixepoch")==0 && p->validJD ){
12243         p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
12244         clearYMD_HMS_TZ(p);
12245         rc = 0;
12246       }
12247 #ifndef SQLITE_OMIT_LOCALTIME
12248       else if( strcmp(z, "utc")==0 ){
12249         sqlite3_int64 c1;
12250         computeJD(p);
12251         c1 = localtimeOffset(p);
12252         p->iJD -= c1;
12253         clearYMD_HMS_TZ(p);
12254         p->iJD += c1 - localtimeOffset(p);
12255         rc = 0;
12256       }
12257 #endif
12258       break;
12259     }
12260     case 'w': {
12261       /*
12262       **    weekday N
12263       **
12264       ** Move the date to the same time on the next occurrence of
12265       ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
12266       ** date is already on the appropriate weekday, this is a no-op.
12267       */
12268       if( strncmp(z, "weekday ", 8)==0 && getValue(&z[8],&r)>0
12269                  && (n=(int)r)==r && n>=0 && r<7 ){
12270         sqlite3_int64 Z;
12271         computeYMD_HMS(p);
12272         p->validTZ = 0;
12273         p->validJD = 0;
12274         computeJD(p);
12275         Z = ((p->iJD + 129600000)/86400000) % 7;
12276         if( Z>n ) Z -= 7;
12277         p->iJD += (n - Z)*86400000;
12278         clearYMD_HMS_TZ(p);
12279         rc = 0;
12280       }
12281       break;
12282     }
12283     case 's': {
12284       /*
12285       **    start of TTTTT
12286       **
12287       ** Move the date backwards to the beginning of the current day,
12288       ** or month or year.
12289       */
12290       if( strncmp(z, "start of ", 9)!=0 ) break;
12291       z += 9;
12292       computeYMD(p);
12293       p->validHMS = 1;
12294       p->h = p->m = 0;
12295       p->s = 0.0;
12296       p->validTZ = 0;
12297       p->validJD = 0;
12298       if( strcmp(z,"month")==0 ){
12299         p->D = 1;
12300         rc = 0;
12301       }else if( strcmp(z,"year")==0 ){
12302         computeYMD(p);
12303         p->M = 1;
12304         p->D = 1;
12305         rc = 0;
12306       }else if( strcmp(z,"day")==0 ){
12307         rc = 0;
12308       }
12309       break;
12310     }
12311     case '+':
12312     case '-':
12313     case '0':
12314     case '1':
12315     case '2':
12316     case '3':
12317     case '4':
12318     case '5':
12319     case '6':
12320     case '7':
12321     case '8':
12322     case '9': {
12323       double rRounder;
12324       n = getValue(z, &r);
12325       assert( n>=1 );
12326       if( z[n]==':' ){
12327         /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
12328         ** specified number of hours, minutes, seconds, and fractional seconds
12329         ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
12330         ** omitted.
12331         */
12332         const char *z2 = z;
12333         DateTime tx;
12334         sqlite3_int64 day;
12335         if( !sqlite3Isdigit(*z2) ) z2++;
12336         memset(&tx, 0, sizeof(tx));
12337         if( parseHhMmSs(z2, &tx) ) break;
12338         computeJD(&tx);
12339         tx.iJD -= 43200000;
12340         day = tx.iJD/86400000;
12341         tx.iJD -= day*86400000;
12342         if( z[0]=='-' ) tx.iJD = -tx.iJD;
12343         computeJD(p);
12344         clearYMD_HMS_TZ(p);
12345         p->iJD += tx.iJD;
12346         rc = 0;
12347         break;
12348       }
12349       z += n;
12350       while( sqlite3Isspace(*z) ) z++;
12351       n = sqlite3Strlen30(z);
12352       if( n>10 || n<3 ) break;
12353       if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
12354       computeJD(p);
12355       rc = 0;
12356       rRounder = r<0 ? -0.5 : +0.5;
12357       if( n==3 && strcmp(z,"day")==0 ){
12358         p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
12359       }else if( n==4 && strcmp(z,"hour")==0 ){
12360         p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
12361       }else if( n==6 && strcmp(z,"minute")==0 ){
12362         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
12363       }else if( n==6 && strcmp(z,"second")==0 ){
12364         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
12365       }else if( n==5 && strcmp(z,"month")==0 ){
12366         int x, y;
12367         computeYMD_HMS(p);
12368         p->M += (int)r;
12369         x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
12370         p->Y += x;
12371         p->M -= x*12;
12372         p->validJD = 0;
12373         computeJD(p);
12374         y = (int)r;
12375         if( y!=r ){
12376           p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
12377         }
12378       }else if( n==4 && strcmp(z,"year")==0 ){
12379         int y = (int)r;
12380         computeYMD_HMS(p);
12381         p->Y += y;
12382         p->validJD = 0;
12383         computeJD(p);
12384         if( y!=r ){
12385           p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
12386         }
12387       }else{
12388         rc = 1;
12389       }
12390       clearYMD_HMS_TZ(p);
12391       break;
12392     }
12393     default: {
12394       break;
12395     }
12396   }
12397   return rc;
12398 }
12399
12400 /*
12401 ** Process time function arguments.  argv[0] is a date-time stamp.
12402 ** argv[1] and following are modifiers.  Parse them all and write
12403 ** the resulting time into the DateTime structure p.  Return 0
12404 ** on success and 1 if there are any errors.
12405 **
12406 ** If there are zero parameters (if even argv[0] is undefined)
12407 ** then assume a default value of "now" for argv[0].
12408 */
12409 static int isDate(
12410   sqlite3_context *context, 
12411   int argc, 
12412   sqlite3_value **argv, 
12413   DateTime *p
12414 ){
12415   int i;
12416   const unsigned char *z;
12417   int eType;
12418   memset(p, 0, sizeof(*p));
12419   if( argc==0 ){
12420     setDateTimeToCurrent(context, p);
12421   }else if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
12422                    || eType==SQLITE_INTEGER ){
12423     p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
12424     p->validJD = 1;
12425   }else{
12426     z = sqlite3_value_text(argv[0]);
12427     if( !z || parseDateOrTime(context, (char*)z, p) ){
12428       return 1;
12429     }
12430   }
12431   for(i=1; i<argc; i++){
12432     if( (z = sqlite3_value_text(argv[i]))==0 || parseModifier((char*)z, p) ){
12433       return 1;
12434     }
12435   }
12436   return 0;
12437 }
12438
12439
12440 /*
12441 ** The following routines implement the various date and time functions
12442 ** of SQLite.
12443 */
12444
12445 /*
12446 **    julianday( TIMESTRING, MOD, MOD, ...)
12447 **
12448 ** Return the julian day number of the date specified in the arguments
12449 */
12450 static void juliandayFunc(
12451   sqlite3_context *context,
12452   int argc,
12453   sqlite3_value **argv
12454 ){
12455   DateTime x;
12456   if( isDate(context, argc, argv, &x)==0 ){
12457     computeJD(&x);
12458     sqlite3_result_double(context, x.iJD/86400000.0);
12459   }
12460 }
12461
12462 /*
12463 **    datetime( TIMESTRING, MOD, MOD, ...)
12464 **
12465 ** Return YYYY-MM-DD HH:MM:SS
12466 */
12467 static void datetimeFunc(
12468   sqlite3_context *context,
12469   int argc,
12470   sqlite3_value **argv
12471 ){
12472   DateTime x;
12473   if( isDate(context, argc, argv, &x)==0 ){
12474     char zBuf[100];
12475     computeYMD_HMS(&x);
12476     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
12477                      x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
12478     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
12479   }
12480 }
12481
12482 /*
12483 **    time( TIMESTRING, MOD, MOD, ...)
12484 **
12485 ** Return HH:MM:SS
12486 */
12487 static void timeFunc(
12488   sqlite3_context *context,
12489   int argc,
12490   sqlite3_value **argv
12491 ){
12492   DateTime x;
12493   if( isDate(context, argc, argv, &x)==0 ){
12494     char zBuf[100];
12495     computeHMS(&x);
12496     sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
12497     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
12498   }
12499 }
12500
12501 /*
12502 **    date( TIMESTRING, MOD, MOD, ...)
12503 **
12504 ** Return YYYY-MM-DD
12505 */
12506 static void dateFunc(
12507   sqlite3_context *context,
12508   int argc,
12509   sqlite3_value **argv
12510 ){
12511   DateTime x;
12512   if( isDate(context, argc, argv, &x)==0 ){
12513     char zBuf[100];
12514     computeYMD(&x);
12515     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
12516     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
12517   }
12518 }
12519
12520 /*
12521 **    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
12522 **
12523 ** Return a string described by FORMAT.  Conversions as follows:
12524 **
12525 **   %d  day of month
12526 **   %f  ** fractional seconds  SS.SSS
12527 **   %H  hour 00-24
12528 **   %j  day of year 000-366
12529 **   %J  ** Julian day number
12530 **   %m  month 01-12
12531 **   %M  minute 00-59
12532 **   %s  seconds since 1970-01-01
12533 **   %S  seconds 00-59
12534 **   %w  day of week 0-6  sunday==0
12535 **   %W  week of year 00-53
12536 **   %Y  year 0000-9999
12537 **   %%  %
12538 */
12539 static void strftimeFunc(
12540   sqlite3_context *context,
12541   int argc,
12542   sqlite3_value **argv
12543 ){
12544   DateTime x;
12545   u64 n;
12546   size_t i,j;
12547   char *z;
12548   sqlite3 *db;
12549   const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
12550   char zBuf[100];
12551   if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
12552   db = sqlite3_context_db_handle(context);
12553   for(i=0, n=1; zFmt[i]; i++, n++){
12554     if( zFmt[i]=='%' ){
12555       switch( zFmt[i+1] ){
12556         case 'd':
12557         case 'H':
12558         case 'm':
12559         case 'M':
12560         case 'S':
12561         case 'W':
12562           n++;
12563           /* fall thru */
12564         case 'w':
12565         case '%':
12566           break;
12567         case 'f':
12568           n += 8;
12569           break;
12570         case 'j':
12571           n += 3;
12572           break;
12573         case 'Y':
12574           n += 8;
12575           break;
12576         case 's':
12577         case 'J':
12578           n += 50;
12579           break;
12580         default:
12581           return;  /* ERROR.  return a NULL */
12582       }
12583       i++;
12584     }
12585   }
12586   testcase( n==sizeof(zBuf)-1 );
12587   testcase( n==sizeof(zBuf) );
12588   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
12589   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
12590   if( n<sizeof(zBuf) ){
12591     z = zBuf;
12592   }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
12593     sqlite3_result_error_toobig(context);
12594     return;
12595   }else{
12596     z = sqlite3DbMallocRaw(db, (int)n);
12597     if( z==0 ){
12598       sqlite3_result_error_nomem(context);
12599       return;
12600     }
12601   }
12602   computeJD(&x);
12603   computeYMD_HMS(&x);
12604   for(i=j=0; zFmt[i]; i++){
12605     if( zFmt[i]!='%' ){
12606       z[j++] = zFmt[i];
12607     }else{
12608       i++;
12609       switch( zFmt[i] ){
12610         case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
12611         case 'f': {
12612           double s = x.s;
12613           if( s>59.999 ) s = 59.999;
12614           sqlite3_snprintf(7, &z[j],"%06.3f", s);
12615           j += sqlite3Strlen30(&z[j]);
12616           break;
12617         }
12618         case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
12619         case 'W': /* Fall thru */
12620         case 'j': {
12621           int nDay;             /* Number of days since 1st day of year */
12622           DateTime y = x;
12623           y.validJD = 0;
12624           y.M = 1;
12625           y.D = 1;
12626           computeJD(&y);
12627           nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
12628           if( zFmt[i]=='W' ){
12629             int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
12630             wd = (int)(((x.iJD+43200000)/86400000)%7);
12631             sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
12632             j += 2;
12633           }else{
12634             sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
12635             j += 3;
12636           }
12637           break;
12638         }
12639         case 'J': {
12640           sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
12641           j+=sqlite3Strlen30(&z[j]);
12642           break;
12643         }
12644         case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
12645         case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
12646         case 's': {
12647           sqlite3_snprintf(30,&z[j],"%lld",
12648                            (i64)(x.iJD/1000 - 21086676*(i64)10000));
12649           j += sqlite3Strlen30(&z[j]);
12650           break;
12651         }
12652         case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
12653         case 'w': {
12654           z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
12655           break;
12656         }
12657         case 'Y': {
12658           sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
12659           break;
12660         }
12661         default:   z[j++] = '%'; break;
12662       }
12663     }
12664   }
12665   z[j] = 0;
12666   sqlite3_result_text(context, z, -1,
12667                       z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
12668 }
12669
12670 /*
12671 ** current_time()
12672 **
12673 ** This function returns the same value as time('now').
12674 */
12675 static void ctimeFunc(
12676   sqlite3_context *context,
12677   int NotUsed,
12678   sqlite3_value **NotUsed2
12679 ){
12680   UNUSED_PARAMETER2(NotUsed, NotUsed2);
12681   timeFunc(context, 0, 0);
12682 }
12683
12684 /*
12685 ** current_date()
12686 **
12687 ** This function returns the same value as date('now').
12688 */
12689 static void cdateFunc(
12690   sqlite3_context *context,
12691   int NotUsed,
12692   sqlite3_value **NotUsed2
12693 ){
12694   UNUSED_PARAMETER2(NotUsed, NotUsed2);
12695   dateFunc(context, 0, 0);
12696 }
12697
12698 /*
12699 ** current_timestamp()
12700 **
12701 ** This function returns the same value as datetime('now').
12702 */
12703 static void ctimestampFunc(
12704   sqlite3_context *context,
12705   int NotUsed,
12706   sqlite3_value **NotUsed2
12707 ){
12708   UNUSED_PARAMETER2(NotUsed, NotUsed2);
12709   datetimeFunc(context, 0, 0);
12710 }
12711 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
12712
12713 #ifdef SQLITE_OMIT_DATETIME_FUNCS
12714 /*
12715 ** If the library is compiled to omit the full-scale date and time
12716 ** handling (to get a smaller binary), the following minimal version
12717 ** of the functions current_time(), current_date() and current_timestamp()
12718 ** are included instead. This is to support column declarations that
12719 ** include "DEFAULT CURRENT_TIME" etc.
12720 **
12721 ** This function uses the C-library functions time(), gmtime()
12722 ** and strftime(). The format string to pass to strftime() is supplied
12723 ** as the user-data for the function.
12724 */
12725 static void currentTimeFunc(
12726   sqlite3_context *context,
12727   int argc,
12728   sqlite3_value **argv
12729 ){
12730   time_t t;
12731   char *zFormat = (char *)sqlite3_user_data(context);
12732   sqlite3 *db;
12733   sqlite3_int64 iT;
12734   char zBuf[20];
12735
12736   UNUSED_PARAMETER(argc);
12737   UNUSED_PARAMETER(argv);
12738
12739   db = sqlite3_context_db_handle(context);
12740   sqlite3OsCurrentTimeInt64(db->pVfs, &iT);
12741   t = iT/1000 - 10000*(sqlite3_int64)21086676;
12742 #ifdef HAVE_GMTIME_R
12743   {
12744     struct tm sNow;
12745     gmtime_r(&t, &sNow);
12746     strftime(zBuf, 20, zFormat, &sNow);
12747   }
12748 #else
12749   {
12750     struct tm *pTm;
12751     sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
12752     pTm = gmtime(&t);
12753     strftime(zBuf, 20, zFormat, pTm);
12754     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
12755   }
12756 #endif
12757
12758   sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
12759 }
12760 #endif
12761
12762 /*
12763 ** This function registered all of the above C functions as SQL
12764 ** functions.  This should be the only routine in this file with
12765 ** external linkage.
12766 */
12767 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
12768   static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
12769 #ifndef SQLITE_OMIT_DATETIME_FUNCS
12770     FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
12771     FUNCTION(date,             -1, 0, 0, dateFunc      ),
12772     FUNCTION(time,             -1, 0, 0, timeFunc      ),
12773     FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
12774     FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
12775     FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
12776     FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
12777     FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
12778 #else
12779     STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
12780     STR_FUNCTION(current_date,      0, "%Y-%m-%d",          0, currentTimeFunc),
12781     STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
12782 #endif
12783   };
12784   int i;
12785   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
12786   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
12787
12788   for(i=0; i<ArraySize(aDateTimeFuncs); i++){
12789     sqlite3FuncDefInsert(pHash, &aFunc[i]);
12790   }
12791 }
12792
12793 /************** End of date.c ************************************************/
12794 /************** Begin file os.c **********************************************/
12795 /*
12796 ** 2005 November 29
12797 **
12798 ** The author disclaims copyright to this source code.  In place of
12799 ** a legal notice, here is a blessing:
12800 **
12801 **    May you do good and not evil.
12802 **    May you find forgiveness for yourself and forgive others.
12803 **    May you share freely, never taking more than you give.
12804 **
12805 ******************************************************************************
12806 **
12807 ** This file contains OS interface code that is common to all
12808 ** architectures.
12809 */
12810 #define _SQLITE_OS_C_ 1
12811 #undef _SQLITE_OS_C_
12812
12813 /*
12814 ** The default SQLite sqlite3_vfs implementations do not allocate
12815 ** memory (actually, os_unix.c allocates a small amount of memory
12816 ** from within OsOpen()), but some third-party implementations may.
12817 ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
12818 ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
12819 **
12820 ** The following functions are instrumented for malloc() failure 
12821 ** testing:
12822 **
12823 **     sqlite3OsOpen()
12824 **     sqlite3OsRead()
12825 **     sqlite3OsWrite()
12826 **     sqlite3OsSync()
12827 **     sqlite3OsLock()
12828 **
12829 */
12830 #if defined(SQLITE_TEST)
12831 SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
12832   #define DO_OS_MALLOC_TEST(x)                                       \
12833   if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) {  \
12834     void *pTstAlloc = sqlite3Malloc(10);                             \
12835     if (!pTstAlloc) return SQLITE_IOERR_NOMEM;                       \
12836     sqlite3_free(pTstAlloc);                                         \
12837   }
12838 #else
12839   #define DO_OS_MALLOC_TEST(x)
12840 #endif
12841
12842 /*
12843 ** The following routines are convenience wrappers around methods
12844 ** of the sqlite3_file object.  This is mostly just syntactic sugar. All
12845 ** of this would be completely automatic if SQLite were coded using
12846 ** C++ instead of plain old C.
12847 */
12848 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
12849   int rc = SQLITE_OK;
12850   if( pId->pMethods ){
12851     rc = pId->pMethods->xClose(pId);
12852     pId->pMethods = 0;
12853   }
12854   return rc;
12855 }
12856 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
12857   DO_OS_MALLOC_TEST(id);
12858   return id->pMethods->xRead(id, pBuf, amt, offset);
12859 }
12860 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
12861   DO_OS_MALLOC_TEST(id);
12862   return id->pMethods->xWrite(id, pBuf, amt, offset);
12863 }
12864 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
12865   return id->pMethods->xTruncate(id, size);
12866 }
12867 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
12868   DO_OS_MALLOC_TEST(id);
12869   return id->pMethods->xSync(id, flags);
12870 }
12871 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
12872   DO_OS_MALLOC_TEST(id);
12873   return id->pMethods->xFileSize(id, pSize);
12874 }
12875 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
12876   DO_OS_MALLOC_TEST(id);
12877   return id->pMethods->xLock(id, lockType);
12878 }
12879 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
12880   return id->pMethods->xUnlock(id, lockType);
12881 }
12882 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
12883   DO_OS_MALLOC_TEST(id);
12884   return id->pMethods->xCheckReservedLock(id, pResOut);
12885 }
12886 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
12887   return id->pMethods->xFileControl(id, op, pArg);
12888 }
12889 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
12890   int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
12891   return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
12892 }
12893 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
12894   return id->pMethods->xDeviceCharacteristics(id);
12895 }
12896 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
12897   return id->pMethods->xShmLock(id, offset, n, flags);
12898 }
12899 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
12900   id->pMethods->xShmBarrier(id);
12901 }
12902 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
12903   return id->pMethods->xShmUnmap(id, deleteFlag);
12904 }
12905 SQLITE_PRIVATE int sqlite3OsShmMap(
12906   sqlite3_file *id,               /* Database file handle */
12907   int iPage,
12908   int pgsz,
12909   int bExtend,                    /* True to extend file if necessary */
12910   void volatile **pp              /* OUT: Pointer to mapping */
12911 ){
12912   return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
12913 }
12914
12915 /*
12916 ** The next group of routines are convenience wrappers around the
12917 ** VFS methods.
12918 */
12919 SQLITE_PRIVATE int sqlite3OsOpen(
12920   sqlite3_vfs *pVfs, 
12921   const char *zPath, 
12922   sqlite3_file *pFile, 
12923   int flags, 
12924   int *pFlagsOut
12925 ){
12926   int rc;
12927   DO_OS_MALLOC_TEST(0);
12928   /* 0x87f3f is a mask of SQLITE_OPEN_ flags that are valid to be passed
12929   ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
12930   ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
12931   ** reaching the VFS. */
12932   rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f3f, pFlagsOut);
12933   assert( rc==SQLITE_OK || pFile->pMethods==0 );
12934   return rc;
12935 }
12936 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
12937   return pVfs->xDelete(pVfs, zPath, dirSync);
12938 }
12939 SQLITE_PRIVATE int sqlite3OsAccess(
12940   sqlite3_vfs *pVfs, 
12941   const char *zPath, 
12942   int flags, 
12943   int *pResOut
12944 ){
12945   DO_OS_MALLOC_TEST(0);
12946   return pVfs->xAccess(pVfs, zPath, flags, pResOut);
12947 }
12948 SQLITE_PRIVATE int sqlite3OsFullPathname(
12949   sqlite3_vfs *pVfs, 
12950   const char *zPath, 
12951   int nPathOut, 
12952   char *zPathOut
12953 ){
12954   zPathOut[0] = 0;
12955   return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
12956 }
12957 #ifndef SQLITE_OMIT_LOAD_EXTENSION
12958 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
12959   return pVfs->xDlOpen(pVfs, zPath);
12960 }
12961 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
12962   pVfs->xDlError(pVfs, nByte, zBufOut);
12963 }
12964 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
12965   return pVfs->xDlSym(pVfs, pHdle, zSym);
12966 }
12967 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
12968   pVfs->xDlClose(pVfs, pHandle);
12969 }
12970 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
12971 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
12972   return pVfs->xRandomness(pVfs, nByte, zBufOut);
12973 }
12974 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
12975   return pVfs->xSleep(pVfs, nMicro);
12976 }
12977 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
12978   int rc;
12979   if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
12980     rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
12981   }else{
12982     double r;
12983     rc = pVfs->xCurrentTime(pVfs, &r);
12984     *pTimeOut = (sqlite3_int64)(r*86400000.0);
12985   }
12986   return rc;
12987 }
12988
12989 SQLITE_PRIVATE int sqlite3OsOpenMalloc(
12990   sqlite3_vfs *pVfs, 
12991   const char *zFile, 
12992   sqlite3_file **ppFile, 
12993   int flags,
12994   int *pOutFlags
12995 ){
12996   int rc = SQLITE_NOMEM;
12997   sqlite3_file *pFile;
12998   pFile = (sqlite3_file *)sqlite3Malloc(pVfs->szOsFile);
12999   if( pFile ){
13000     rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
13001     if( rc!=SQLITE_OK ){
13002       sqlite3_free(pFile);
13003     }else{
13004       *ppFile = pFile;
13005     }
13006   }
13007   return rc;
13008 }
13009 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
13010   int rc = SQLITE_OK;
13011   assert( pFile );
13012   rc = sqlite3OsClose(pFile);
13013   sqlite3_free(pFile);
13014   return rc;
13015 }
13016
13017 /*
13018 ** This function is a wrapper around the OS specific implementation of
13019 ** sqlite3_os_init(). The purpose of the wrapper is to provide the
13020 ** ability to simulate a malloc failure, so that the handling of an
13021 ** error in sqlite3_os_init() by the upper layers can be tested.
13022 */
13023 SQLITE_PRIVATE int sqlite3OsInit(void){
13024   void *p = sqlite3_malloc(10);
13025   if( p==0 ) return SQLITE_NOMEM;
13026   sqlite3_free(p);
13027   return sqlite3_os_init();
13028 }
13029
13030 /*
13031 ** The list of all registered VFS implementations.
13032 */
13033 static sqlite3_vfs * SQLITE_WSD vfsList = 0;
13034 #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
13035
13036 /*
13037 ** Locate a VFS by name.  If no name is given, simply return the
13038 ** first VFS on the list.
13039 */
13040 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
13041   sqlite3_vfs *pVfs = 0;
13042 #if SQLITE_THREADSAFE
13043   sqlite3_mutex *mutex;
13044 #endif
13045 #ifndef SQLITE_OMIT_AUTOINIT
13046   int rc = sqlite3_initialize();
13047   if( rc ) return 0;
13048 #endif
13049 #if SQLITE_THREADSAFE
13050   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
13051 #endif
13052   sqlite3_mutex_enter(mutex);
13053   for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
13054     if( zVfs==0 ) break;
13055     if( strcmp(zVfs, pVfs->zName)==0 ) break;
13056   }
13057   sqlite3_mutex_leave(mutex);
13058   return pVfs;
13059 }
13060
13061 /*
13062 ** Unlink a VFS from the linked list
13063 */
13064 static void vfsUnlink(sqlite3_vfs *pVfs){
13065   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
13066   if( pVfs==0 ){
13067     /* No-op */
13068   }else if( vfsList==pVfs ){
13069     vfsList = pVfs->pNext;
13070   }else if( vfsList ){
13071     sqlite3_vfs *p = vfsList;
13072     while( p->pNext && p->pNext!=pVfs ){
13073       p = p->pNext;
13074     }
13075     if( p->pNext==pVfs ){
13076       p->pNext = pVfs->pNext;
13077     }
13078   }
13079 }
13080
13081 /*
13082 ** Register a VFS with the system.  It is harmless to register the same
13083 ** VFS multiple times.  The new VFS becomes the default if makeDflt is
13084 ** true.
13085 */
13086 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
13087   sqlite3_mutex *mutex = 0;
13088 #ifndef SQLITE_OMIT_AUTOINIT
13089   int rc = sqlite3_initialize();
13090   if( rc ) return rc;
13091 #endif
13092   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
13093   sqlite3_mutex_enter(mutex);
13094   vfsUnlink(pVfs);
13095   if( makeDflt || vfsList==0 ){
13096     pVfs->pNext = vfsList;
13097     vfsList = pVfs;
13098   }else{
13099     pVfs->pNext = vfsList->pNext;
13100     vfsList->pNext = pVfs;
13101   }
13102   assert(vfsList);
13103   sqlite3_mutex_leave(mutex);
13104   return SQLITE_OK;
13105 }
13106
13107 /*
13108 ** Unregister a VFS so that it is no longer accessible.
13109 */
13110 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
13111 #if SQLITE_THREADSAFE
13112   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
13113 #endif
13114   sqlite3_mutex_enter(mutex);
13115   vfsUnlink(pVfs);
13116   sqlite3_mutex_leave(mutex);
13117   return SQLITE_OK;
13118 }
13119
13120 /************** End of os.c **************************************************/
13121 /************** Begin file fault.c *******************************************/
13122 /*
13123 ** 2008 Jan 22
13124 **
13125 ** The author disclaims copyright to this source code.  In place of
13126 ** a legal notice, here is a blessing:
13127 **
13128 **    May you do good and not evil.
13129 **    May you find forgiveness for yourself and forgive others.
13130 **    May you share freely, never taking more than you give.
13131 **
13132 *************************************************************************
13133 **
13134 ** This file contains code to support the concept of "benign" 
13135 ** malloc failures (when the xMalloc() or xRealloc() method of the
13136 ** sqlite3_mem_methods structure fails to allocate a block of memory
13137 ** and returns 0). 
13138 **
13139 ** Most malloc failures are non-benign. After they occur, SQLite
13140 ** abandons the current operation and returns an error code (usually
13141 ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
13142 ** fatal. For example, if a malloc fails while resizing a hash table, this 
13143 ** is completely recoverable simply by not carrying out the resize. The 
13144 ** hash table will continue to function normally.  So a malloc failure 
13145 ** during a hash table resize is a benign fault.
13146 */
13147
13148
13149 #ifndef SQLITE_OMIT_BUILTIN_TEST
13150
13151 /*
13152 ** Global variables.
13153 */
13154 typedef struct BenignMallocHooks BenignMallocHooks;
13155 static SQLITE_WSD struct BenignMallocHooks {
13156   void (*xBenignBegin)(void);
13157   void (*xBenignEnd)(void);
13158 } sqlite3Hooks = { 0, 0 };
13159
13160 /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
13161 ** structure.  If writable static data is unsupported on the target,
13162 ** we have to locate the state vector at run-time.  In the more common
13163 ** case where writable static data is supported, wsdHooks can refer directly
13164 ** to the "sqlite3Hooks" state vector declared above.
13165 */
13166 #ifdef SQLITE_OMIT_WSD
13167 # define wsdHooksInit \
13168   BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
13169 # define wsdHooks x[0]
13170 #else
13171 # define wsdHooksInit
13172 # define wsdHooks sqlite3Hooks
13173 #endif
13174
13175
13176 /*
13177 ** Register hooks to call when sqlite3BeginBenignMalloc() and
13178 ** sqlite3EndBenignMalloc() are called, respectively.
13179 */
13180 SQLITE_PRIVATE void sqlite3BenignMallocHooks(
13181   void (*xBenignBegin)(void),
13182   void (*xBenignEnd)(void)
13183 ){
13184   wsdHooksInit;
13185   wsdHooks.xBenignBegin = xBenignBegin;
13186   wsdHooks.xBenignEnd = xBenignEnd;
13187 }
13188
13189 /*
13190 ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
13191 ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
13192 ** indicates that subsequent malloc failures are non-benign.
13193 */
13194 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
13195   wsdHooksInit;
13196   if( wsdHooks.xBenignBegin ){
13197     wsdHooks.xBenignBegin();
13198   }
13199 }
13200 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
13201   wsdHooksInit;
13202   if( wsdHooks.xBenignEnd ){
13203     wsdHooks.xBenignEnd();
13204   }
13205 }
13206
13207 #endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
13208
13209 /************** End of fault.c ***********************************************/
13210 /************** Begin file mem0.c ********************************************/
13211 /*
13212 ** 2008 October 28
13213 **
13214 ** The author disclaims copyright to this source code.  In place of
13215 ** a legal notice, here is a blessing:
13216 **
13217 **    May you do good and not evil.
13218 **    May you find forgiveness for yourself and forgive others.
13219 **    May you share freely, never taking more than you give.
13220 **
13221 *************************************************************************
13222 **
13223 ** This file contains a no-op memory allocation drivers for use when
13224 ** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
13225 ** here always fail.  SQLite will not operate with these drivers.  These
13226 ** are merely placeholders.  Real drivers must be substituted using
13227 ** sqlite3_config() before SQLite will operate.
13228 */
13229
13230 /*
13231 ** This version of the memory allocator is the default.  It is
13232 ** used when no other memory allocator is specified using compile-time
13233 ** macros.
13234 */
13235 #ifdef SQLITE_ZERO_MALLOC
13236
13237 /*
13238 ** No-op versions of all memory allocation routines
13239 */
13240 static void *sqlite3MemMalloc(int nByte){ return 0; }
13241 static void sqlite3MemFree(void *pPrior){ return; }
13242 static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
13243 static int sqlite3MemSize(void *pPrior){ return 0; }
13244 static int sqlite3MemRoundup(int n){ return n; }
13245 static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
13246 static void sqlite3MemShutdown(void *NotUsed){ return; }
13247
13248 /*
13249 ** This routine is the only routine in this file with external linkage.
13250 **
13251 ** Populate the low-level memory allocation function pointers in
13252 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
13253 */
13254 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
13255   static const sqlite3_mem_methods defaultMethods = {
13256      sqlite3MemMalloc,
13257      sqlite3MemFree,
13258      sqlite3MemRealloc,
13259      sqlite3MemSize,
13260      sqlite3MemRoundup,
13261      sqlite3MemInit,
13262      sqlite3MemShutdown,
13263      0
13264   };
13265   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
13266 }
13267
13268 #endif /* SQLITE_ZERO_MALLOC */
13269
13270 /************** End of mem0.c ************************************************/
13271 /************** Begin file mem1.c ********************************************/
13272 /*
13273 ** 2007 August 14
13274 **
13275 ** The author disclaims copyright to this source code.  In place of
13276 ** a legal notice, here is a blessing:
13277 **
13278 **    May you do good and not evil.
13279 **    May you find forgiveness for yourself and forgive others.
13280 **    May you share freely, never taking more than you give.
13281 **
13282 *************************************************************************
13283 **
13284 ** This file contains low-level memory allocation drivers for when
13285 ** SQLite will use the standard C-library malloc/realloc/free interface
13286 ** to obtain the memory it needs.
13287 **
13288 ** This file contains implementations of the low-level memory allocation
13289 ** routines specified in the sqlite3_mem_methods object.
13290 */
13291
13292 /*
13293 ** This version of the memory allocator is the default.  It is
13294 ** used when no other memory allocator is specified using compile-time
13295 ** macros.
13296 */
13297 #ifdef SQLITE_SYSTEM_MALLOC
13298
13299 /*
13300 ** Like malloc(), but remember the size of the allocation
13301 ** so that we can find it later using sqlite3MemSize().
13302 **
13303 ** For this low-level routine, we are guaranteed that nByte>0 because
13304 ** cases of nByte<=0 will be intercepted and dealt with by higher level
13305 ** routines.
13306 */
13307 static void *sqlite3MemMalloc(int nByte){
13308   sqlite3_int64 *p;
13309   assert( nByte>0 );
13310   nByte = ROUND8(nByte);
13311   p = malloc( nByte+8 );
13312   if( p ){
13313     p[0] = nByte;
13314     p++;
13315   }else{
13316     testcase( sqlite3GlobalConfig.xLog!=0 );
13317     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
13318   }
13319   return (void *)p;
13320 }
13321
13322 /*
13323 ** Like free() but works for allocations obtained from sqlite3MemMalloc()
13324 ** or sqlite3MemRealloc().
13325 **
13326 ** For this low-level routine, we already know that pPrior!=0 since
13327 ** cases where pPrior==0 will have been intecepted and dealt with
13328 ** by higher-level routines.
13329 */
13330 static void sqlite3MemFree(void *pPrior){
13331   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
13332   assert( pPrior!=0 );
13333   p--;
13334   free(p);
13335 }
13336
13337 /*
13338 ** Report the allocated size of a prior return from xMalloc()
13339 ** or xRealloc().
13340 */
13341 static int sqlite3MemSize(void *pPrior){
13342   sqlite3_int64 *p;
13343   if( pPrior==0 ) return 0;
13344   p = (sqlite3_int64*)pPrior;
13345   p--;
13346   return (int)p[0];
13347 }
13348
13349 /*
13350 ** Like realloc().  Resize an allocation previously obtained from
13351 ** sqlite3MemMalloc().
13352 **
13353 ** For this low-level interface, we know that pPrior!=0.  Cases where
13354 ** pPrior==0 while have been intercepted by higher-level routine and
13355 ** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
13356 ** cases where nByte<=0 will have been intercepted by higher-level
13357 ** routines and redirected to xFree.
13358 */
13359 static void *sqlite3MemRealloc(void *pPrior, int nByte){
13360   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
13361   assert( pPrior!=0 && nByte>0 );
13362   nByte = ROUND8(nByte);
13363   p--;
13364   p = realloc(p, nByte+8 );
13365   if( p ){
13366     p[0] = nByte;
13367     p++;
13368   }else{
13369     testcase( sqlite3GlobalConfig.xLog!=0 );
13370     sqlite3_log(SQLITE_NOMEM,
13371       "failed memory resize %u to %u bytes",
13372       sqlite3MemSize(pPrior), nByte);
13373   }
13374   return (void*)p;
13375 }
13376
13377 /*
13378 ** Round up a request size to the next valid allocation size.
13379 */
13380 static int sqlite3MemRoundup(int n){
13381   return ROUND8(n);
13382 }
13383
13384 /*
13385 ** Initialize this module.
13386 */
13387 static int sqlite3MemInit(void *NotUsed){
13388   UNUSED_PARAMETER(NotUsed);
13389   return SQLITE_OK;
13390 }
13391
13392 /*
13393 ** Deinitialize this module.
13394 */
13395 static void sqlite3MemShutdown(void *NotUsed){
13396   UNUSED_PARAMETER(NotUsed);
13397   return;
13398 }
13399
13400 /*
13401 ** This routine is the only routine in this file with external linkage.
13402 **
13403 ** Populate the low-level memory allocation function pointers in
13404 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
13405 */
13406 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
13407   static const sqlite3_mem_methods defaultMethods = {
13408      sqlite3MemMalloc,
13409      sqlite3MemFree,
13410      sqlite3MemRealloc,
13411      sqlite3MemSize,
13412      sqlite3MemRoundup,
13413      sqlite3MemInit,
13414      sqlite3MemShutdown,
13415      0
13416   };
13417   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
13418 }
13419
13420 #endif /* SQLITE_SYSTEM_MALLOC */
13421
13422 /************** End of mem1.c ************************************************/
13423 /************** Begin file mem2.c ********************************************/
13424 /*
13425 ** 2007 August 15
13426 **
13427 ** The author disclaims copyright to this source code.  In place of
13428 ** a legal notice, here is a blessing:
13429 **
13430 **    May you do good and not evil.
13431 **    May you find forgiveness for yourself and forgive others.
13432 **    May you share freely, never taking more than you give.
13433 **
13434 *************************************************************************
13435 **
13436 ** This file contains low-level memory allocation drivers for when
13437 ** SQLite will use the standard C-library malloc/realloc/free interface
13438 ** to obtain the memory it needs while adding lots of additional debugging
13439 ** information to each allocation in order to help detect and fix memory
13440 ** leaks and memory usage errors.
13441 **
13442 ** This file contains implementations of the low-level memory allocation
13443 ** routines specified in the sqlite3_mem_methods object.
13444 */
13445
13446 /*
13447 ** This version of the memory allocator is used only if the
13448 ** SQLITE_MEMDEBUG macro is defined
13449 */
13450 #ifdef SQLITE_MEMDEBUG
13451
13452 /*
13453 ** The backtrace functionality is only available with GLIBC
13454 */
13455 #ifdef __GLIBC__
13456   extern int backtrace(void**,int);
13457   extern void backtrace_symbols_fd(void*const*,int,int);
13458 #else
13459 # define backtrace(A,B) 1
13460 # define backtrace_symbols_fd(A,B,C)
13461 #endif
13462
13463 /*
13464 ** Each memory allocation looks like this:
13465 **
13466 **  ------------------------------------------------------------------------
13467 **  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
13468 **  ------------------------------------------------------------------------
13469 **
13470 ** The application code sees only a pointer to the allocation.  We have
13471 ** to back up from the allocation pointer to find the MemBlockHdr.  The
13472 ** MemBlockHdr tells us the size of the allocation and the number of
13473 ** backtrace pointers.  There is also a guard word at the end of the
13474 ** MemBlockHdr.
13475 */
13476 struct MemBlockHdr {
13477   i64 iSize;                          /* Size of this allocation */
13478   struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
13479   char nBacktrace;                    /* Number of backtraces on this alloc */
13480   char nBacktraceSlots;               /* Available backtrace slots */
13481   u8 nTitle;                          /* Bytes of title; includes '\0' */
13482   u8 eType;                           /* Allocation type code */
13483   int iForeGuard;                     /* Guard word for sanity */
13484 };
13485
13486 /*
13487 ** Guard words
13488 */
13489 #define FOREGUARD 0x80F5E153
13490 #define REARGUARD 0xE4676B53
13491
13492 /*
13493 ** Number of malloc size increments to track.
13494 */
13495 #define NCSIZE  1000
13496
13497 /*
13498 ** All of the static variables used by this module are collected
13499 ** into a single structure named "mem".  This is to keep the
13500 ** static variables organized and to reduce namespace pollution
13501 ** when this module is combined with other in the amalgamation.
13502 */
13503 static struct {
13504   
13505   /*
13506   ** Mutex to control access to the memory allocation subsystem.
13507   */
13508   sqlite3_mutex *mutex;
13509
13510   /*
13511   ** Head and tail of a linked list of all outstanding allocations
13512   */
13513   struct MemBlockHdr *pFirst;
13514   struct MemBlockHdr *pLast;
13515   
13516   /*
13517   ** The number of levels of backtrace to save in new allocations.
13518   */
13519   int nBacktrace;
13520   void (*xBacktrace)(int, int, void **);
13521
13522   /*
13523   ** Title text to insert in front of each block
13524   */
13525   int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
13526   char zTitle[100];  /* The title text */
13527
13528   /* 
13529   ** sqlite3MallocDisallow() increments the following counter.
13530   ** sqlite3MallocAllow() decrements it.
13531   */
13532   int disallow; /* Do not allow memory allocation */
13533
13534   /*
13535   ** Gather statistics on the sizes of memory allocations.
13536   ** nAlloc[i] is the number of allocation attempts of i*8
13537   ** bytes.  i==NCSIZE is the number of allocation attempts for
13538   ** sizes more than NCSIZE*8 bytes.
13539   */
13540   int nAlloc[NCSIZE];      /* Total number of allocations */
13541   int nCurrent[NCSIZE];    /* Current number of allocations */
13542   int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
13543
13544 } mem;
13545
13546
13547 /*
13548 ** Adjust memory usage statistics
13549 */
13550 static void adjustStats(int iSize, int increment){
13551   int i = ROUND8(iSize)/8;
13552   if( i>NCSIZE-1 ){
13553     i = NCSIZE - 1;
13554   }
13555   if( increment>0 ){
13556     mem.nAlloc[i]++;
13557     mem.nCurrent[i]++;
13558     if( mem.nCurrent[i]>mem.mxCurrent[i] ){
13559       mem.mxCurrent[i] = mem.nCurrent[i];
13560     }
13561   }else{
13562     mem.nCurrent[i]--;
13563     assert( mem.nCurrent[i]>=0 );
13564   }
13565 }
13566
13567 /*
13568 ** Given an allocation, find the MemBlockHdr for that allocation.
13569 **
13570 ** This routine checks the guards at either end of the allocation and
13571 ** if they are incorrect it asserts.
13572 */
13573 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
13574   struct MemBlockHdr *p;
13575   int *pInt;
13576   u8 *pU8;
13577   int nReserve;
13578
13579   p = (struct MemBlockHdr*)pAllocation;
13580   p--;
13581   assert( p->iForeGuard==(int)FOREGUARD );
13582   nReserve = ROUND8(p->iSize);
13583   pInt = (int*)pAllocation;
13584   pU8 = (u8*)pAllocation;
13585   assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
13586   /* This checks any of the "extra" bytes allocated due
13587   ** to rounding up to an 8 byte boundary to ensure 
13588   ** they haven't been overwritten.
13589   */
13590   while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
13591   return p;
13592 }
13593
13594 /*
13595 ** Return the number of bytes currently allocated at address p.
13596 */
13597 static int sqlite3MemSize(void *p){
13598   struct MemBlockHdr *pHdr;
13599   if( !p ){
13600     return 0;
13601   }
13602   pHdr = sqlite3MemsysGetHeader(p);
13603   return pHdr->iSize;
13604 }
13605
13606 /*
13607 ** Initialize the memory allocation subsystem.
13608 */
13609 static int sqlite3MemInit(void *NotUsed){
13610   UNUSED_PARAMETER(NotUsed);
13611   assert( (sizeof(struct MemBlockHdr)&7) == 0 );
13612   if( !sqlite3GlobalConfig.bMemstat ){
13613     /* If memory status is enabled, then the malloc.c wrapper will already
13614     ** hold the STATIC_MEM mutex when the routines here are invoked. */
13615     mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
13616   }
13617   return SQLITE_OK;
13618 }
13619
13620 /*
13621 ** Deinitialize the memory allocation subsystem.
13622 */
13623 static void sqlite3MemShutdown(void *NotUsed){
13624   UNUSED_PARAMETER(NotUsed);
13625   mem.mutex = 0;
13626 }
13627
13628 /*
13629 ** Round up a request size to the next valid allocation size.
13630 */
13631 static int sqlite3MemRoundup(int n){
13632   return ROUND8(n);
13633 }
13634
13635 /*
13636 ** Fill a buffer with pseudo-random bytes.  This is used to preset
13637 ** the content of a new memory allocation to unpredictable values and
13638 ** to clear the content of a freed allocation to unpredictable values.
13639 */
13640 static void randomFill(char *pBuf, int nByte){
13641   unsigned int x, y, r;
13642   x = SQLITE_PTR_TO_INT(pBuf);
13643   y = nByte | 1;
13644   while( nByte >= 4 ){
13645     x = (x>>1) ^ (-(x&1) & 0xd0000001);
13646     y = y*1103515245 + 12345;
13647     r = x ^ y;
13648     *(int*)pBuf = r;
13649     pBuf += 4;
13650     nByte -= 4;
13651   }
13652   while( nByte-- > 0 ){
13653     x = (x>>1) ^ (-(x&1) & 0xd0000001);
13654     y = y*1103515245 + 12345;
13655     r = x ^ y;
13656     *(pBuf++) = r & 0xff;
13657   }
13658 }
13659
13660 /*
13661 ** Allocate nByte bytes of memory.
13662 */
13663 static void *sqlite3MemMalloc(int nByte){
13664   struct MemBlockHdr *pHdr;
13665   void **pBt;
13666   char *z;
13667   int *pInt;
13668   void *p = 0;
13669   int totalSize;
13670   int nReserve;
13671   sqlite3_mutex_enter(mem.mutex);
13672   assert( mem.disallow==0 );
13673   nReserve = ROUND8(nByte);
13674   totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
13675                mem.nBacktrace*sizeof(void*) + mem.nTitle;
13676   p = malloc(totalSize);
13677   if( p ){
13678     z = p;
13679     pBt = (void**)&z[mem.nTitle];
13680     pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
13681     pHdr->pNext = 0;
13682     pHdr->pPrev = mem.pLast;
13683     if( mem.pLast ){
13684       mem.pLast->pNext = pHdr;
13685     }else{
13686       mem.pFirst = pHdr;
13687     }
13688     mem.pLast = pHdr;
13689     pHdr->iForeGuard = FOREGUARD;
13690     pHdr->eType = MEMTYPE_HEAP;
13691     pHdr->nBacktraceSlots = mem.nBacktrace;
13692     pHdr->nTitle = mem.nTitle;
13693     if( mem.nBacktrace ){
13694       void *aAddr[40];
13695       pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
13696       memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
13697       assert(pBt[0]);
13698       if( mem.xBacktrace ){
13699         mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
13700       }
13701     }else{
13702       pHdr->nBacktrace = 0;
13703     }
13704     if( mem.nTitle ){
13705       memcpy(z, mem.zTitle, mem.nTitle);
13706     }
13707     pHdr->iSize = nByte;
13708     adjustStats(nByte, +1);
13709     pInt = (int*)&pHdr[1];
13710     pInt[nReserve/sizeof(int)] = REARGUARD;
13711     randomFill((char*)pInt, nByte);
13712     memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
13713     p = (void*)pInt;
13714   }
13715   sqlite3_mutex_leave(mem.mutex);
13716   return p; 
13717 }
13718
13719 /*
13720 ** Free memory.
13721 */
13722 static void sqlite3MemFree(void *pPrior){
13723   struct MemBlockHdr *pHdr;
13724   void **pBt;
13725   char *z;
13726   assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0 
13727        || mem.mutex!=0 );
13728   pHdr = sqlite3MemsysGetHeader(pPrior);
13729   pBt = (void**)pHdr;
13730   pBt -= pHdr->nBacktraceSlots;
13731   sqlite3_mutex_enter(mem.mutex);
13732   if( pHdr->pPrev ){
13733     assert( pHdr->pPrev->pNext==pHdr );
13734     pHdr->pPrev->pNext = pHdr->pNext;
13735   }else{
13736     assert( mem.pFirst==pHdr );
13737     mem.pFirst = pHdr->pNext;
13738   }
13739   if( pHdr->pNext ){
13740     assert( pHdr->pNext->pPrev==pHdr );
13741     pHdr->pNext->pPrev = pHdr->pPrev;
13742   }else{
13743     assert( mem.pLast==pHdr );
13744     mem.pLast = pHdr->pPrev;
13745   }
13746   z = (char*)pBt;
13747   z -= pHdr->nTitle;
13748   adjustStats(pHdr->iSize, -1);
13749   randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
13750                 pHdr->iSize + sizeof(int) + pHdr->nTitle);
13751   free(z);
13752   sqlite3_mutex_leave(mem.mutex);  
13753 }
13754
13755 /*
13756 ** Change the size of an existing memory allocation.
13757 **
13758 ** For this debugging implementation, we *always* make a copy of the
13759 ** allocation into a new place in memory.  In this way, if the 
13760 ** higher level code is using pointer to the old allocation, it is 
13761 ** much more likely to break and we are much more liking to find
13762 ** the error.
13763 */
13764 static void *sqlite3MemRealloc(void *pPrior, int nByte){
13765   struct MemBlockHdr *pOldHdr;
13766   void *pNew;
13767   assert( mem.disallow==0 );
13768   pOldHdr = sqlite3MemsysGetHeader(pPrior);
13769   pNew = sqlite3MemMalloc(nByte);
13770   if( pNew ){
13771     memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
13772     if( nByte>pOldHdr->iSize ){
13773       randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - pOldHdr->iSize);
13774     }
13775     sqlite3MemFree(pPrior);
13776   }
13777   return pNew;
13778 }
13779
13780 /*
13781 ** Populate the low-level memory allocation function pointers in
13782 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
13783 */
13784 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
13785   static const sqlite3_mem_methods defaultMethods = {
13786      sqlite3MemMalloc,
13787      sqlite3MemFree,
13788      sqlite3MemRealloc,
13789      sqlite3MemSize,
13790      sqlite3MemRoundup,
13791      sqlite3MemInit,
13792      sqlite3MemShutdown,
13793      0
13794   };
13795   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
13796 }
13797
13798 /*
13799 ** Set the "type" of an allocation.
13800 */
13801 SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
13802   if( p ){
13803     struct MemBlockHdr *pHdr;
13804     pHdr = sqlite3MemsysGetHeader(p);
13805     assert( pHdr->iForeGuard==FOREGUARD );
13806     pHdr->eType = eType;
13807   }
13808 }
13809
13810 /*
13811 ** Return TRUE if the mask of type in eType matches the type of the
13812 ** allocation p.  Also return true if p==NULL.
13813 **
13814 ** This routine is designed for use within an assert() statement, to
13815 ** verify the type of an allocation.  For example:
13816 **
13817 **     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
13818 */
13819 SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
13820   int rc = 1;
13821   if( p ){
13822     struct MemBlockHdr *pHdr;
13823     pHdr = sqlite3MemsysGetHeader(p);
13824     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
13825     assert( (pHdr->eType & (pHdr->eType-1))==0 );  /* Only one type bit set */
13826     if( (pHdr->eType&eType)==0 ){
13827       void **pBt;
13828       pBt = (void**)pHdr;
13829       pBt -= pHdr->nBacktraceSlots;
13830       backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(stderr));
13831       fprintf(stderr, "\n");
13832       rc = 0;
13833     }
13834   }
13835   return rc;
13836 }
13837  
13838
13839 /*
13840 ** Set the number of backtrace levels kept for each allocation.
13841 ** A value of zero turns off backtracing.  The number is always rounded
13842 ** up to a multiple of 2.
13843 */
13844 SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
13845   if( depth<0 ){ depth = 0; }
13846   if( depth>20 ){ depth = 20; }
13847   depth = (depth+1)&0xfe;
13848   mem.nBacktrace = depth;
13849 }
13850
13851 SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
13852   mem.xBacktrace = xBacktrace;
13853 }
13854
13855 /*
13856 ** Set the title string for subsequent allocations.
13857 */
13858 SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
13859   unsigned int n = sqlite3Strlen30(zTitle) + 1;
13860   sqlite3_mutex_enter(mem.mutex);
13861   if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
13862   memcpy(mem.zTitle, zTitle, n);
13863   mem.zTitle[n] = 0;
13864   mem.nTitle = ROUND8(n);
13865   sqlite3_mutex_leave(mem.mutex);
13866 }
13867
13868 SQLITE_PRIVATE void sqlite3MemdebugSync(){
13869   struct MemBlockHdr *pHdr;
13870   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
13871     void **pBt = (void**)pHdr;
13872     pBt -= pHdr->nBacktraceSlots;
13873     mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
13874   }
13875 }
13876
13877 /*
13878 ** Open the file indicated and write a log of all unfreed memory 
13879 ** allocations into that log.
13880 */
13881 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
13882   FILE *out;
13883   struct MemBlockHdr *pHdr;
13884   void **pBt;
13885   int i;
13886   out = fopen(zFilename, "w");
13887   if( out==0 ){
13888     fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
13889                     zFilename);
13890     return;
13891   }
13892   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
13893     char *z = (char*)pHdr;
13894     z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
13895     fprintf(out, "**** %lld bytes at %p from %s ****\n", 
13896             pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
13897     if( pHdr->nBacktrace ){
13898       fflush(out);
13899       pBt = (void**)pHdr;
13900       pBt -= pHdr->nBacktraceSlots;
13901       backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
13902       fprintf(out, "\n");
13903     }
13904   }
13905   fprintf(out, "COUNTS:\n");
13906   for(i=0; i<NCSIZE-1; i++){
13907     if( mem.nAlloc[i] ){
13908       fprintf(out, "   %5d: %10d %10d %10d\n", 
13909             i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
13910     }
13911   }
13912   if( mem.nAlloc[NCSIZE-1] ){
13913     fprintf(out, "   %5d: %10d %10d %10d\n",
13914              NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
13915              mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
13916   }
13917   fclose(out);
13918 }
13919
13920 /*
13921 ** Return the number of times sqlite3MemMalloc() has been called.
13922 */
13923 SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
13924   int i;
13925   int nTotal = 0;
13926   for(i=0; i<NCSIZE; i++){
13927     nTotal += mem.nAlloc[i];
13928   }
13929   return nTotal;
13930 }
13931
13932
13933 #endif /* SQLITE_MEMDEBUG */
13934
13935 /************** End of mem2.c ************************************************/
13936 /************** Begin file mem3.c ********************************************/
13937 /*
13938 ** 2007 October 14
13939 **
13940 ** The author disclaims copyright to this source code.  In place of
13941 ** a legal notice, here is a blessing:
13942 **
13943 **    May you do good and not evil.
13944 **    May you find forgiveness for yourself and forgive others.
13945 **    May you share freely, never taking more than you give.
13946 **
13947 *************************************************************************
13948 ** This file contains the C functions that implement a memory
13949 ** allocation subsystem for use by SQLite. 
13950 **
13951 ** This version of the memory allocation subsystem omits all
13952 ** use of malloc(). The SQLite user supplies a block of memory
13953 ** before calling sqlite3_initialize() from which allocations
13954 ** are made and returned by the xMalloc() and xRealloc() 
13955 ** implementations. Once sqlite3_initialize() has been called,
13956 ** the amount of memory available to SQLite is fixed and cannot
13957 ** be changed.
13958 **
13959 ** This version of the memory allocation subsystem is included
13960 ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
13961 */
13962
13963 /*
13964 ** This version of the memory allocator is only built into the library
13965 ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
13966 ** mean that the library will use a memory-pool by default, just that
13967 ** it is available. The mempool allocator is activated by calling
13968 ** sqlite3_config().
13969 */
13970 #ifdef SQLITE_ENABLE_MEMSYS3
13971
13972 /*
13973 ** Maximum size (in Mem3Blocks) of a "small" chunk.
13974 */
13975 #define MX_SMALL 10
13976
13977
13978 /*
13979 ** Number of freelist hash slots
13980 */
13981 #define N_HASH  61
13982
13983 /*
13984 ** A memory allocation (also called a "chunk") consists of two or 
13985 ** more blocks where each block is 8 bytes.  The first 8 bytes are 
13986 ** a header that is not returned to the user.
13987 **
13988 ** A chunk is two or more blocks that is either checked out or
13989 ** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
13990 ** size of the allocation in blocks if the allocation is free.
13991 ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
13992 ** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
13993 ** is true if the previous chunk is checked out and false if the
13994 ** previous chunk is free.  The u.hdr.prevSize field is the size of
13995 ** the previous chunk in blocks if the previous chunk is on the
13996 ** freelist. If the previous chunk is checked out, then
13997 ** u.hdr.prevSize can be part of the data for that chunk and should
13998 ** not be read or written.
13999 **
14000 ** We often identify a chunk by its index in mem3.aPool[].  When
14001 ** this is done, the chunk index refers to the second block of
14002 ** the chunk.  In this way, the first chunk has an index of 1.
14003 ** A chunk index of 0 means "no such chunk" and is the equivalent
14004 ** of a NULL pointer.
14005 **
14006 ** The second block of free chunks is of the form u.list.  The
14007 ** two fields form a double-linked list of chunks of related sizes.
14008 ** Pointers to the head of the list are stored in mem3.aiSmall[] 
14009 ** for smaller chunks and mem3.aiHash[] for larger chunks.
14010 **
14011 ** The second block of a chunk is user data if the chunk is checked 
14012 ** out.  If a chunk is checked out, the user data may extend into
14013 ** the u.hdr.prevSize value of the following chunk.
14014 */
14015 typedef struct Mem3Block Mem3Block;
14016 struct Mem3Block {
14017   union {
14018     struct {
14019       u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
14020       u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
14021     } hdr;
14022     struct {
14023       u32 next;       /* Index in mem3.aPool[] of next free chunk */
14024       u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
14025     } list;
14026   } u;
14027 };
14028
14029 /*
14030 ** All of the static variables used by this module are collected
14031 ** into a single structure named "mem3".  This is to keep the
14032 ** static variables organized and to reduce namespace pollution
14033 ** when this module is combined with other in the amalgamation.
14034 */
14035 static SQLITE_WSD struct Mem3Global {
14036   /*
14037   ** Memory available for allocation. nPool is the size of the array
14038   ** (in Mem3Blocks) pointed to by aPool less 2.
14039   */
14040   u32 nPool;
14041   Mem3Block *aPool;
14042
14043   /*
14044   ** True if we are evaluating an out-of-memory callback.
14045   */
14046   int alarmBusy;
14047   
14048   /*
14049   ** Mutex to control access to the memory allocation subsystem.
14050   */
14051   sqlite3_mutex *mutex;
14052   
14053   /*
14054   ** The minimum amount of free space that we have seen.
14055   */
14056   u32 mnMaster;
14057
14058   /*
14059   ** iMaster is the index of the master chunk.  Most new allocations
14060   ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
14061   ** of the current master.  iMaster is 0 if there is not master chunk.
14062   ** The master chunk is not in either the aiHash[] or aiSmall[].
14063   */
14064   u32 iMaster;
14065   u32 szMaster;
14066
14067   /*
14068   ** Array of lists of free blocks according to the block size 
14069   ** for smaller chunks, or a hash on the block size for larger
14070   ** chunks.
14071   */
14072   u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
14073   u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
14074 } mem3 = { 97535575 };
14075
14076 #define mem3 GLOBAL(struct Mem3Global, mem3)
14077
14078 /*
14079 ** Unlink the chunk at mem3.aPool[i] from list it is currently
14080 ** on.  *pRoot is the list that i is a member of.
14081 */
14082 static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
14083   u32 next = mem3.aPool[i].u.list.next;
14084   u32 prev = mem3.aPool[i].u.list.prev;
14085   assert( sqlite3_mutex_held(mem3.mutex) );
14086   if( prev==0 ){
14087     *pRoot = next;
14088   }else{
14089     mem3.aPool[prev].u.list.next = next;
14090   }
14091   if( next ){
14092     mem3.aPool[next].u.list.prev = prev;
14093   }
14094   mem3.aPool[i].u.list.next = 0;
14095   mem3.aPool[i].u.list.prev = 0;
14096 }
14097
14098 /*
14099 ** Unlink the chunk at index i from 
14100 ** whatever list is currently a member of.
14101 */
14102 static void memsys3Unlink(u32 i){
14103   u32 size, hash;
14104   assert( sqlite3_mutex_held(mem3.mutex) );
14105   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
14106   assert( i>=1 );
14107   size = mem3.aPool[i-1].u.hdr.size4x/4;
14108   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
14109   assert( size>=2 );
14110   if( size <= MX_SMALL ){
14111     memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
14112   }else{
14113     hash = size % N_HASH;
14114     memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
14115   }
14116 }
14117
14118 /*
14119 ** Link the chunk at mem3.aPool[i] so that is on the list rooted
14120 ** at *pRoot.
14121 */
14122 static void memsys3LinkIntoList(u32 i, u32 *pRoot){
14123   assert( sqlite3_mutex_held(mem3.mutex) );
14124   mem3.aPool[i].u.list.next = *pRoot;
14125   mem3.aPool[i].u.list.prev = 0;
14126   if( *pRoot ){
14127     mem3.aPool[*pRoot].u.list.prev = i;
14128   }
14129   *pRoot = i;
14130 }
14131
14132 /*
14133 ** Link the chunk at index i into either the appropriate
14134 ** small chunk list, or into the large chunk hash table.
14135 */
14136 static void memsys3Link(u32 i){
14137   u32 size, hash;
14138   assert( sqlite3_mutex_held(mem3.mutex) );
14139   assert( i>=1 );
14140   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
14141   size = mem3.aPool[i-1].u.hdr.size4x/4;
14142   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
14143   assert( size>=2 );
14144   if( size <= MX_SMALL ){
14145     memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
14146   }else{
14147     hash = size % N_HASH;
14148     memsys3LinkIntoList(i, &mem3.aiHash[hash]);
14149   }
14150 }
14151
14152 /*
14153 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
14154 ** will already be held (obtained by code in malloc.c) if
14155 ** sqlite3GlobalConfig.bMemStat is true.
14156 */
14157 static void memsys3Enter(void){
14158   if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
14159     mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
14160   }
14161   sqlite3_mutex_enter(mem3.mutex);
14162 }
14163 static void memsys3Leave(void){
14164   sqlite3_mutex_leave(mem3.mutex);
14165 }
14166
14167 /*
14168 ** Called when we are unable to satisfy an allocation of nBytes.
14169 */
14170 static void memsys3OutOfMemory(int nByte){
14171   if( !mem3.alarmBusy ){
14172     mem3.alarmBusy = 1;
14173     assert( sqlite3_mutex_held(mem3.mutex) );
14174     sqlite3_mutex_leave(mem3.mutex);
14175     sqlite3_release_memory(nByte);
14176     sqlite3_mutex_enter(mem3.mutex);
14177     mem3.alarmBusy = 0;
14178   }
14179 }
14180
14181
14182 /*
14183 ** Chunk i is a free chunk that has been unlinked.  Adjust its 
14184 ** size parameters for check-out and return a pointer to the 
14185 ** user portion of the chunk.
14186 */
14187 static void *memsys3Checkout(u32 i, u32 nBlock){
14188   u32 x;
14189   assert( sqlite3_mutex_held(mem3.mutex) );
14190   assert( i>=1 );
14191   assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
14192   assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
14193   x = mem3.aPool[i-1].u.hdr.size4x;
14194   mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
14195   mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
14196   mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
14197   return &mem3.aPool[i];
14198 }
14199
14200 /*
14201 ** Carve a piece off of the end of the mem3.iMaster free chunk.
14202 ** Return a pointer to the new allocation.  Or, if the master chunk
14203 ** is not large enough, return 0.
14204 */
14205 static void *memsys3FromMaster(u32 nBlock){
14206   assert( sqlite3_mutex_held(mem3.mutex) );
14207   assert( mem3.szMaster>=nBlock );
14208   if( nBlock>=mem3.szMaster-1 ){
14209     /* Use the entire master */
14210     void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
14211     mem3.iMaster = 0;
14212     mem3.szMaster = 0;
14213     mem3.mnMaster = 0;
14214     return p;
14215   }else{
14216     /* Split the master block.  Return the tail. */
14217     u32 newi, x;
14218     newi = mem3.iMaster + mem3.szMaster - nBlock;
14219     assert( newi > mem3.iMaster+1 );
14220     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
14221     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
14222     mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
14223     mem3.szMaster -= nBlock;
14224     mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
14225     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
14226     mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
14227     if( mem3.szMaster < mem3.mnMaster ){
14228       mem3.mnMaster = mem3.szMaster;
14229     }
14230     return (void*)&mem3.aPool[newi];
14231   }
14232 }
14233
14234 /*
14235 ** *pRoot is the head of a list of free chunks of the same size
14236 ** or same size hash.  In other words, *pRoot is an entry in either
14237 ** mem3.aiSmall[] or mem3.aiHash[].  
14238 **
14239 ** This routine examines all entries on the given list and tries
14240 ** to coalesce each entries with adjacent free chunks.  
14241 **
14242 ** If it sees a chunk that is larger than mem3.iMaster, it replaces 
14243 ** the current mem3.iMaster with the new larger chunk.  In order for
14244 ** this mem3.iMaster replacement to work, the master chunk must be
14245 ** linked into the hash tables.  That is not the normal state of
14246 ** affairs, of course.  The calling routine must link the master
14247 ** chunk before invoking this routine, then must unlink the (possibly
14248 ** changed) master chunk once this routine has finished.
14249 */
14250 static void memsys3Merge(u32 *pRoot){
14251   u32 iNext, prev, size, i, x;
14252
14253   assert( sqlite3_mutex_held(mem3.mutex) );
14254   for(i=*pRoot; i>0; i=iNext){
14255     iNext = mem3.aPool[i].u.list.next;
14256     size = mem3.aPool[i-1].u.hdr.size4x;
14257     assert( (size&1)==0 );
14258     if( (size&2)==0 ){
14259       memsys3UnlinkFromList(i, pRoot);
14260       assert( i > mem3.aPool[i-1].u.hdr.prevSize );
14261       prev = i - mem3.aPool[i-1].u.hdr.prevSize;
14262       if( prev==iNext ){
14263         iNext = mem3.aPool[prev].u.list.next;
14264       }
14265       memsys3Unlink(prev);
14266       size = i + size/4 - prev;
14267       x = mem3.aPool[prev-1].u.hdr.size4x & 2;
14268       mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
14269       mem3.aPool[prev+size-1].u.hdr.prevSize = size;
14270       memsys3Link(prev);
14271       i = prev;
14272     }else{
14273       size /= 4;
14274     }
14275     if( size>mem3.szMaster ){
14276       mem3.iMaster = i;
14277       mem3.szMaster = size;
14278     }
14279   }
14280 }
14281
14282 /*
14283 ** Return a block of memory of at least nBytes in size.
14284 ** Return NULL if unable.
14285 **
14286 ** This function assumes that the necessary mutexes, if any, are
14287 ** already held by the caller. Hence "Unsafe".
14288 */
14289 static void *memsys3MallocUnsafe(int nByte){
14290   u32 i;
14291   u32 nBlock;
14292   u32 toFree;
14293
14294   assert( sqlite3_mutex_held(mem3.mutex) );
14295   assert( sizeof(Mem3Block)==8 );
14296   if( nByte<=12 ){
14297     nBlock = 2;
14298   }else{
14299     nBlock = (nByte + 11)/8;
14300   }
14301   assert( nBlock>=2 );
14302
14303   /* STEP 1:
14304   ** Look for an entry of the correct size in either the small
14305   ** chunk table or in the large chunk hash table.  This is
14306   ** successful most of the time (about 9 times out of 10).
14307   */
14308   if( nBlock <= MX_SMALL ){
14309     i = mem3.aiSmall[nBlock-2];
14310     if( i>0 ){
14311       memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
14312       return memsys3Checkout(i, nBlock);
14313     }
14314   }else{
14315     int hash = nBlock % N_HASH;
14316     for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
14317       if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
14318         memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
14319         return memsys3Checkout(i, nBlock);
14320       }
14321     }
14322   }
14323
14324   /* STEP 2:
14325   ** Try to satisfy the allocation by carving a piece off of the end
14326   ** of the master chunk.  This step usually works if step 1 fails.
14327   */
14328   if( mem3.szMaster>=nBlock ){
14329     return memsys3FromMaster(nBlock);
14330   }
14331
14332
14333   /* STEP 3:  
14334   ** Loop through the entire memory pool.  Coalesce adjacent free
14335   ** chunks.  Recompute the master chunk as the largest free chunk.
14336   ** Then try again to satisfy the allocation by carving a piece off
14337   ** of the end of the master chunk.  This step happens very
14338   ** rarely (we hope!)
14339   */
14340   for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
14341     memsys3OutOfMemory(toFree);
14342     if( mem3.iMaster ){
14343       memsys3Link(mem3.iMaster);
14344       mem3.iMaster = 0;
14345       mem3.szMaster = 0;
14346     }
14347     for(i=0; i<N_HASH; i++){
14348       memsys3Merge(&mem3.aiHash[i]);
14349     }
14350     for(i=0; i<MX_SMALL-1; i++){
14351       memsys3Merge(&mem3.aiSmall[i]);
14352     }
14353     if( mem3.szMaster ){
14354       memsys3Unlink(mem3.iMaster);
14355       if( mem3.szMaster>=nBlock ){
14356         return memsys3FromMaster(nBlock);
14357       }
14358     }
14359   }
14360
14361   /* If none of the above worked, then we fail. */
14362   return 0;
14363 }
14364
14365 /*
14366 ** Free an outstanding memory allocation.
14367 **
14368 ** This function assumes that the necessary mutexes, if any, are
14369 ** already held by the caller. Hence "Unsafe".
14370 */
14371 void memsys3FreeUnsafe(void *pOld){
14372   Mem3Block *p = (Mem3Block*)pOld;
14373   int i;
14374   u32 size, x;
14375   assert( sqlite3_mutex_held(mem3.mutex) );
14376   assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
14377   i = p - mem3.aPool;
14378   assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
14379   size = mem3.aPool[i-1].u.hdr.size4x/4;
14380   assert( i+size<=mem3.nPool+1 );
14381   mem3.aPool[i-1].u.hdr.size4x &= ~1;
14382   mem3.aPool[i+size-1].u.hdr.prevSize = size;
14383   mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
14384   memsys3Link(i);
14385
14386   /* Try to expand the master using the newly freed chunk */
14387   if( mem3.iMaster ){
14388     while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
14389       size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
14390       mem3.iMaster -= size;
14391       mem3.szMaster += size;
14392       memsys3Unlink(mem3.iMaster);
14393       x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
14394       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
14395       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
14396     }
14397     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
14398     while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
14399       memsys3Unlink(mem3.iMaster+mem3.szMaster);
14400       mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
14401       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
14402       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
14403     }
14404   }
14405 }
14406
14407 /*
14408 ** Return the size of an outstanding allocation, in bytes.  The
14409 ** size returned omits the 8-byte header overhead.  This only
14410 ** works for chunks that are currently checked out.
14411 */
14412 static int memsys3Size(void *p){
14413   Mem3Block *pBlock;
14414   if( p==0 ) return 0;
14415   pBlock = (Mem3Block*)p;
14416   assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
14417   return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
14418 }
14419
14420 /*
14421 ** Round up a request size to the next valid allocation size.
14422 */
14423 static int memsys3Roundup(int n){
14424   if( n<=12 ){
14425     return 12;
14426   }else{
14427     return ((n+11)&~7) - 4;
14428   }
14429 }
14430
14431 /*
14432 ** Allocate nBytes of memory.
14433 */
14434 static void *memsys3Malloc(int nBytes){
14435   sqlite3_int64 *p;
14436   assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
14437   memsys3Enter();
14438   p = memsys3MallocUnsafe(nBytes);
14439   memsys3Leave();
14440   return (void*)p; 
14441 }
14442
14443 /*
14444 ** Free memory.
14445 */
14446 void memsys3Free(void *pPrior){
14447   assert( pPrior );
14448   memsys3Enter();
14449   memsys3FreeUnsafe(pPrior);
14450   memsys3Leave();
14451 }
14452
14453 /*
14454 ** Change the size of an existing memory allocation
14455 */
14456 void *memsys3Realloc(void *pPrior, int nBytes){
14457   int nOld;
14458   void *p;
14459   if( pPrior==0 ){
14460     return sqlite3_malloc(nBytes);
14461   }
14462   if( nBytes<=0 ){
14463     sqlite3_free(pPrior);
14464     return 0;
14465   }
14466   nOld = memsys3Size(pPrior);
14467   if( nBytes<=nOld && nBytes>=nOld-128 ){
14468     return pPrior;
14469   }
14470   memsys3Enter();
14471   p = memsys3MallocUnsafe(nBytes);
14472   if( p ){
14473     if( nOld<nBytes ){
14474       memcpy(p, pPrior, nOld);
14475     }else{
14476       memcpy(p, pPrior, nBytes);
14477     }
14478     memsys3FreeUnsafe(pPrior);
14479   }
14480   memsys3Leave();
14481   return p;
14482 }
14483
14484 /*
14485 ** Initialize this module.
14486 */
14487 static int memsys3Init(void *NotUsed){
14488   UNUSED_PARAMETER(NotUsed);
14489   if( !sqlite3GlobalConfig.pHeap ){
14490     return SQLITE_ERROR;
14491   }
14492
14493   /* Store a pointer to the memory block in global structure mem3. */
14494   assert( sizeof(Mem3Block)==8 );
14495   mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
14496   mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
14497
14498   /* Initialize the master block. */
14499   mem3.szMaster = mem3.nPool;
14500   mem3.mnMaster = mem3.szMaster;
14501   mem3.iMaster = 1;
14502   mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
14503   mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
14504   mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
14505
14506   return SQLITE_OK;
14507 }
14508
14509 /*
14510 ** Deinitialize this module.
14511 */
14512 static void memsys3Shutdown(void *NotUsed){
14513   UNUSED_PARAMETER(NotUsed);
14514   mem3.mutex = 0;
14515   return;
14516 }
14517
14518
14519
14520 /*
14521 ** Open the file indicated and write a log of all unfreed memory 
14522 ** allocations into that log.
14523 */
14524 SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
14525 #ifdef SQLITE_DEBUG
14526   FILE *out;
14527   u32 i, j;
14528   u32 size;
14529   if( zFilename==0 || zFilename[0]==0 ){
14530     out = stdout;
14531   }else{
14532     out = fopen(zFilename, "w");
14533     if( out==0 ){
14534       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
14535                       zFilename);
14536       return;
14537     }
14538   }
14539   memsys3Enter();
14540   fprintf(out, "CHUNKS:\n");
14541   for(i=1; i<=mem3.nPool; i+=size/4){
14542     size = mem3.aPool[i-1].u.hdr.size4x;
14543     if( size/4<=1 ){
14544       fprintf(out, "%p size error\n", &mem3.aPool[i]);
14545       assert( 0 );
14546       break;
14547     }
14548     if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
14549       fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
14550       assert( 0 );
14551       break;
14552     }
14553     if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
14554       fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
14555       assert( 0 );
14556       break;
14557     }
14558     if( size&1 ){
14559       fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
14560     }else{
14561       fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
14562                   i==mem3.iMaster ? " **master**" : "");
14563     }
14564   }
14565   for(i=0; i<MX_SMALL-1; i++){
14566     if( mem3.aiSmall[i]==0 ) continue;
14567     fprintf(out, "small(%2d):", i);
14568     for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
14569       fprintf(out, " %p(%d)", &mem3.aPool[j],
14570               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
14571     }
14572     fprintf(out, "\n"); 
14573   }
14574   for(i=0; i<N_HASH; i++){
14575     if( mem3.aiHash[i]==0 ) continue;
14576     fprintf(out, "hash(%2d):", i);
14577     for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
14578       fprintf(out, " %p(%d)", &mem3.aPool[j],
14579               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
14580     }
14581     fprintf(out, "\n"); 
14582   }
14583   fprintf(out, "master=%d\n", mem3.iMaster);
14584   fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
14585   fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
14586   sqlite3_mutex_leave(mem3.mutex);
14587   if( out==stdout ){
14588     fflush(stdout);
14589   }else{
14590     fclose(out);
14591   }
14592 #else
14593   UNUSED_PARAMETER(zFilename);
14594 #endif
14595 }
14596
14597 /*
14598 ** This routine is the only routine in this file with external 
14599 ** linkage.
14600 **
14601 ** Populate the low-level memory allocation function pointers in
14602 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
14603 ** arguments specify the block of memory to manage.
14604 **
14605 ** This routine is only called by sqlite3_config(), and therefore
14606 ** is not required to be threadsafe (it is not).
14607 */
14608 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
14609   static const sqlite3_mem_methods mempoolMethods = {
14610      memsys3Malloc,
14611      memsys3Free,
14612      memsys3Realloc,
14613      memsys3Size,
14614      memsys3Roundup,
14615      memsys3Init,
14616      memsys3Shutdown,
14617      0
14618   };
14619   return &mempoolMethods;
14620 }
14621
14622 #endif /* SQLITE_ENABLE_MEMSYS3 */
14623
14624 /************** End of mem3.c ************************************************/
14625 /************** Begin file mem5.c ********************************************/
14626 /*
14627 ** 2007 October 14
14628 **
14629 ** The author disclaims copyright to this source code.  In place of
14630 ** a legal notice, here is a blessing:
14631 **
14632 **    May you do good and not evil.
14633 **    May you find forgiveness for yourself and forgive others.
14634 **    May you share freely, never taking more than you give.
14635 **
14636 *************************************************************************
14637 ** This file contains the C functions that implement a memory
14638 ** allocation subsystem for use by SQLite. 
14639 **
14640 ** This version of the memory allocation subsystem omits all
14641 ** use of malloc(). The application gives SQLite a block of memory
14642 ** before calling sqlite3_initialize() from which allocations
14643 ** are made and returned by the xMalloc() and xRealloc() 
14644 ** implementations. Once sqlite3_initialize() has been called,
14645 ** the amount of memory available to SQLite is fixed and cannot
14646 ** be changed.
14647 **
14648 ** This version of the memory allocation subsystem is included
14649 ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
14650 **
14651 ** This memory allocator uses the following algorithm:
14652 **
14653 **   1.  All memory allocations sizes are rounded up to a power of 2.
14654 **
14655 **   2.  If two adjacent free blocks are the halves of a larger block,
14656 **       then the two blocks are coalesed into the single larger block.
14657 **
14658 **   3.  New memory is allocated from the first available free block.
14659 **
14660 ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
14661 ** Concerning Dynamic Storage Allocation". Journal of the Association for
14662 ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
14663 ** 
14664 ** Let n be the size of the largest allocation divided by the minimum
14665 ** allocation size (after rounding all sizes up to a power of 2.)  Let M
14666 ** be the maximum amount of memory ever outstanding at one time.  Let
14667 ** N be the total amount of memory available for allocation.  Robson
14668 ** proved that this memory allocator will never breakdown due to 
14669 ** fragmentation as long as the following constraint holds:
14670 **
14671 **      N >=  M*(1 + log2(n)/2) - n + 1
14672 **
14673 ** The sqlite3_status() logic tracks the maximum values of n and M so
14674 ** that an application can, at any time, verify this constraint.
14675 */
14676
14677 /*
14678 ** This version of the memory allocator is used only when 
14679 ** SQLITE_ENABLE_MEMSYS5 is defined.
14680 */
14681 #ifdef SQLITE_ENABLE_MEMSYS5
14682
14683 /*
14684 ** A minimum allocation is an instance of the following structure.
14685 ** Larger allocations are an array of these structures where the
14686 ** size of the array is a power of 2.
14687 **
14688 ** The size of this object must be a power of two.  That fact is
14689 ** verified in memsys5Init().
14690 */
14691 typedef struct Mem5Link Mem5Link;
14692 struct Mem5Link {
14693   int next;       /* Index of next free chunk */
14694   int prev;       /* Index of previous free chunk */
14695 };
14696
14697 /*
14698 ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
14699 ** mem5.szAtom is always at least 8 and 32-bit integers are used,
14700 ** it is not actually possible to reach this limit.
14701 */
14702 #define LOGMAX 30
14703
14704 /*
14705 ** Masks used for mem5.aCtrl[] elements.
14706 */
14707 #define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
14708 #define CTRL_FREE     0x20    /* True if not checked out */
14709
14710 /*
14711 ** All of the static variables used by this module are collected
14712 ** into a single structure named "mem5".  This is to keep the
14713 ** static variables organized and to reduce namespace pollution
14714 ** when this module is combined with other in the amalgamation.
14715 */
14716 static SQLITE_WSD struct Mem5Global {
14717   /*
14718   ** Memory available for allocation
14719   */
14720   int szAtom;      /* Smallest possible allocation in bytes */
14721   int nBlock;      /* Number of szAtom sized blocks in zPool */
14722   u8 *zPool;       /* Memory available to be allocated */
14723   
14724   /*
14725   ** Mutex to control access to the memory allocation subsystem.
14726   */
14727   sqlite3_mutex *mutex;
14728
14729   /*
14730   ** Performance statistics
14731   */
14732   u64 nAlloc;         /* Total number of calls to malloc */
14733   u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
14734   u64 totalExcess;    /* Total internal fragmentation */
14735   u32 currentOut;     /* Current checkout, including internal fragmentation */
14736   u32 currentCount;   /* Current number of distinct checkouts */
14737   u32 maxOut;         /* Maximum instantaneous currentOut */
14738   u32 maxCount;       /* Maximum instantaneous currentCount */
14739   u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
14740   
14741   /*
14742   ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
14743   ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
14744   ** and so forth.
14745   */
14746   int aiFreelist[LOGMAX+1];
14747
14748   /*
14749   ** Space for tracking which blocks are checked out and the size
14750   ** of each block.  One byte per block.
14751   */
14752   u8 *aCtrl;
14753
14754 } mem5 = { 0 };
14755
14756 /*
14757 ** Access the static variable through a macro for SQLITE_OMIT_WSD
14758 */
14759 #define mem5 GLOBAL(struct Mem5Global, mem5)
14760
14761 /*
14762 ** Assuming mem5.zPool is divided up into an array of Mem5Link
14763 ** structures, return a pointer to the idx-th such lik.
14764 */
14765 #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
14766
14767 /*
14768 ** Unlink the chunk at mem5.aPool[i] from list it is currently
14769 ** on.  It should be found on mem5.aiFreelist[iLogsize].
14770 */
14771 static void memsys5Unlink(int i, int iLogsize){
14772   int next, prev;
14773   assert( i>=0 && i<mem5.nBlock );
14774   assert( iLogsize>=0 && iLogsize<=LOGMAX );
14775   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
14776
14777   next = MEM5LINK(i)->next;
14778   prev = MEM5LINK(i)->prev;
14779   if( prev<0 ){
14780     mem5.aiFreelist[iLogsize] = next;
14781   }else{
14782     MEM5LINK(prev)->next = next;
14783   }
14784   if( next>=0 ){
14785     MEM5LINK(next)->prev = prev;
14786   }
14787 }
14788
14789 /*
14790 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
14791 ** free list.
14792 */
14793 static void memsys5Link(int i, int iLogsize){
14794   int x;
14795   assert( sqlite3_mutex_held(mem5.mutex) );
14796   assert( i>=0 && i<mem5.nBlock );
14797   assert( iLogsize>=0 && iLogsize<=LOGMAX );
14798   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
14799
14800   x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
14801   MEM5LINK(i)->prev = -1;
14802   if( x>=0 ){
14803     assert( x<mem5.nBlock );
14804     MEM5LINK(x)->prev = i;
14805   }
14806   mem5.aiFreelist[iLogsize] = i;
14807 }
14808
14809 /*
14810 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
14811 ** will already be held (obtained by code in malloc.c) if
14812 ** sqlite3GlobalConfig.bMemStat is true.
14813 */
14814 static void memsys5Enter(void){
14815   sqlite3_mutex_enter(mem5.mutex);
14816 }
14817 static void memsys5Leave(void){
14818   sqlite3_mutex_leave(mem5.mutex);
14819 }
14820
14821 /*
14822 ** Return the size of an outstanding allocation, in bytes.  The
14823 ** size returned omits the 8-byte header overhead.  This only
14824 ** works for chunks that are currently checked out.
14825 */
14826 static int memsys5Size(void *p){
14827   int iSize = 0;
14828   if( p ){
14829     int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;
14830     assert( i>=0 && i<mem5.nBlock );
14831     iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
14832   }
14833   return iSize;
14834 }
14835
14836 /*
14837 ** Find the first entry on the freelist iLogsize.  Unlink that
14838 ** entry and return its index. 
14839 */
14840 static int memsys5UnlinkFirst(int iLogsize){
14841   int i;
14842   int iFirst;
14843
14844   assert( iLogsize>=0 && iLogsize<=LOGMAX );
14845   i = iFirst = mem5.aiFreelist[iLogsize];
14846   assert( iFirst>=0 );
14847   while( i>0 ){
14848     if( i<iFirst ) iFirst = i;
14849     i = MEM5LINK(i)->next;
14850   }
14851   memsys5Unlink(iFirst, iLogsize);
14852   return iFirst;
14853 }
14854
14855 /*
14856 ** Return a block of memory of at least nBytes in size.
14857 ** Return NULL if unable.  Return NULL if nBytes==0.
14858 **
14859 ** The caller guarantees that nByte positive.
14860 **
14861 ** The caller has obtained a mutex prior to invoking this
14862 ** routine so there is never any chance that two or more
14863 ** threads can be in this routine at the same time.
14864 */
14865 static void *memsys5MallocUnsafe(int nByte){
14866   int i;           /* Index of a mem5.aPool[] slot */
14867   int iBin;        /* Index into mem5.aiFreelist[] */
14868   int iFullSz;     /* Size of allocation rounded up to power of 2 */
14869   int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
14870
14871   /* nByte must be a positive */
14872   assert( nByte>0 );
14873
14874   /* Keep track of the maximum allocation request.  Even unfulfilled
14875   ** requests are counted */
14876   if( (u32)nByte>mem5.maxRequest ){
14877     mem5.maxRequest = nByte;
14878   }
14879
14880   /* Abort if the requested allocation size is larger than the largest
14881   ** power of two that we can represent using 32-bit signed integers.
14882   */
14883   if( nByte > 0x40000000 ){
14884     return 0;
14885   }
14886
14887   /* Round nByte up to the next valid power of two */
14888   for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
14889
14890   /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
14891   ** block.  If not, then split a block of the next larger power of
14892   ** two in order to create a new free block of size iLogsize.
14893   */
14894   for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
14895   if( iBin>LOGMAX ){
14896     testcase( sqlite3GlobalConfig.xLog!=0 );
14897     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
14898     return 0;
14899   }
14900   i = memsys5UnlinkFirst(iBin);
14901   while( iBin>iLogsize ){
14902     int newSize;
14903
14904     iBin--;
14905     newSize = 1 << iBin;
14906     mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
14907     memsys5Link(i+newSize, iBin);
14908   }
14909   mem5.aCtrl[i] = iLogsize;
14910
14911   /* Update allocator performance statistics. */
14912   mem5.nAlloc++;
14913   mem5.totalAlloc += iFullSz;
14914   mem5.totalExcess += iFullSz - nByte;
14915   mem5.currentCount++;
14916   mem5.currentOut += iFullSz;
14917   if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
14918   if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
14919
14920   /* Return a pointer to the allocated memory. */
14921   return (void*)&mem5.zPool[i*mem5.szAtom];
14922 }
14923
14924 /*
14925 ** Free an outstanding memory allocation.
14926 */
14927 static void memsys5FreeUnsafe(void *pOld){
14928   u32 size, iLogsize;
14929   int iBlock;
14930
14931   /* Set iBlock to the index of the block pointed to by pOld in 
14932   ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
14933   */
14934   iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;
14935
14936   /* Check that the pointer pOld points to a valid, non-free block. */
14937   assert( iBlock>=0 && iBlock<mem5.nBlock );
14938   assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
14939   assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
14940
14941   iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
14942   size = 1<<iLogsize;
14943   assert( iBlock+size-1<(u32)mem5.nBlock );
14944
14945   mem5.aCtrl[iBlock] |= CTRL_FREE;
14946   mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
14947   assert( mem5.currentCount>0 );
14948   assert( mem5.currentOut>=(size*mem5.szAtom) );
14949   mem5.currentCount--;
14950   mem5.currentOut -= size*mem5.szAtom;
14951   assert( mem5.currentOut>0 || mem5.currentCount==0 );
14952   assert( mem5.currentCount>0 || mem5.currentOut==0 );
14953
14954   mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
14955   while( ALWAYS(iLogsize<LOGMAX) ){
14956     int iBuddy;
14957     if( (iBlock>>iLogsize) & 1 ){
14958       iBuddy = iBlock - size;
14959     }else{
14960       iBuddy = iBlock + size;
14961     }
14962     assert( iBuddy>=0 );
14963     if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
14964     if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
14965     memsys5Unlink(iBuddy, iLogsize);
14966     iLogsize++;
14967     if( iBuddy<iBlock ){
14968       mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
14969       mem5.aCtrl[iBlock] = 0;
14970       iBlock = iBuddy;
14971     }else{
14972       mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
14973       mem5.aCtrl[iBuddy] = 0;
14974     }
14975     size *= 2;
14976   }
14977   memsys5Link(iBlock, iLogsize);
14978 }
14979
14980 /*
14981 ** Allocate nBytes of memory
14982 */
14983 static void *memsys5Malloc(int nBytes){
14984   sqlite3_int64 *p = 0;
14985   if( nBytes>0 ){
14986     memsys5Enter();
14987     p = memsys5MallocUnsafe(nBytes);
14988     memsys5Leave();
14989   }
14990   return (void*)p; 
14991 }
14992
14993 /*
14994 ** Free memory.
14995 **
14996 ** The outer layer memory allocator prevents this routine from
14997 ** being called with pPrior==0.
14998 */
14999 static void memsys5Free(void *pPrior){
15000   assert( pPrior!=0 );
15001   memsys5Enter();
15002   memsys5FreeUnsafe(pPrior);
15003   memsys5Leave();  
15004 }
15005
15006 /*
15007 ** Change the size of an existing memory allocation.
15008 **
15009 ** The outer layer memory allocator prevents this routine from
15010 ** being called with pPrior==0.  
15011 **
15012 ** nBytes is always a value obtained from a prior call to
15013 ** memsys5Round().  Hence nBytes is always a non-negative power
15014 ** of two.  If nBytes==0 that means that an oversize allocation
15015 ** (an allocation larger than 0x40000000) was requested and this
15016 ** routine should return 0 without freeing pPrior.
15017 */
15018 static void *memsys5Realloc(void *pPrior, int nBytes){
15019   int nOld;
15020   void *p;
15021   assert( pPrior!=0 );
15022   assert( (nBytes&(nBytes-1))==0 );
15023   assert( nBytes>=0 );
15024   if( nBytes==0 ){
15025     return 0;
15026   }
15027   nOld = memsys5Size(pPrior);
15028   if( nBytes<=nOld ){
15029     return pPrior;
15030   }
15031   memsys5Enter();
15032   p = memsys5MallocUnsafe(nBytes);
15033   if( p ){
15034     memcpy(p, pPrior, nOld);
15035     memsys5FreeUnsafe(pPrior);
15036   }
15037   memsys5Leave();
15038   return p;
15039 }
15040
15041 /*
15042 ** Round up a request size to the next valid allocation size.  If
15043 ** the allocation is too large to be handled by this allocation system,
15044 ** return 0.
15045 **
15046 ** All allocations must be a power of two and must be expressed by a
15047 ** 32-bit signed integer.  Hence the largest allocation is 0x40000000
15048 ** or 1073741824 bytes.
15049 */
15050 static int memsys5Roundup(int n){
15051   int iFullSz;
15052   if( n > 0x40000000 ) return 0;
15053   for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
15054   return iFullSz;
15055 }
15056
15057 /*
15058 ** Return the ceiling of the logarithm base 2 of iValue.
15059 **
15060 ** Examples:   memsys5Log(1) -> 0
15061 **             memsys5Log(2) -> 1
15062 **             memsys5Log(4) -> 2
15063 **             memsys5Log(5) -> 3
15064 **             memsys5Log(8) -> 3
15065 **             memsys5Log(9) -> 4
15066 */
15067 static int memsys5Log(int iValue){
15068   int iLog;
15069   for(iLog=0; (1<<iLog)<iValue; iLog++);
15070   return iLog;
15071 }
15072
15073 /*
15074 ** Initialize the memory allocator.
15075 **
15076 ** This routine is not threadsafe.  The caller must be holding a mutex
15077 ** to prevent multiple threads from entering at the same time.
15078 */
15079 static int memsys5Init(void *NotUsed){
15080   int ii;            /* Loop counter */
15081   int nByte;         /* Number of bytes of memory available to this allocator */
15082   u8 *zByte;         /* Memory usable by this allocator */
15083   int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
15084   int iOffset;       /* An offset into mem5.aCtrl[] */
15085
15086   UNUSED_PARAMETER(NotUsed);
15087
15088   /* For the purposes of this routine, disable the mutex */
15089   mem5.mutex = 0;
15090
15091   /* The size of a Mem5Link object must be a power of two.  Verify that
15092   ** this is case.
15093   */
15094   assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
15095
15096   nByte = sqlite3GlobalConfig.nHeap;
15097   zByte = (u8*)sqlite3GlobalConfig.pHeap;
15098   assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */
15099
15100   nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
15101   mem5.szAtom = (1<<nMinLog);
15102   while( (int)sizeof(Mem5Link)>mem5.szAtom ){
15103     mem5.szAtom = mem5.szAtom << 1;
15104   }
15105
15106   mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
15107   mem5.zPool = zByte;
15108   mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
15109
15110   for(ii=0; ii<=LOGMAX; ii++){
15111     mem5.aiFreelist[ii] = -1;
15112   }
15113
15114   iOffset = 0;
15115   for(ii=LOGMAX; ii>=0; ii--){
15116     int nAlloc = (1<<ii);
15117     if( (iOffset+nAlloc)<=mem5.nBlock ){
15118       mem5.aCtrl[iOffset] = ii | CTRL_FREE;
15119       memsys5Link(iOffset, ii);
15120       iOffset += nAlloc;
15121     }
15122     assert((iOffset+nAlloc)>mem5.nBlock);
15123   }
15124
15125   /* If a mutex is required for normal operation, allocate one */
15126   if( sqlite3GlobalConfig.bMemstat==0 ){
15127     mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
15128   }
15129
15130   return SQLITE_OK;
15131 }
15132
15133 /*
15134 ** Deinitialize this module.
15135 */
15136 static void memsys5Shutdown(void *NotUsed){
15137   UNUSED_PARAMETER(NotUsed);
15138   mem5.mutex = 0;
15139   return;
15140 }
15141
15142 #ifdef SQLITE_TEST
15143 /*
15144 ** Open the file indicated and write a log of all unfreed memory 
15145 ** allocations into that log.
15146 */
15147 SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
15148   FILE *out;
15149   int i, j, n;
15150   int nMinLog;
15151
15152   if( zFilename==0 || zFilename[0]==0 ){
15153     out = stdout;
15154   }else{
15155     out = fopen(zFilename, "w");
15156     if( out==0 ){
15157       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
15158                       zFilename);
15159       return;
15160     }
15161   }
15162   memsys5Enter();
15163   nMinLog = memsys5Log(mem5.szAtom);
15164   for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
15165     for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
15166     fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
15167   }
15168   fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
15169   fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
15170   fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
15171   fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
15172   fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
15173   fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
15174   fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
15175   fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
15176   memsys5Leave();
15177   if( out==stdout ){
15178     fflush(stdout);
15179   }else{
15180     fclose(out);
15181   }
15182 }
15183 #endif
15184
15185 /*
15186 ** This routine is the only routine in this file with external 
15187 ** linkage. It returns a pointer to a static sqlite3_mem_methods
15188 ** struct populated with the memsys5 methods.
15189 */
15190 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
15191   static const sqlite3_mem_methods memsys5Methods = {
15192      memsys5Malloc,
15193      memsys5Free,
15194      memsys5Realloc,
15195      memsys5Size,
15196      memsys5Roundup,
15197      memsys5Init,
15198      memsys5Shutdown,
15199      0
15200   };
15201   return &memsys5Methods;
15202 }
15203
15204 #endif /* SQLITE_ENABLE_MEMSYS5 */
15205
15206 /************** End of mem5.c ************************************************/
15207 /************** Begin file mutex.c *******************************************/
15208 /*
15209 ** 2007 August 14
15210 **
15211 ** The author disclaims copyright to this source code.  In place of
15212 ** a legal notice, here is a blessing:
15213 **
15214 **    May you do good and not evil.
15215 **    May you find forgiveness for yourself and forgive others.
15216 **    May you share freely, never taking more than you give.
15217 **
15218 *************************************************************************
15219 ** This file contains the C functions that implement mutexes.
15220 **
15221 ** This file contains code that is common across all mutex implementations.
15222 */
15223
15224 #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
15225 /*
15226 ** For debugging purposes, record when the mutex subsystem is initialized
15227 ** and uninitialized so that we can assert() if there is an attempt to
15228 ** allocate a mutex while the system is uninitialized.
15229 */
15230 static SQLITE_WSD int mutexIsInit = 0;
15231 #endif /* SQLITE_DEBUG */
15232
15233
15234 #ifndef SQLITE_MUTEX_OMIT
15235 /*
15236 ** Initialize the mutex system.
15237 */
15238 SQLITE_PRIVATE int sqlite3MutexInit(void){ 
15239   int rc = SQLITE_OK;
15240   if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
15241     /* If the xMutexAlloc method has not been set, then the user did not
15242     ** install a mutex implementation via sqlite3_config() prior to 
15243     ** sqlite3_initialize() being called. This block copies pointers to
15244     ** the default implementation into the sqlite3GlobalConfig structure.
15245     */
15246     sqlite3_mutex_methods const *pFrom;
15247     sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
15248
15249     if( sqlite3GlobalConfig.bCoreMutex ){
15250       pFrom = sqlite3DefaultMutex();
15251     }else{
15252       pFrom = sqlite3NoopMutex();
15253     }
15254     memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
15255     memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
15256            sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
15257     pTo->xMutexAlloc = pFrom->xMutexAlloc;
15258   }
15259   rc = sqlite3GlobalConfig.mutex.xMutexInit();
15260
15261 #ifdef SQLITE_DEBUG
15262   GLOBAL(int, mutexIsInit) = 1;
15263 #endif
15264
15265   return rc;
15266 }
15267
15268 /*
15269 ** Shutdown the mutex system. This call frees resources allocated by
15270 ** sqlite3MutexInit().
15271 */
15272 SQLITE_PRIVATE int sqlite3MutexEnd(void){
15273   int rc = SQLITE_OK;
15274   if( sqlite3GlobalConfig.mutex.xMutexEnd ){
15275     rc = sqlite3GlobalConfig.mutex.xMutexEnd();
15276   }
15277
15278 #ifdef SQLITE_DEBUG
15279   GLOBAL(int, mutexIsInit) = 0;
15280 #endif
15281
15282   return rc;
15283 }
15284
15285 /*
15286 ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
15287 */
15288 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
15289 #ifndef SQLITE_OMIT_AUTOINIT
15290   if( sqlite3_initialize() ) return 0;
15291 #endif
15292   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
15293 }
15294
15295 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
15296   if( !sqlite3GlobalConfig.bCoreMutex ){
15297     return 0;
15298   }
15299   assert( GLOBAL(int, mutexIsInit) );
15300   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
15301 }
15302
15303 /*
15304 ** Free a dynamic mutex.
15305 */
15306 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
15307   if( p ){
15308     sqlite3GlobalConfig.mutex.xMutexFree(p);
15309   }
15310 }
15311
15312 /*
15313 ** Obtain the mutex p. If some other thread already has the mutex, block
15314 ** until it can be obtained.
15315 */
15316 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
15317   if( p ){
15318     sqlite3GlobalConfig.mutex.xMutexEnter(p);
15319   }
15320 }
15321
15322 /*
15323 ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
15324 ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
15325 */
15326 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
15327   int rc = SQLITE_OK;
15328   if( p ){
15329     return sqlite3GlobalConfig.mutex.xMutexTry(p);
15330   }
15331   return rc;
15332 }
15333
15334 /*
15335 ** The sqlite3_mutex_leave() routine exits a mutex that was previously
15336 ** entered by the same thread.  The behavior is undefined if the mutex 
15337 ** is not currently entered. If a NULL pointer is passed as an argument
15338 ** this function is a no-op.
15339 */
15340 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
15341   if( p ){
15342     sqlite3GlobalConfig.mutex.xMutexLeave(p);
15343   }
15344 }
15345
15346 #ifndef NDEBUG
15347 /*
15348 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
15349 ** intended for use inside assert() statements.
15350 */
15351 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
15352   return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
15353 }
15354 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
15355   return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
15356 }
15357 #endif
15358
15359 #endif /* SQLITE_MUTEX_OMIT */
15360
15361 /************** End of mutex.c ***********************************************/
15362 /************** Begin file mutex_noop.c **************************************/
15363 /*
15364 ** 2008 October 07
15365 **
15366 ** The author disclaims copyright to this source code.  In place of
15367 ** a legal notice, here is a blessing:
15368 **
15369 **    May you do good and not evil.
15370 **    May you find forgiveness for yourself and forgive others.
15371 **    May you share freely, never taking more than you give.
15372 **
15373 *************************************************************************
15374 ** This file contains the C functions that implement mutexes.
15375 **
15376 ** This implementation in this file does not provide any mutual
15377 ** exclusion and is thus suitable for use only in applications
15378 ** that use SQLite in a single thread.  The routines defined
15379 ** here are place-holders.  Applications can substitute working
15380 ** mutex routines at start-time using the
15381 **
15382 **     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
15383 **
15384 ** interface.
15385 **
15386 ** If compiled with SQLITE_DEBUG, then additional logic is inserted
15387 ** that does error checking on mutexes to make sure they are being
15388 ** called correctly.
15389 */
15390
15391 #ifndef SQLITE_MUTEX_OMIT
15392
15393 #ifndef SQLITE_DEBUG
15394 /*
15395 ** Stub routines for all mutex methods.
15396 **
15397 ** This routines provide no mutual exclusion or error checking.
15398 */
15399 static int noopMutexInit(void){ return SQLITE_OK; }
15400 static int noopMutexEnd(void){ return SQLITE_OK; }
15401 static sqlite3_mutex *noopMutexAlloc(int id){ 
15402   UNUSED_PARAMETER(id);
15403   return (sqlite3_mutex*)8; 
15404 }
15405 static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
15406 static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
15407 static int noopMutexTry(sqlite3_mutex *p){
15408   UNUSED_PARAMETER(p);
15409   return SQLITE_OK;
15410 }
15411 static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
15412
15413 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
15414   static const sqlite3_mutex_methods sMutex = {
15415     noopMutexInit,
15416     noopMutexEnd,
15417     noopMutexAlloc,
15418     noopMutexFree,
15419     noopMutexEnter,
15420     noopMutexTry,
15421     noopMutexLeave,
15422
15423     0,
15424     0,
15425   };
15426
15427   return &sMutex;
15428 }
15429 #endif /* !SQLITE_DEBUG */
15430
15431 #ifdef SQLITE_DEBUG
15432 /*
15433 ** In this implementation, error checking is provided for testing
15434 ** and debugging purposes.  The mutexes still do not provide any
15435 ** mutual exclusion.
15436 */
15437
15438 /*
15439 ** The mutex object
15440 */
15441 typedef struct sqlite3_debug_mutex {
15442   int id;     /* The mutex type */
15443   int cnt;    /* Number of entries without a matching leave */
15444 } sqlite3_debug_mutex;
15445
15446 /*
15447 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
15448 ** intended for use inside assert() statements.
15449 */
15450 static int debugMutexHeld(sqlite3_mutex *pX){
15451   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
15452   return p==0 || p->cnt>0;
15453 }
15454 static int debugMutexNotheld(sqlite3_mutex *pX){
15455   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
15456   return p==0 || p->cnt==0;
15457 }
15458
15459 /*
15460 ** Initialize and deinitialize the mutex subsystem.
15461 */
15462 static int debugMutexInit(void){ return SQLITE_OK; }
15463 static int debugMutexEnd(void){ return SQLITE_OK; }
15464
15465 /*
15466 ** The sqlite3_mutex_alloc() routine allocates a new
15467 ** mutex and returns a pointer to it.  If it returns NULL
15468 ** that means that a mutex could not be allocated. 
15469 */
15470 static sqlite3_mutex *debugMutexAlloc(int id){
15471   static sqlite3_debug_mutex aStatic[6];
15472   sqlite3_debug_mutex *pNew = 0;
15473   switch( id ){
15474     case SQLITE_MUTEX_FAST:
15475     case SQLITE_MUTEX_RECURSIVE: {
15476       pNew = sqlite3Malloc(sizeof(*pNew));
15477       if( pNew ){
15478         pNew->id = id;
15479         pNew->cnt = 0;
15480       }
15481       break;
15482     }
15483     default: {
15484       assert( id-2 >= 0 );
15485       assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
15486       pNew = &aStatic[id-2];
15487       pNew->id = id;
15488       break;
15489     }
15490   }
15491   return (sqlite3_mutex*)pNew;
15492 }
15493
15494 /*
15495 ** This routine deallocates a previously allocated mutex.
15496 */
15497 static void debugMutexFree(sqlite3_mutex *pX){
15498   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
15499   assert( p->cnt==0 );
15500   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
15501   sqlite3_free(p);
15502 }
15503
15504 /*
15505 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
15506 ** to enter a mutex.  If another thread is already within the mutex,
15507 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
15508 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
15509 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
15510 ** be entered multiple times by the same thread.  In such cases the,
15511 ** mutex must be exited an equal number of times before another thread
15512 ** can enter.  If the same thread tries to enter any other kind of mutex
15513 ** more than once, the behavior is undefined.
15514 */
15515 static void debugMutexEnter(sqlite3_mutex *pX){
15516   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
15517   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
15518   p->cnt++;
15519 }
15520 static int debugMutexTry(sqlite3_mutex *pX){
15521   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
15522   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
15523   p->cnt++;
15524   return SQLITE_OK;
15525 }
15526
15527 /*
15528 ** The sqlite3_mutex_leave() routine exits a mutex that was
15529 ** previously entered by the same thread.  The behavior
15530 ** is undefined if the mutex is not currently entered or
15531 ** is not currently allocated.  SQLite will never do either.
15532 */
15533 static void debugMutexLeave(sqlite3_mutex *pX){
15534   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
15535   assert( debugMutexHeld(pX) );
15536   p->cnt--;
15537   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
15538 }
15539
15540 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
15541   static const sqlite3_mutex_methods sMutex = {
15542     debugMutexInit,
15543     debugMutexEnd,
15544     debugMutexAlloc,
15545     debugMutexFree,
15546     debugMutexEnter,
15547     debugMutexTry,
15548     debugMutexLeave,
15549
15550     debugMutexHeld,
15551     debugMutexNotheld
15552   };
15553
15554   return &sMutex;
15555 }
15556 #endif /* SQLITE_DEBUG */
15557
15558 /*
15559 ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
15560 ** is used regardless of the run-time threadsafety setting.
15561 */
15562 #ifdef SQLITE_MUTEX_NOOP
15563 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
15564   return sqlite3NoopMutex();
15565 }
15566 #endif /* SQLITE_MUTEX_NOOP */
15567 #endif /* SQLITE_MUTEX_OMIT */
15568
15569 /************** End of mutex_noop.c ******************************************/
15570 /************** Begin file mutex_os2.c ***************************************/
15571 /*
15572 ** 2007 August 28
15573 **
15574 ** The author disclaims copyright to this source code.  In place of
15575 ** a legal notice, here is a blessing:
15576 **
15577 **    May you do good and not evil.
15578 **    May you find forgiveness for yourself and forgive others.
15579 **    May you share freely, never taking more than you give.
15580 **
15581 *************************************************************************
15582 ** This file contains the C functions that implement mutexes for OS/2
15583 */
15584
15585 /*
15586 ** The code in this file is only used if SQLITE_MUTEX_OS2 is defined.
15587 ** See the mutex.h file for details.
15588 */
15589 #ifdef SQLITE_MUTEX_OS2
15590
15591 /********************** OS/2 Mutex Implementation **********************
15592 **
15593 ** This implementation of mutexes is built using the OS/2 API.
15594 */
15595
15596 /*
15597 ** The mutex object
15598 ** Each recursive mutex is an instance of the following structure.
15599 */
15600 struct sqlite3_mutex {
15601   HMTX mutex;       /* Mutex controlling the lock */
15602   int  id;          /* Mutex type */
15603   int  nRef;        /* Number of references */
15604   TID  owner;       /* Thread holding this mutex */
15605 };
15606
15607 #define OS2_MUTEX_INITIALIZER   0,0,0,0
15608
15609 /*
15610 ** Initialize and deinitialize the mutex subsystem.
15611 */
15612 static int os2MutexInit(void){ return SQLITE_OK; }
15613 static int os2MutexEnd(void){ return SQLITE_OK; }
15614
15615 /*
15616 ** The sqlite3_mutex_alloc() routine allocates a new
15617 ** mutex and returns a pointer to it.  If it returns NULL
15618 ** that means that a mutex could not be allocated. 
15619 ** SQLite will unwind its stack and return an error.  The argument
15620 ** to sqlite3_mutex_alloc() is one of these integer constants:
15621 **
15622 ** <ul>
15623 ** <li>  SQLITE_MUTEX_FAST               0
15624 ** <li>  SQLITE_MUTEX_RECURSIVE          1
15625 ** <li>  SQLITE_MUTEX_STATIC_MASTER      2
15626 ** <li>  SQLITE_MUTEX_STATIC_MEM         3
15627 ** <li>  SQLITE_MUTEX_STATIC_PRNG        4
15628 ** </ul>
15629 **
15630 ** The first two constants cause sqlite3_mutex_alloc() to create
15631 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
15632 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
15633 ** The mutex implementation does not need to make a distinction
15634 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
15635 ** not want to.  But SQLite will only request a recursive mutex in
15636 ** cases where it really needs one.  If a faster non-recursive mutex
15637 ** implementation is available on the host platform, the mutex subsystem
15638 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
15639 **
15640 ** The other allowed parameters to sqlite3_mutex_alloc() each return
15641 ** a pointer to a static preexisting mutex.  Three static mutexes are
15642 ** used by the current version of SQLite.  Future versions of SQLite
15643 ** may add additional static mutexes.  Static mutexes are for internal
15644 ** use by SQLite only.  Applications that use SQLite mutexes should
15645 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
15646 ** SQLITE_MUTEX_RECURSIVE.
15647 **
15648 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
15649 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
15650 ** returns a different mutex on every call.  But for the static
15651 ** mutex types, the same mutex is returned on every call that has
15652 ** the same type number.
15653 */
15654 static sqlite3_mutex *os2MutexAlloc(int iType){
15655   sqlite3_mutex *p = NULL;
15656   switch( iType ){
15657     case SQLITE_MUTEX_FAST:
15658     case SQLITE_MUTEX_RECURSIVE: {
15659       p = sqlite3MallocZero( sizeof(*p) );
15660       if( p ){
15661         p->id = iType;
15662         if( DosCreateMutexSem( 0, &p->mutex, 0, FALSE ) != NO_ERROR ){
15663           sqlite3_free( p );
15664           p = NULL;
15665         }
15666       }
15667       break;
15668     }
15669     default: {
15670       static volatile int isInit = 0;
15671       static sqlite3_mutex staticMutexes[] = {
15672         { OS2_MUTEX_INITIALIZER, },
15673         { OS2_MUTEX_INITIALIZER, },
15674         { OS2_MUTEX_INITIALIZER, },
15675         { OS2_MUTEX_INITIALIZER, },
15676         { OS2_MUTEX_INITIALIZER, },
15677         { OS2_MUTEX_INITIALIZER, },
15678       };
15679       if ( !isInit ){
15680         APIRET rc;
15681         PTIB ptib;
15682         PPIB ppib;
15683         HMTX mutex;
15684         char name[32];
15685         DosGetInfoBlocks( &ptib, &ppib );
15686         sqlite3_snprintf( sizeof(name), name, "\\SEM32\\SQLITE%04x",
15687                           ppib->pib_ulpid );
15688         while( !isInit ){
15689           mutex = 0;
15690           rc = DosCreateMutexSem( name, &mutex, 0, FALSE);
15691           if( rc == NO_ERROR ){
15692             unsigned int i;
15693             if( !isInit ){
15694               for( i = 0; i < sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++ ){
15695                 DosCreateMutexSem( 0, &staticMutexes[i].mutex, 0, FALSE );
15696               }
15697               isInit = 1;
15698             }
15699             DosCloseMutexSem( mutex );
15700           }else if( rc == ERROR_DUPLICATE_NAME ){
15701             DosSleep( 1 );
15702           }else{
15703             return p;
15704           }
15705         }
15706       }
15707       assert( iType-2 >= 0 );
15708       assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
15709       p = &staticMutexes[iType-2];
15710       p->id = iType;
15711       break;
15712     }
15713   }
15714   return p;
15715 }
15716
15717
15718 /*
15719 ** This routine deallocates a previously allocated mutex.
15720 ** SQLite is careful to deallocate every mutex that it allocates.
15721 */
15722 static void os2MutexFree(sqlite3_mutex *p){
15723   if( p==0 ) return;
15724   assert( p->nRef==0 );
15725   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
15726   DosCloseMutexSem( p->mutex );
15727   sqlite3_free( p );
15728 }
15729
15730 #ifdef SQLITE_DEBUG
15731 /*
15732 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
15733 ** intended for use inside assert() statements.
15734 */
15735 static int os2MutexHeld(sqlite3_mutex *p){
15736   TID tid;
15737   PID pid;
15738   ULONG ulCount;
15739   PTIB ptib;
15740   if( p!=0 ) {
15741     DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
15742   } else {
15743     DosGetInfoBlocks(&ptib, NULL);
15744     tid = ptib->tib_ptib2->tib2_ultid;
15745   }
15746   return p==0 || (p->nRef!=0 && p->owner==tid);
15747 }
15748 static int os2MutexNotheld(sqlite3_mutex *p){
15749   TID tid;
15750   PID pid;
15751   ULONG ulCount;
15752   PTIB ptib;
15753   if( p!= 0 ) {
15754     DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
15755   } else {
15756     DosGetInfoBlocks(&ptib, NULL);
15757     tid = ptib->tib_ptib2->tib2_ultid;
15758   }
15759   return p==0 || p->nRef==0 || p->owner!=tid;
15760 }
15761 #endif
15762
15763 /*
15764 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
15765 ** to enter a mutex.  If another thread is already within the mutex,
15766 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
15767 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
15768 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
15769 ** be entered multiple times by the same thread.  In such cases the,
15770 ** mutex must be exited an equal number of times before another thread
15771 ** can enter.  If the same thread tries to enter any other kind of mutex
15772 ** more than once, the behavior is undefined.
15773 */
15774 static void os2MutexEnter(sqlite3_mutex *p){
15775   TID tid;
15776   PID holder1;
15777   ULONG holder2;
15778   if( p==0 ) return;
15779   assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
15780   DosRequestMutexSem(p->mutex, SEM_INDEFINITE_WAIT);
15781   DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
15782   p->owner = tid;
15783   p->nRef++;
15784 }
15785 static int os2MutexTry(sqlite3_mutex *p){
15786   int rc;
15787   TID tid;
15788   PID holder1;
15789   ULONG holder2;
15790   if( p==0 ) return SQLITE_OK;
15791   assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
15792   if( DosRequestMutexSem(p->mutex, SEM_IMMEDIATE_RETURN) == NO_ERROR) {
15793     DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
15794     p->owner = tid;
15795     p->nRef++;
15796     rc = SQLITE_OK;
15797   } else {
15798     rc = SQLITE_BUSY;
15799   }
15800
15801   return rc;
15802 }
15803
15804 /*
15805 ** The sqlite3_mutex_leave() routine exits a mutex that was
15806 ** previously entered by the same thread.  The behavior
15807 ** is undefined if the mutex is not currently entered or
15808 ** is not currently allocated.  SQLite will never do either.
15809 */
15810 static void os2MutexLeave(sqlite3_mutex *p){
15811   TID tid;
15812   PID holder1;
15813   ULONG holder2;
15814   if( p==0 ) return;
15815   assert( p->nRef>0 );
15816   DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
15817   assert( p->owner==tid );
15818   p->nRef--;
15819   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
15820   DosReleaseMutexSem(p->mutex);
15821 }
15822
15823 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
15824   static const sqlite3_mutex_methods sMutex = {
15825     os2MutexInit,
15826     os2MutexEnd,
15827     os2MutexAlloc,
15828     os2MutexFree,
15829     os2MutexEnter,
15830     os2MutexTry,
15831     os2MutexLeave,
15832 #ifdef SQLITE_DEBUG
15833     os2MutexHeld,
15834     os2MutexNotheld
15835 #endif
15836   };
15837
15838   return &sMutex;
15839 }
15840 #endif /* SQLITE_MUTEX_OS2 */
15841
15842 /************** End of mutex_os2.c *******************************************/
15843 /************** Begin file mutex_unix.c **************************************/
15844 /*
15845 ** 2007 August 28
15846 **
15847 ** The author disclaims copyright to this source code.  In place of
15848 ** a legal notice, here is a blessing:
15849 **
15850 **    May you do good and not evil.
15851 **    May you find forgiveness for yourself and forgive others.
15852 **    May you share freely, never taking more than you give.
15853 **
15854 *************************************************************************
15855 ** This file contains the C functions that implement mutexes for pthreads
15856 */
15857
15858 /*
15859 ** The code in this file is only used if we are compiling threadsafe
15860 ** under unix with pthreads.
15861 **
15862 ** Note that this implementation requires a version of pthreads that
15863 ** supports recursive mutexes.
15864 */
15865 #ifdef SQLITE_MUTEX_PTHREADS
15866
15867 #include <pthread.h>
15868
15869 /*
15870 ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
15871 ** are necessary under two condidtions:  (1) Debug builds and (2) using
15872 ** home-grown mutexes.  Encapsulate these conditions into a single #define.
15873 */
15874 #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
15875 # define SQLITE_MUTEX_NREF 1
15876 #else
15877 # define SQLITE_MUTEX_NREF 0
15878 #endif
15879
15880 /*
15881 ** Each recursive mutex is an instance of the following structure.
15882 */
15883 struct sqlite3_mutex {
15884   pthread_mutex_t mutex;     /* Mutex controlling the lock */
15885 #if SQLITE_MUTEX_NREF
15886   int id;                    /* Mutex type */
15887   volatile int nRef;         /* Number of entrances */
15888   volatile pthread_t owner;  /* Thread that is within this mutex */
15889   int trace;                 /* True to trace changes */
15890 #endif
15891 };
15892 #if SQLITE_MUTEX_NREF
15893 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
15894 #else
15895 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
15896 #endif
15897
15898 /*
15899 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
15900 ** intended for use only inside assert() statements.  On some platforms,
15901 ** there might be race conditions that can cause these routines to
15902 ** deliver incorrect results.  In particular, if pthread_equal() is
15903 ** not an atomic operation, then these routines might delivery
15904 ** incorrect results.  On most platforms, pthread_equal() is a 
15905 ** comparison of two integers and is therefore atomic.  But we are
15906 ** told that HPUX is not such a platform.  If so, then these routines
15907 ** will not always work correctly on HPUX.
15908 **
15909 ** On those platforms where pthread_equal() is not atomic, SQLite
15910 ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
15911 ** make sure no assert() statements are evaluated and hence these
15912 ** routines are never called.
15913 */
15914 #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
15915 static int pthreadMutexHeld(sqlite3_mutex *p){
15916   return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
15917 }
15918 static int pthreadMutexNotheld(sqlite3_mutex *p){
15919   return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
15920 }
15921 #endif
15922
15923 /*
15924 ** Initialize and deinitialize the mutex subsystem.
15925 */
15926 static int pthreadMutexInit(void){ return SQLITE_OK; }
15927 static int pthreadMutexEnd(void){ return SQLITE_OK; }
15928
15929 /*
15930 ** The sqlite3_mutex_alloc() routine allocates a new
15931 ** mutex and returns a pointer to it.  If it returns NULL
15932 ** that means that a mutex could not be allocated.  SQLite
15933 ** will unwind its stack and return an error.  The argument
15934 ** to sqlite3_mutex_alloc() is one of these integer constants:
15935 **
15936 ** <ul>
15937 ** <li>  SQLITE_MUTEX_FAST
15938 ** <li>  SQLITE_MUTEX_RECURSIVE
15939 ** <li>  SQLITE_MUTEX_STATIC_MASTER
15940 ** <li>  SQLITE_MUTEX_STATIC_MEM
15941 ** <li>  SQLITE_MUTEX_STATIC_MEM2
15942 ** <li>  SQLITE_MUTEX_STATIC_PRNG
15943 ** <li>  SQLITE_MUTEX_STATIC_LRU
15944 ** <li>  SQLITE_MUTEX_STATIC_LRU2
15945 ** </ul>
15946 **
15947 ** The first two constants cause sqlite3_mutex_alloc() to create
15948 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
15949 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
15950 ** The mutex implementation does not need to make a distinction
15951 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
15952 ** not want to.  But SQLite will only request a recursive mutex in
15953 ** cases where it really needs one.  If a faster non-recursive mutex
15954 ** implementation is available on the host platform, the mutex subsystem
15955 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
15956 **
15957 ** The other allowed parameters to sqlite3_mutex_alloc() each return
15958 ** a pointer to a static preexisting mutex.  Six static mutexes are
15959 ** used by the current version of SQLite.  Future versions of SQLite
15960 ** may add additional static mutexes.  Static mutexes are for internal
15961 ** use by SQLite only.  Applications that use SQLite mutexes should
15962 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
15963 ** SQLITE_MUTEX_RECURSIVE.
15964 **
15965 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
15966 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
15967 ** returns a different mutex on every call.  But for the static 
15968 ** mutex types, the same mutex is returned on every call that has
15969 ** the same type number.
15970 */
15971 static sqlite3_mutex *pthreadMutexAlloc(int iType){
15972   static sqlite3_mutex staticMutexes[] = {
15973     SQLITE3_MUTEX_INITIALIZER,
15974     SQLITE3_MUTEX_INITIALIZER,
15975     SQLITE3_MUTEX_INITIALIZER,
15976     SQLITE3_MUTEX_INITIALIZER,
15977     SQLITE3_MUTEX_INITIALIZER,
15978     SQLITE3_MUTEX_INITIALIZER
15979   };
15980   sqlite3_mutex *p;
15981   switch( iType ){
15982     case SQLITE_MUTEX_RECURSIVE: {
15983       p = sqlite3MallocZero( sizeof(*p) );
15984       if( p ){
15985 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
15986         /* If recursive mutexes are not available, we will have to
15987         ** build our own.  See below. */
15988         pthread_mutex_init(&p->mutex, 0);
15989 #else
15990         /* Use a recursive mutex if it is available */
15991         pthread_mutexattr_t recursiveAttr;
15992         pthread_mutexattr_init(&recursiveAttr);
15993         pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
15994         pthread_mutex_init(&p->mutex, &recursiveAttr);
15995         pthread_mutexattr_destroy(&recursiveAttr);
15996 #endif
15997 #if SQLITE_MUTEX_NREF
15998         p->id = iType;
15999 #endif
16000       }
16001       break;
16002     }
16003     case SQLITE_MUTEX_FAST: {
16004       p = sqlite3MallocZero( sizeof(*p) );
16005       if( p ){
16006 #if SQLITE_MUTEX_NREF
16007         p->id = iType;
16008 #endif
16009         pthread_mutex_init(&p->mutex, 0);
16010       }
16011       break;
16012     }
16013     default: {
16014       assert( iType-2 >= 0 );
16015       assert( iType-2 < ArraySize(staticMutexes) );
16016       p = &staticMutexes[iType-2];
16017 #if SQLITE_MUTEX_NREF
16018       p->id = iType;
16019 #endif
16020       break;
16021     }
16022   }
16023   return p;
16024 }
16025
16026
16027 /*
16028 ** This routine deallocates a previously
16029 ** allocated mutex.  SQLite is careful to deallocate every
16030 ** mutex that it allocates.
16031 */
16032 static void pthreadMutexFree(sqlite3_mutex *p){
16033   assert( p->nRef==0 );
16034   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
16035   pthread_mutex_destroy(&p->mutex);
16036   sqlite3_free(p);
16037 }
16038
16039 /*
16040 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
16041 ** to enter a mutex.  If another thread is already within the mutex,
16042 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
16043 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
16044 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
16045 ** be entered multiple times by the same thread.  In such cases the,
16046 ** mutex must be exited an equal number of times before another thread
16047 ** can enter.  If the same thread tries to enter any other kind of mutex
16048 ** more than once, the behavior is undefined.
16049 */
16050 static void pthreadMutexEnter(sqlite3_mutex *p){
16051   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
16052
16053 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
16054   /* If recursive mutexes are not available, then we have to grow
16055   ** our own.  This implementation assumes that pthread_equal()
16056   ** is atomic - that it cannot be deceived into thinking self
16057   ** and p->owner are equal if p->owner changes between two values
16058   ** that are not equal to self while the comparison is taking place.
16059   ** This implementation also assumes a coherent cache - that 
16060   ** separate processes cannot read different values from the same
16061   ** address at the same time.  If either of these two conditions
16062   ** are not met, then the mutexes will fail and problems will result.
16063   */
16064   {
16065     pthread_t self = pthread_self();
16066     if( p->nRef>0 && pthread_equal(p->owner, self) ){
16067       p->nRef++;
16068     }else{
16069       pthread_mutex_lock(&p->mutex);
16070       assert( p->nRef==0 );
16071       p->owner = self;
16072       p->nRef = 1;
16073     }
16074   }
16075 #else
16076   /* Use the built-in recursive mutexes if they are available.
16077   */
16078   pthread_mutex_lock(&p->mutex);
16079 #if SQLITE_MUTEX_NREF
16080   p->owner = pthread_self();
16081   p->nRef++;
16082 #endif
16083 #endif
16084
16085 #ifdef SQLITE_DEBUG
16086   if( p->trace ){
16087     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
16088   }
16089 #endif
16090 }
16091 static int pthreadMutexTry(sqlite3_mutex *p){
16092   int rc;
16093   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
16094
16095 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
16096   /* If recursive mutexes are not available, then we have to grow
16097   ** our own.  This implementation assumes that pthread_equal()
16098   ** is atomic - that it cannot be deceived into thinking self
16099   ** and p->owner are equal if p->owner changes between two values
16100   ** that are not equal to self while the comparison is taking place.
16101   ** This implementation also assumes a coherent cache - that 
16102   ** separate processes cannot read different values from the same
16103   ** address at the same time.  If either of these two conditions
16104   ** are not met, then the mutexes will fail and problems will result.
16105   */
16106   {
16107     pthread_t self = pthread_self();
16108     if( p->nRef>0 && pthread_equal(p->owner, self) ){
16109       p->nRef++;
16110       rc = SQLITE_OK;
16111     }else if( pthread_mutex_trylock(&p->mutex)==0 ){
16112       assert( p->nRef==0 );
16113       p->owner = self;
16114       p->nRef = 1;
16115       rc = SQLITE_OK;
16116     }else{
16117       rc = SQLITE_BUSY;
16118     }
16119   }
16120 #else
16121   /* Use the built-in recursive mutexes if they are available.
16122   */
16123   if( pthread_mutex_trylock(&p->mutex)==0 ){
16124 #if SQLITE_MUTEX_NREF
16125     p->owner = pthread_self();
16126     p->nRef++;
16127 #endif
16128     rc = SQLITE_OK;
16129   }else{
16130     rc = SQLITE_BUSY;
16131   }
16132 #endif
16133
16134 #ifdef SQLITE_DEBUG
16135   if( rc==SQLITE_OK && p->trace ){
16136     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
16137   }
16138 #endif
16139   return rc;
16140 }
16141
16142 /*
16143 ** The sqlite3_mutex_leave() routine exits a mutex that was
16144 ** previously entered by the same thread.  The behavior
16145 ** is undefined if the mutex is not currently entered or
16146 ** is not currently allocated.  SQLite will never do either.
16147 */
16148 static void pthreadMutexLeave(sqlite3_mutex *p){
16149   assert( pthreadMutexHeld(p) );
16150 #if SQLITE_MUTEX_NREF
16151   p->nRef--;
16152 #endif
16153   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
16154
16155 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
16156   if( p->nRef==0 ){
16157     pthread_mutex_unlock(&p->mutex);
16158   }
16159 #else
16160   pthread_mutex_unlock(&p->mutex);
16161 #endif
16162
16163 #ifdef SQLITE_DEBUG
16164   if( p->trace ){
16165     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
16166   }
16167 #endif
16168 }
16169
16170 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
16171   static const sqlite3_mutex_methods sMutex = {
16172     pthreadMutexInit,
16173     pthreadMutexEnd,
16174     pthreadMutexAlloc,
16175     pthreadMutexFree,
16176     pthreadMutexEnter,
16177     pthreadMutexTry,
16178     pthreadMutexLeave,
16179 #ifdef SQLITE_DEBUG
16180     pthreadMutexHeld,
16181     pthreadMutexNotheld
16182 #else
16183     0,
16184     0
16185 #endif
16186   };
16187
16188   return &sMutex;
16189 }
16190
16191 #endif /* SQLITE_MUTEX_PTHREAD */
16192
16193 /************** End of mutex_unix.c ******************************************/
16194 /************** Begin file mutex_w32.c ***************************************/
16195 /*
16196 ** 2007 August 14
16197 **
16198 ** The author disclaims copyright to this source code.  In place of
16199 ** a legal notice, here is a blessing:
16200 **
16201 **    May you do good and not evil.
16202 **    May you find forgiveness for yourself and forgive others.
16203 **    May you share freely, never taking more than you give.
16204 **
16205 *************************************************************************
16206 ** This file contains the C functions that implement mutexes for win32
16207 */
16208
16209 /*
16210 ** The code in this file is only used if we are compiling multithreaded
16211 ** on a win32 system.
16212 */
16213 #ifdef SQLITE_MUTEX_W32
16214
16215 /*
16216 ** Each recursive mutex is an instance of the following structure.
16217 */
16218 struct sqlite3_mutex {
16219   CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
16220   int id;                    /* Mutex type */
16221 #ifdef SQLITE_DEBUG
16222   volatile int nRef;         /* Number of enterances */
16223   volatile DWORD owner;      /* Thread holding this mutex */
16224   int trace;                 /* True to trace changes */
16225 #endif
16226 };
16227 #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
16228 #ifdef SQLITE_DEBUG
16229 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0, 0 }
16230 #else
16231 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
16232 #endif
16233
16234 /*
16235 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
16236 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
16237 **
16238 ** Here is an interesting observation:  Win95, Win98, and WinME lack
16239 ** the LockFileEx() API.  But we can still statically link against that
16240 ** API as long as we don't call it win running Win95/98/ME.  A call to
16241 ** this routine is used to determine if the host is Win95/98/ME or
16242 ** WinNT/2K/XP so that we will know whether or not we can safely call
16243 ** the LockFileEx() API.
16244 **
16245 ** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
16246 ** which is only available if your application was compiled with 
16247 ** _WIN32_WINNT defined to a value >= 0x0400.  Currently, the only
16248 ** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef 
16249 ** this out as well.
16250 */
16251 #if 0
16252 #if SQLITE_OS_WINCE
16253 # define mutexIsNT()  (1)
16254 #else
16255   static int mutexIsNT(void){
16256     static int osType = 0;
16257     if( osType==0 ){
16258       OSVERSIONINFO sInfo;
16259       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
16260       GetVersionEx(&sInfo);
16261       osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
16262     }
16263     return osType==2;
16264   }
16265 #endif /* SQLITE_OS_WINCE */
16266 #endif
16267
16268 #ifdef SQLITE_DEBUG
16269 /*
16270 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
16271 ** intended for use only inside assert() statements.
16272 */
16273 static int winMutexHeld(sqlite3_mutex *p){
16274   return p->nRef!=0 && p->owner==GetCurrentThreadId();
16275 }
16276 static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
16277   return p->nRef==0 || p->owner!=tid;
16278 }
16279 static int winMutexNotheld(sqlite3_mutex *p){
16280   DWORD tid = GetCurrentThreadId(); 
16281   return winMutexNotheld2(p, tid);
16282 }
16283 #endif
16284
16285
16286 /*
16287 ** Initialize and deinitialize the mutex subsystem.
16288 */
16289 static sqlite3_mutex winMutex_staticMutexes[6] = {
16290   SQLITE3_MUTEX_INITIALIZER,
16291   SQLITE3_MUTEX_INITIALIZER,
16292   SQLITE3_MUTEX_INITIALIZER,
16293   SQLITE3_MUTEX_INITIALIZER,
16294   SQLITE3_MUTEX_INITIALIZER,
16295   SQLITE3_MUTEX_INITIALIZER
16296 };
16297 static int winMutex_isInit = 0;
16298 /* As winMutexInit() and winMutexEnd() are called as part
16299 ** of the sqlite3_initialize and sqlite3_shutdown()
16300 ** processing, the "interlocked" magic is probably not
16301 ** strictly necessary.
16302 */
16303 static long winMutex_lock = 0;
16304
16305 static int winMutexInit(void){ 
16306   /* The first to increment to 1 does actual initialization */
16307   if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
16308     int i;
16309     for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
16310       InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
16311     }
16312     winMutex_isInit = 1;
16313   }else{
16314     /* Someone else is in the process of initing the static mutexes */
16315     while( !winMutex_isInit ){
16316       Sleep(1);
16317     }
16318   }
16319   return SQLITE_OK; 
16320 }
16321
16322 static int winMutexEnd(void){ 
16323   /* The first to decrement to 0 does actual shutdown 
16324   ** (which should be the last to shutdown.) */
16325   if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
16326     if( winMutex_isInit==1 ){
16327       int i;
16328       for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
16329         DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
16330       }
16331       winMutex_isInit = 0;
16332     }
16333   }
16334   return SQLITE_OK; 
16335 }
16336
16337 /*
16338 ** The sqlite3_mutex_alloc() routine allocates a new
16339 ** mutex and returns a pointer to it.  If it returns NULL
16340 ** that means that a mutex could not be allocated.  SQLite
16341 ** will unwind its stack and return an error.  The argument
16342 ** to sqlite3_mutex_alloc() is one of these integer constants:
16343 **
16344 ** <ul>
16345 ** <li>  SQLITE_MUTEX_FAST
16346 ** <li>  SQLITE_MUTEX_RECURSIVE
16347 ** <li>  SQLITE_MUTEX_STATIC_MASTER
16348 ** <li>  SQLITE_MUTEX_STATIC_MEM
16349 ** <li>  SQLITE_MUTEX_STATIC_MEM2
16350 ** <li>  SQLITE_MUTEX_STATIC_PRNG
16351 ** <li>  SQLITE_MUTEX_STATIC_LRU
16352 ** <li>  SQLITE_MUTEX_STATIC_LRU2
16353 ** </ul>
16354 **
16355 ** The first two constants cause sqlite3_mutex_alloc() to create
16356 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
16357 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
16358 ** The mutex implementation does not need to make a distinction
16359 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
16360 ** not want to.  But SQLite will only request a recursive mutex in
16361 ** cases where it really needs one.  If a faster non-recursive mutex
16362 ** implementation is available on the host platform, the mutex subsystem
16363 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
16364 **
16365 ** The other allowed parameters to sqlite3_mutex_alloc() each return
16366 ** a pointer to a static preexisting mutex.  Six static mutexes are
16367 ** used by the current version of SQLite.  Future versions of SQLite
16368 ** may add additional static mutexes.  Static mutexes are for internal
16369 ** use by SQLite only.  Applications that use SQLite mutexes should
16370 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
16371 ** SQLITE_MUTEX_RECURSIVE.
16372 **
16373 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
16374 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
16375 ** returns a different mutex on every call.  But for the static 
16376 ** mutex types, the same mutex is returned on every call that has
16377 ** the same type number.
16378 */
16379 static sqlite3_mutex *winMutexAlloc(int iType){
16380   sqlite3_mutex *p;
16381
16382   switch( iType ){
16383     case SQLITE_MUTEX_FAST:
16384     case SQLITE_MUTEX_RECURSIVE: {
16385       p = sqlite3MallocZero( sizeof(*p) );
16386       if( p ){  
16387 #ifdef SQLITE_DEBUG
16388         p->id = iType;
16389 #endif
16390         InitializeCriticalSection(&p->mutex);
16391       }
16392       break;
16393     }
16394     default: {
16395       assert( winMutex_isInit==1 );
16396       assert( iType-2 >= 0 );
16397       assert( iType-2 < ArraySize(winMutex_staticMutexes) );
16398       p = &winMutex_staticMutexes[iType-2];
16399 #ifdef SQLITE_DEBUG
16400       p->id = iType;
16401 #endif
16402       break;
16403     }
16404   }
16405   return p;
16406 }
16407
16408
16409 /*
16410 ** This routine deallocates a previously
16411 ** allocated mutex.  SQLite is careful to deallocate every
16412 ** mutex that it allocates.
16413 */
16414 static void winMutexFree(sqlite3_mutex *p){
16415   assert( p );
16416   assert( p->nRef==0 );
16417   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
16418   DeleteCriticalSection(&p->mutex);
16419   sqlite3_free(p);
16420 }
16421
16422 /*
16423 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
16424 ** to enter a mutex.  If another thread is already within the mutex,
16425 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
16426 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
16427 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
16428 ** be entered multiple times by the same thread.  In such cases the,
16429 ** mutex must be exited an equal number of times before another thread
16430 ** can enter.  If the same thread tries to enter any other kind of mutex
16431 ** more than once, the behavior is undefined.
16432 */
16433 static void winMutexEnter(sqlite3_mutex *p){
16434 #ifdef SQLITE_DEBUG
16435   DWORD tid = GetCurrentThreadId(); 
16436   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
16437 #endif
16438   EnterCriticalSection(&p->mutex);
16439 #ifdef SQLITE_DEBUG
16440   p->owner = tid; 
16441   p->nRef++;
16442   if( p->trace ){
16443     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
16444   }
16445 #endif
16446 }
16447 static int winMutexTry(sqlite3_mutex *p){
16448 #ifndef NDEBUG
16449   DWORD tid = GetCurrentThreadId(); 
16450 #endif
16451   int rc = SQLITE_BUSY;
16452   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
16453   /*
16454   ** The sqlite3_mutex_try() routine is very rarely used, and when it
16455   ** is used it is merely an optimization.  So it is OK for it to always
16456   ** fail.  
16457   **
16458   ** The TryEnterCriticalSection() interface is only available on WinNT.
16459   ** And some windows compilers complain if you try to use it without
16460   ** first doing some #defines that prevent SQLite from building on Win98.
16461   ** For that reason, we will omit this optimization for now.  See
16462   ** ticket #2685.
16463   */
16464 #if 0
16465   if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
16466     p->owner = tid;
16467     p->nRef++;
16468     rc = SQLITE_OK;
16469   }
16470 #else
16471   UNUSED_PARAMETER(p);
16472 #endif
16473 #ifdef SQLITE_DEBUG
16474   if( rc==SQLITE_OK && p->trace ){
16475     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
16476   }
16477 #endif
16478   return rc;
16479 }
16480
16481 /*
16482 ** The sqlite3_mutex_leave() routine exits a mutex that was
16483 ** previously entered by the same thread.  The behavior
16484 ** is undefined if the mutex is not currently entered or
16485 ** is not currently allocated.  SQLite will never do either.
16486 */
16487 static void winMutexLeave(sqlite3_mutex *p){
16488 #ifndef NDEBUG
16489   DWORD tid = GetCurrentThreadId();
16490   assert( p->nRef>0 );
16491   assert( p->owner==tid );
16492   p->nRef--;
16493   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
16494 #endif
16495   LeaveCriticalSection(&p->mutex);
16496 #ifdef SQLITE_DEBUG
16497   if( p->trace ){
16498     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
16499   }
16500 #endif
16501 }
16502
16503 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
16504   static const sqlite3_mutex_methods sMutex = {
16505     winMutexInit,
16506     winMutexEnd,
16507     winMutexAlloc,
16508     winMutexFree,
16509     winMutexEnter,
16510     winMutexTry,
16511     winMutexLeave,
16512 #ifdef SQLITE_DEBUG
16513     winMutexHeld,
16514     winMutexNotheld
16515 #else
16516     0,
16517     0
16518 #endif
16519   };
16520
16521   return &sMutex;
16522 }
16523 #endif /* SQLITE_MUTEX_W32 */
16524
16525 /************** End of mutex_w32.c *******************************************/
16526 /************** Begin file malloc.c ******************************************/
16527 /*
16528 ** 2001 September 15
16529 **
16530 ** The author disclaims copyright to this source code.  In place of
16531 ** a legal notice, here is a blessing:
16532 **
16533 **    May you do good and not evil.
16534 **    May you find forgiveness for yourself and forgive others.
16535 **    May you share freely, never taking more than you give.
16536 **
16537 *************************************************************************
16538 **
16539 ** Memory allocation functions used throughout sqlite.
16540 */
16541
16542 /*
16543 ** This routine runs when the memory allocator sees that the
16544 ** total memory allocation is about to exceed the soft heap
16545 ** limit.
16546 */
16547 static void softHeapLimitEnforcer(
16548   void *NotUsed, 
16549   sqlite3_int64 NotUsed2,
16550   int allocSize
16551 ){
16552   UNUSED_PARAMETER2(NotUsed, NotUsed2);
16553   sqlite3_release_memory(allocSize);
16554 }
16555
16556 /*
16557 ** Set the soft heap-size limit for the library. Passing a zero or 
16558 ** negative value indicates no limit.
16559 */
16560 SQLITE_API void sqlite3_soft_heap_limit(int n){
16561   sqlite3_uint64 iLimit;
16562   int overage;
16563   if( n<0 ){
16564     iLimit = 0;
16565   }else{
16566     iLimit = n;
16567   }
16568 #ifndef SQLITE_OMIT_AUTOINIT
16569   sqlite3_initialize();
16570 #endif
16571   if( iLimit>0 ){
16572     sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, iLimit);
16573   }else{
16574     sqlite3MemoryAlarm(0, 0, 0);
16575   }
16576   overage = (int)(sqlite3_memory_used() - (i64)n);
16577   if( overage>0 ){
16578     sqlite3_release_memory(overage);
16579   }
16580 }
16581
16582 /*
16583 ** Attempt to release up to n bytes of non-essential memory currently
16584 ** held by SQLite. An example of non-essential memory is memory used to
16585 ** cache database pages that are not currently in use.
16586 */
16587 SQLITE_API int sqlite3_release_memory(int n){
16588 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
16589   int nRet = 0;
16590   nRet += sqlite3PcacheReleaseMemory(n-nRet);
16591   return nRet;
16592 #else
16593   UNUSED_PARAMETER(n);
16594   return SQLITE_OK;
16595 #endif
16596 }
16597
16598 /*
16599 ** State information local to the memory allocation subsystem.
16600 */
16601 static SQLITE_WSD struct Mem0Global {
16602   /* Number of free pages for scratch and page-cache memory */
16603   u32 nScratchFree;
16604   u32 nPageFree;
16605
16606   sqlite3_mutex *mutex;         /* Mutex to serialize access */
16607
16608   /*
16609   ** The alarm callback and its arguments.  The mem0.mutex lock will
16610   ** be held while the callback is running.  Recursive calls into
16611   ** the memory subsystem are allowed, but no new callbacks will be
16612   ** issued.
16613   */
16614   sqlite3_int64 alarmThreshold;
16615   void (*alarmCallback)(void*, sqlite3_int64,int);
16616   void *alarmArg;
16617
16618   /*
16619   ** Pointers to the end of sqlite3GlobalConfig.pScratch and
16620   ** sqlite3GlobalConfig.pPage to a block of memory that records
16621   ** which pages are available.
16622   */
16623   u32 *aScratchFree;
16624   u32 *aPageFree;
16625 } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
16626
16627 #define mem0 GLOBAL(struct Mem0Global, mem0)
16628
16629 /*
16630 ** Initialize the memory allocation subsystem.
16631 */
16632 SQLITE_PRIVATE int sqlite3MallocInit(void){
16633   if( sqlite3GlobalConfig.m.xMalloc==0 ){
16634     sqlite3MemSetDefault();
16635   }
16636   memset(&mem0, 0, sizeof(mem0));
16637   if( sqlite3GlobalConfig.bCoreMutex ){
16638     mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
16639   }
16640   if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
16641       && sqlite3GlobalConfig.nScratch>=0 ){
16642     int i;
16643     sqlite3GlobalConfig.szScratch = ROUNDDOWN8(sqlite3GlobalConfig.szScratch-4);
16644     mem0.aScratchFree = (u32*)&((char*)sqlite3GlobalConfig.pScratch)
16645                   [sqlite3GlobalConfig.szScratch*sqlite3GlobalConfig.nScratch];
16646     for(i=0; i<sqlite3GlobalConfig.nScratch; i++){ mem0.aScratchFree[i] = i; }
16647     mem0.nScratchFree = sqlite3GlobalConfig.nScratch;
16648   }else{
16649     sqlite3GlobalConfig.pScratch = 0;
16650     sqlite3GlobalConfig.szScratch = 0;
16651   }
16652   if( sqlite3GlobalConfig.pPage && sqlite3GlobalConfig.szPage>=512
16653       && sqlite3GlobalConfig.nPage>=1 ){
16654     int i;
16655     int overhead;
16656     int sz = ROUNDDOWN8(sqlite3GlobalConfig.szPage);
16657     int n = sqlite3GlobalConfig.nPage;
16658     overhead = (4*n + sz - 1)/sz;
16659     sqlite3GlobalConfig.nPage -= overhead;
16660     mem0.aPageFree = (u32*)&((char*)sqlite3GlobalConfig.pPage)
16661                   [sqlite3GlobalConfig.szPage*sqlite3GlobalConfig.nPage];
16662     for(i=0; i<sqlite3GlobalConfig.nPage; i++){ mem0.aPageFree[i] = i; }
16663     mem0.nPageFree = sqlite3GlobalConfig.nPage;
16664   }else{
16665     sqlite3GlobalConfig.pPage = 0;
16666     sqlite3GlobalConfig.szPage = 0;
16667   }
16668   return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
16669 }
16670
16671 /*
16672 ** Deinitialize the memory allocation subsystem.
16673 */
16674 SQLITE_PRIVATE void sqlite3MallocEnd(void){
16675   if( sqlite3GlobalConfig.m.xShutdown ){
16676     sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
16677   }
16678   memset(&mem0, 0, sizeof(mem0));
16679 }
16680
16681 /*
16682 ** Return the amount of memory currently checked out.
16683 */
16684 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
16685   int n, mx;
16686   sqlite3_int64 res;
16687   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
16688   res = (sqlite3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
16689   return res;
16690 }
16691
16692 /*
16693 ** Return the maximum amount of memory that has ever been
16694 ** checked out since either the beginning of this process
16695 ** or since the most recent reset.
16696 */
16697 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
16698   int n, mx;
16699   sqlite3_int64 res;
16700   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
16701   res = (sqlite3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
16702   return res;
16703 }
16704
16705 /*
16706 ** Change the alarm callback
16707 */
16708 SQLITE_PRIVATE int sqlite3MemoryAlarm(
16709   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
16710   void *pArg,
16711   sqlite3_int64 iThreshold
16712 ){
16713   sqlite3_mutex_enter(mem0.mutex);
16714   mem0.alarmCallback = xCallback;
16715   mem0.alarmArg = pArg;
16716   mem0.alarmThreshold = iThreshold;
16717   sqlite3_mutex_leave(mem0.mutex);
16718   return SQLITE_OK;
16719 }
16720
16721 #ifndef SQLITE_OMIT_DEPRECATED
16722 /*
16723 ** Deprecated external interface.  Internal/core SQLite code
16724 ** should call sqlite3MemoryAlarm.
16725 */
16726 SQLITE_API int sqlite3_memory_alarm(
16727   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
16728   void *pArg,
16729   sqlite3_int64 iThreshold
16730 ){
16731   return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
16732 }
16733 #endif
16734
16735 /*
16736 ** Trigger the alarm 
16737 */
16738 static void sqlite3MallocAlarm(int nByte){
16739   void (*xCallback)(void*,sqlite3_int64,int);
16740   sqlite3_int64 nowUsed;
16741   void *pArg;
16742   if( mem0.alarmCallback==0 ) return;
16743   xCallback = mem0.alarmCallback;
16744   nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
16745   pArg = mem0.alarmArg;
16746   mem0.alarmCallback = 0;
16747   sqlite3_mutex_leave(mem0.mutex);
16748   xCallback(pArg, nowUsed, nByte);
16749   sqlite3_mutex_enter(mem0.mutex);
16750   mem0.alarmCallback = xCallback;
16751   mem0.alarmArg = pArg;
16752 }
16753
16754 /*
16755 ** Do a memory allocation with statistics and alarms.  Assume the
16756 ** lock is already held.
16757 */
16758 static int mallocWithAlarm(int n, void **pp){
16759   int nFull;
16760   void *p;
16761   assert( sqlite3_mutex_held(mem0.mutex) );
16762   nFull = sqlite3GlobalConfig.m.xRoundup(n);
16763   sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
16764   if( mem0.alarmCallback!=0 ){
16765     int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
16766     if( nUsed+nFull >= mem0.alarmThreshold ){
16767       sqlite3MallocAlarm(nFull);
16768     }
16769   }
16770   p = sqlite3GlobalConfig.m.xMalloc(nFull);
16771   if( p==0 && mem0.alarmCallback ){
16772     sqlite3MallocAlarm(nFull);
16773     p = sqlite3GlobalConfig.m.xMalloc(nFull);
16774   }
16775   if( p ){
16776     nFull = sqlite3MallocSize(p);
16777     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
16778   }
16779   *pp = p;
16780   return nFull;
16781 }
16782
16783 /*
16784 ** Allocate memory.  This routine is like sqlite3_malloc() except that it
16785 ** assumes the memory subsystem has already been initialized.
16786 */
16787 SQLITE_PRIVATE void *sqlite3Malloc(int n){
16788   void *p;
16789   if( n<=0 || n>=0x7fffff00 ){
16790     /* A memory allocation of a number of bytes which is near the maximum
16791     ** signed integer value might cause an integer overflow inside of the
16792     ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
16793     ** 255 bytes of overhead.  SQLite itself will never use anything near
16794     ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
16795     p = 0;
16796   }else if( sqlite3GlobalConfig.bMemstat ){
16797     sqlite3_mutex_enter(mem0.mutex);
16798     mallocWithAlarm(n, &p);
16799     sqlite3_mutex_leave(mem0.mutex);
16800   }else{
16801     p = sqlite3GlobalConfig.m.xMalloc(n);
16802   }
16803   return p;
16804 }
16805
16806 /*
16807 ** This version of the memory allocation is for use by the application.
16808 ** First make sure the memory subsystem is initialized, then do the
16809 ** allocation.
16810 */
16811 SQLITE_API void *sqlite3_malloc(int n){
16812 #ifndef SQLITE_OMIT_AUTOINIT
16813   if( sqlite3_initialize() ) return 0;
16814 #endif
16815   return sqlite3Malloc(n);
16816 }
16817
16818 /*
16819 ** Each thread may only have a single outstanding allocation from
16820 ** xScratchMalloc().  We verify this constraint in the single-threaded
16821 ** case by setting scratchAllocOut to 1 when an allocation
16822 ** is outstanding clearing it when the allocation is freed.
16823 */
16824 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
16825 static int scratchAllocOut = 0;
16826 #endif
16827
16828
16829 /*
16830 ** Allocate memory that is to be used and released right away.
16831 ** This routine is similar to alloca() in that it is not intended
16832 ** for situations where the memory might be held long-term.  This
16833 ** routine is intended to get memory to old large transient data
16834 ** structures that would not normally fit on the stack of an
16835 ** embedded processor.
16836 */
16837 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
16838   void *p;
16839   assert( n>0 );
16840
16841 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
16842   /* Verify that no more than two scratch allocation per thread
16843   ** is outstanding at one time.  (This is only checked in the
16844   ** single-threaded case since checking in the multi-threaded case
16845   ** would be much more complicated.) */
16846   assert( scratchAllocOut<=1 );
16847 #endif
16848
16849   if( sqlite3GlobalConfig.szScratch<n ){
16850     goto scratch_overflow;
16851   }else{  
16852     sqlite3_mutex_enter(mem0.mutex);
16853     if( mem0.nScratchFree==0 ){
16854       sqlite3_mutex_leave(mem0.mutex);
16855       goto scratch_overflow;
16856     }else{
16857       int i;
16858       i = mem0.aScratchFree[--mem0.nScratchFree];
16859       i *= sqlite3GlobalConfig.szScratch;
16860       sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
16861       sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
16862       sqlite3_mutex_leave(mem0.mutex);
16863       p = (void*)&((char*)sqlite3GlobalConfig.pScratch)[i];
16864       assert(  (((u8*)p - (u8*)0) & 7)==0 );
16865     }
16866   }
16867 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
16868   scratchAllocOut = p!=0;
16869 #endif
16870
16871   return p;
16872
16873 scratch_overflow:
16874   if( sqlite3GlobalConfig.bMemstat ){
16875     sqlite3_mutex_enter(mem0.mutex);
16876     sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
16877     n = mallocWithAlarm(n, &p);
16878     if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
16879     sqlite3_mutex_leave(mem0.mutex);
16880   }else{
16881     p = sqlite3GlobalConfig.m.xMalloc(n);
16882   }
16883   sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
16884 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
16885   scratchAllocOut = p!=0;
16886 #endif
16887   return p;    
16888 }
16889 SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
16890   if( p ){
16891     if( sqlite3GlobalConfig.pScratch==0
16892            || p<sqlite3GlobalConfig.pScratch
16893            || p>=(void*)mem0.aScratchFree ){
16894       assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
16895       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
16896       if( sqlite3GlobalConfig.bMemstat ){
16897         int iSize = sqlite3MallocSize(p);
16898         sqlite3_mutex_enter(mem0.mutex);
16899         sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
16900         sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
16901         sqlite3GlobalConfig.m.xFree(p);
16902         sqlite3_mutex_leave(mem0.mutex);
16903       }else{
16904         sqlite3GlobalConfig.m.xFree(p);
16905       }
16906     }else{
16907       int i;
16908       i = (int)((u8*)p - (u8*)sqlite3GlobalConfig.pScratch);
16909       i /= sqlite3GlobalConfig.szScratch;
16910       assert( i>=0 && i<sqlite3GlobalConfig.nScratch );
16911       sqlite3_mutex_enter(mem0.mutex);
16912       assert( mem0.nScratchFree<(u32)sqlite3GlobalConfig.nScratch );
16913       mem0.aScratchFree[mem0.nScratchFree++] = i;
16914       sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
16915       sqlite3_mutex_leave(mem0.mutex);
16916
16917 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
16918     /* Verify that no more than two scratch allocation per thread
16919     ** is outstanding at one time.  (This is only checked in the
16920     ** single-threaded case since checking in the multi-threaded case
16921     ** would be much more complicated.) */
16922     assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
16923     scratchAllocOut = 0;
16924 #endif
16925
16926     }
16927   }
16928 }
16929
16930 /*
16931 ** TRUE if p is a lookaside memory allocation from db
16932 */
16933 #ifndef SQLITE_OMIT_LOOKASIDE
16934 static int isLookaside(sqlite3 *db, void *p){
16935   return db && p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
16936 }
16937 #else
16938 #define isLookaside(A,B) 0
16939 #endif
16940
16941 /*
16942 ** Return the size of a memory allocation previously obtained from
16943 ** sqlite3Malloc() or sqlite3_malloc().
16944 */
16945 SQLITE_PRIVATE int sqlite3MallocSize(void *p){
16946   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
16947   return sqlite3GlobalConfig.m.xSize(p);
16948 }
16949 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
16950   assert( db==0 || sqlite3_mutex_held(db->mutex) );
16951   if( isLookaside(db, p) ){
16952     return db->lookaside.sz;
16953   }else{
16954     assert( sqlite3MemdebugHasType(p,
16955              db ? (MEMTYPE_DB|MEMTYPE_HEAP) : MEMTYPE_HEAP) );
16956     return sqlite3GlobalConfig.m.xSize(p);
16957   }
16958 }
16959
16960 /*
16961 ** Free memory previously obtained from sqlite3Malloc().
16962 */
16963 SQLITE_API void sqlite3_free(void *p){
16964   if( p==0 ) return;
16965   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
16966   if( sqlite3GlobalConfig.bMemstat ){
16967     sqlite3_mutex_enter(mem0.mutex);
16968     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
16969     sqlite3GlobalConfig.m.xFree(p);
16970     sqlite3_mutex_leave(mem0.mutex);
16971   }else{
16972     sqlite3GlobalConfig.m.xFree(p);
16973   }
16974 }
16975
16976 /*
16977 ** Free memory that might be associated with a particular database
16978 ** connection.
16979 */
16980 SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
16981   assert( db==0 || sqlite3_mutex_held(db->mutex) );
16982   if( isLookaside(db, p) ){
16983     LookasideSlot *pBuf = (LookasideSlot*)p;
16984     pBuf->pNext = db->lookaside.pFree;
16985     db->lookaside.pFree = pBuf;
16986     db->lookaside.nOut--;
16987   }else{
16988     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB|MEMTYPE_HEAP) );
16989     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
16990     sqlite3_free(p);
16991   }
16992 }
16993
16994 /*
16995 ** Change the size of an existing memory allocation
16996 */
16997 SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
16998   int nOld, nNew;
16999   void *pNew;
17000   if( pOld==0 ){
17001     return sqlite3Malloc(nBytes);
17002   }
17003   if( nBytes<=0 ){
17004     sqlite3_free(pOld);
17005     return 0;
17006   }
17007   if( nBytes>=0x7fffff00 ){
17008     /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
17009     return 0;
17010   }
17011   nOld = sqlite3MallocSize(pOld);
17012   nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
17013   if( nOld==nNew ){
17014     pNew = pOld;
17015   }else if( sqlite3GlobalConfig.bMemstat ){
17016     sqlite3_mutex_enter(mem0.mutex);
17017     sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
17018     if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nNew-nOld >= 
17019           mem0.alarmThreshold ){
17020       sqlite3MallocAlarm(nNew-nOld);
17021     }
17022     assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
17023     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
17024     if( pNew==0 && mem0.alarmCallback ){
17025       sqlite3MallocAlarm(nBytes);
17026       pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
17027     }
17028     if( pNew ){
17029       nNew = sqlite3MallocSize(pNew);
17030       sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
17031     }
17032     sqlite3_mutex_leave(mem0.mutex);
17033   }else{
17034     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
17035   }
17036   return pNew;
17037 }
17038
17039 /*
17040 ** The public interface to sqlite3Realloc.  Make sure that the memory
17041 ** subsystem is initialized prior to invoking sqliteRealloc.
17042 */
17043 SQLITE_API void *sqlite3_realloc(void *pOld, int n){
17044 #ifndef SQLITE_OMIT_AUTOINIT
17045   if( sqlite3_initialize() ) return 0;
17046 #endif
17047   return sqlite3Realloc(pOld, n);
17048 }
17049
17050
17051 /*
17052 ** Allocate and zero memory.
17053 */ 
17054 SQLITE_PRIVATE void *sqlite3MallocZero(int n){
17055   void *p = sqlite3Malloc(n);
17056   if( p ){
17057     memset(p, 0, n);
17058   }
17059   return p;
17060 }
17061
17062 /*
17063 ** Allocate and zero memory.  If the allocation fails, make
17064 ** the mallocFailed flag in the connection pointer.
17065 */
17066 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
17067   void *p = sqlite3DbMallocRaw(db, n);
17068   if( p ){
17069     memset(p, 0, n);
17070   }
17071   return p;
17072 }
17073
17074 /*
17075 ** Allocate and zero memory.  If the allocation fails, make
17076 ** the mallocFailed flag in the connection pointer.
17077 **
17078 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
17079 ** failure on the same database connection) then always return 0.
17080 ** Hence for a particular database connection, once malloc starts
17081 ** failing, it fails consistently until mallocFailed is reset.
17082 ** This is an important assumption.  There are many places in the
17083 ** code that do things like this:
17084 **
17085 **         int *a = (int*)sqlite3DbMallocRaw(db, 100);
17086 **         int *b = (int*)sqlite3DbMallocRaw(db, 200);
17087 **         if( b ) a[10] = 9;
17088 **
17089 ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
17090 ** that all prior mallocs (ex: "a") worked too.
17091 */
17092 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
17093   void *p;
17094   assert( db==0 || sqlite3_mutex_held(db->mutex) );
17095 #ifndef SQLITE_OMIT_LOOKASIDE
17096   if( db ){
17097     LookasideSlot *pBuf;
17098     if( db->mallocFailed ){
17099       return 0;
17100     }
17101     if( db->lookaside.bEnabled && n<=db->lookaside.sz
17102          && (pBuf = db->lookaside.pFree)!=0 ){
17103       db->lookaside.pFree = pBuf->pNext;
17104       db->lookaside.nOut++;
17105       if( db->lookaside.nOut>db->lookaside.mxOut ){
17106         db->lookaside.mxOut = db->lookaside.nOut;
17107       }
17108       return (void*)pBuf;
17109     }
17110   }
17111 #else
17112   if( db && db->mallocFailed ){
17113     return 0;
17114   }
17115 #endif
17116   p = sqlite3Malloc(n);
17117   if( !p && db ){
17118     db->mallocFailed = 1;
17119   }
17120   sqlite3MemdebugSetType(p,
17121             (db && db->lookaside.bEnabled) ? MEMTYPE_DB : MEMTYPE_HEAP);
17122   return p;
17123 }
17124
17125 /*
17126 ** Resize the block of memory pointed to by p to n bytes. If the
17127 ** resize fails, set the mallocFailed flag in the connection object.
17128 */
17129 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
17130   void *pNew = 0;
17131   assert( db!=0 );
17132   assert( sqlite3_mutex_held(db->mutex) );
17133   if( db->mallocFailed==0 ){
17134     if( p==0 ){
17135       return sqlite3DbMallocRaw(db, n);
17136     }
17137     if( isLookaside(db, p) ){
17138       if( n<=db->lookaside.sz ){
17139         return p;
17140       }
17141       pNew = sqlite3DbMallocRaw(db, n);
17142       if( pNew ){
17143         memcpy(pNew, p, db->lookaside.sz);
17144         sqlite3DbFree(db, p);
17145       }
17146     }else{
17147       assert( sqlite3MemdebugHasType(p, MEMTYPE_DB|MEMTYPE_HEAP) );
17148       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
17149       pNew = sqlite3_realloc(p, n);
17150       if( !pNew ){
17151         db->mallocFailed = 1;
17152       }
17153       sqlite3MemdebugSetType(pNew,
17154             db->lookaside.bEnabled ? MEMTYPE_DB : MEMTYPE_HEAP);
17155     }
17156   }
17157   return pNew;
17158 }
17159
17160 /*
17161 ** Attempt to reallocate p.  If the reallocation fails, then free p
17162 ** and set the mallocFailed flag in the database connection.
17163 */
17164 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
17165   void *pNew;
17166   pNew = sqlite3DbRealloc(db, p, n);
17167   if( !pNew ){
17168     sqlite3DbFree(db, p);
17169   }
17170   return pNew;
17171 }
17172
17173 /*
17174 ** Make a copy of a string in memory obtained from sqliteMalloc(). These 
17175 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
17176 ** is because when memory debugging is turned on, these two functions are 
17177 ** called via macros that record the current file and line number in the
17178 ** ThreadData structure.
17179 */
17180 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
17181   char *zNew;
17182   size_t n;
17183   if( z==0 ){
17184     return 0;
17185   }
17186   n = sqlite3Strlen30(z) + 1;
17187   assert( (n&0x7fffffff)==n );
17188   zNew = sqlite3DbMallocRaw(db, (int)n);
17189   if( zNew ){
17190     memcpy(zNew, z, n);
17191   }
17192   return zNew;
17193 }
17194 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
17195   char *zNew;
17196   if( z==0 ){
17197     return 0;
17198   }
17199   assert( (n&0x7fffffff)==n );
17200   zNew = sqlite3DbMallocRaw(db, n+1);
17201   if( zNew ){
17202     memcpy(zNew, z, n);
17203     zNew[n] = 0;
17204   }
17205   return zNew;
17206 }
17207
17208 /*
17209 ** Create a string from the zFromat argument and the va_list that follows.
17210 ** Store the string in memory obtained from sqliteMalloc() and make *pz
17211 ** point to that string.
17212 */
17213 SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
17214   va_list ap;
17215   char *z;
17216
17217   va_start(ap, zFormat);
17218   z = sqlite3VMPrintf(db, zFormat, ap);
17219   va_end(ap);
17220   sqlite3DbFree(db, *pz);
17221   *pz = z;
17222 }
17223
17224
17225 /*
17226 ** This function must be called before exiting any API function (i.e. 
17227 ** returning control to the user) that has called sqlite3_malloc or
17228 ** sqlite3_realloc.
17229 **
17230 ** The returned value is normally a copy of the second argument to this
17231 ** function. However, if a malloc() failure has occurred since the previous
17232 ** invocation SQLITE_NOMEM is returned instead. 
17233 **
17234 ** If the first argument, db, is not NULL and a malloc() error has occurred,
17235 ** then the connection error-code (the value returned by sqlite3_errcode())
17236 ** is set to SQLITE_NOMEM.
17237 */
17238 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
17239   /* If the db handle is not NULL, then we must hold the connection handle
17240   ** mutex here. Otherwise the read (and possible write) of db->mallocFailed 
17241   ** is unsafe, as is the call to sqlite3Error().
17242   */
17243   assert( !db || sqlite3_mutex_held(db->mutex) );
17244   if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
17245     sqlite3Error(db, SQLITE_NOMEM, 0);
17246     db->mallocFailed = 0;
17247     rc = SQLITE_NOMEM;
17248   }
17249   return rc & (db ? db->errMask : 0xff);
17250 }
17251
17252 /************** End of malloc.c **********************************************/
17253 /************** Begin file printf.c ******************************************/
17254 /*
17255 ** The "printf" code that follows dates from the 1980's.  It is in
17256 ** the public domain.  The original comments are included here for
17257 ** completeness.  They are very out-of-date but might be useful as
17258 ** an historical reference.  Most of the "enhancements" have been backed
17259 ** out so that the functionality is now the same as standard printf().
17260 **
17261 **************************************************************************
17262 **
17263 ** The following modules is an enhanced replacement for the "printf" subroutines
17264 ** found in the standard C library.  The following enhancements are
17265 ** supported:
17266 **
17267 **      +  Additional functions.  The standard set of "printf" functions
17268 **         includes printf, fprintf, sprintf, vprintf, vfprintf, and
17269 **         vsprintf.  This module adds the following:
17270 **
17271 **           *  snprintf -- Works like sprintf, but has an extra argument
17272 **                          which is the size of the buffer written to.
17273 **
17274 **           *  mprintf --  Similar to sprintf.  Writes output to memory
17275 **                          obtained from malloc.
17276 **
17277 **           *  xprintf --  Calls a function to dispose of output.
17278 **
17279 **           *  nprintf --  No output, but returns the number of characters
17280 **                          that would have been output by printf.
17281 **
17282 **           *  A v- version (ex: vsnprintf) of every function is also
17283 **              supplied.
17284 **
17285 **      +  A few extensions to the formatting notation are supported:
17286 **
17287 **           *  The "=" flag (similar to "-") causes the output to be
17288 **              be centered in the appropriately sized field.
17289 **
17290 **           *  The %b field outputs an integer in binary notation.
17291 **
17292 **           *  The %c field now accepts a precision.  The character output
17293 **              is repeated by the number of times the precision specifies.
17294 **
17295 **           *  The %' field works like %c, but takes as its character the
17296 **              next character of the format string, instead of the next
17297 **              argument.  For example,  printf("%.78'-")  prints 78 minus
17298 **              signs, the same as  printf("%.78c",'-').
17299 **
17300 **      +  When compiled using GCC on a SPARC, this version of printf is
17301 **         faster than the library printf for SUN OS 4.1.
17302 **
17303 **      +  All functions are fully reentrant.
17304 **
17305 */
17306
17307 /*
17308 ** Conversion types fall into various categories as defined by the
17309 ** following enumeration.
17310 */
17311 #define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
17312 #define etFLOAT       2 /* Floating point.  %f */
17313 #define etEXP         3 /* Exponentional notation. %e and %E */
17314 #define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
17315 #define etSIZE        5 /* Return number of characters processed so far. %n */
17316 #define etSTRING      6 /* Strings. %s */
17317 #define etDYNSTRING   7 /* Dynamically allocated strings. %z */
17318 #define etPERCENT     8 /* Percent symbol. %% */
17319 #define etCHARX       9 /* Characters. %c */
17320 /* The rest are extensions, not normally found in printf() */
17321 #define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
17322 #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
17323                           NULL pointers replaced by SQL NULL.  %Q */
17324 #define etTOKEN      12 /* a pointer to a Token structure */
17325 #define etSRCLIST    13 /* a pointer to a SrcList */
17326 #define etPOINTER    14 /* The %p conversion */
17327 #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
17328 #define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
17329
17330 #define etINVALID     0 /* Any unrecognized conversion type */
17331
17332
17333 /*
17334 ** An "etByte" is an 8-bit unsigned value.
17335 */
17336 typedef unsigned char etByte;
17337
17338 /*
17339 ** Each builtin conversion character (ex: the 'd' in "%d") is described
17340 ** by an instance of the following structure
17341 */
17342 typedef struct et_info {   /* Information about each format field */
17343   char fmttype;            /* The format field code letter */
17344   etByte base;             /* The base for radix conversion */
17345   etByte flags;            /* One or more of FLAG_ constants below */
17346   etByte type;             /* Conversion paradigm */
17347   etByte charset;          /* Offset into aDigits[] of the digits string */
17348   etByte prefix;           /* Offset into aPrefix[] of the prefix string */
17349 } et_info;
17350
17351 /*
17352 ** Allowed values for et_info.flags
17353 */
17354 #define FLAG_SIGNED  1     /* True if the value to convert is signed */
17355 #define FLAG_INTERN  2     /* True if for internal use only */
17356 #define FLAG_STRING  4     /* Allow infinity precision */
17357
17358
17359 /*
17360 ** The following table is searched linearly, so it is good to put the
17361 ** most frequently used conversion types first.
17362 */
17363 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
17364 static const char aPrefix[] = "-x0\000X0";
17365 static const et_info fmtinfo[] = {
17366   {  'd', 10, 1, etRADIX,      0,  0 },
17367   {  's',  0, 4, etSTRING,     0,  0 },
17368   {  'g',  0, 1, etGENERIC,    30, 0 },
17369   {  'z',  0, 4, etDYNSTRING,  0,  0 },
17370   {  'q',  0, 4, etSQLESCAPE,  0,  0 },
17371   {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
17372   {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
17373   {  'c',  0, 0, etCHARX,      0,  0 },
17374   {  'o',  8, 0, etRADIX,      0,  2 },
17375   {  'u', 10, 0, etRADIX,      0,  0 },
17376   {  'x', 16, 0, etRADIX,      16, 1 },
17377   {  'X', 16, 0, etRADIX,      0,  4 },
17378 #ifndef SQLITE_OMIT_FLOATING_POINT
17379   {  'f',  0, 1, etFLOAT,      0,  0 },
17380   {  'e',  0, 1, etEXP,        30, 0 },
17381   {  'E',  0, 1, etEXP,        14, 0 },
17382   {  'G',  0, 1, etGENERIC,    14, 0 },
17383 #endif
17384   {  'i', 10, 1, etRADIX,      0,  0 },
17385   {  'n',  0, 0, etSIZE,       0,  0 },
17386   {  '%',  0, 0, etPERCENT,    0,  0 },
17387   {  'p', 16, 0, etPOINTER,    0,  1 },
17388
17389 /* All the rest have the FLAG_INTERN bit set and are thus for internal
17390 ** use only */
17391   {  'T',  0, 2, etTOKEN,      0,  0 },
17392   {  'S',  0, 2, etSRCLIST,    0,  0 },
17393   {  'r', 10, 3, etORDINAL,    0,  0 },
17394 };
17395
17396 /*
17397 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
17398 ** conversions will work.
17399 */
17400 #ifndef SQLITE_OMIT_FLOATING_POINT
17401 /*
17402 ** "*val" is a double such that 0.1 <= *val < 10.0
17403 ** Return the ascii code for the leading digit of *val, then
17404 ** multiply "*val" by 10.0 to renormalize.
17405 **
17406 ** Example:
17407 **     input:     *val = 3.14159
17408 **     output:    *val = 1.4159    function return = '3'
17409 **
17410 ** The counter *cnt is incremented each time.  After counter exceeds
17411 ** 16 (the number of significant digits in a 64-bit float) '0' is
17412 ** always returned.
17413 */
17414 static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
17415   int digit;
17416   LONGDOUBLE_TYPE d;
17417   if( (*cnt)++ >= 16 ) return '0';
17418   digit = (int)*val;
17419   d = digit;
17420   digit += '0';
17421   *val = (*val - d)*10.0;
17422   return (char)digit;
17423 }
17424 #endif /* SQLITE_OMIT_FLOATING_POINT */
17425
17426 /*
17427 ** Append N space characters to the given string buffer.
17428 */
17429 static void appendSpace(StrAccum *pAccum, int N){
17430   static const char zSpaces[] = "                             ";
17431   while( N>=(int)sizeof(zSpaces)-1 ){
17432     sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
17433     N -= sizeof(zSpaces)-1;
17434   }
17435   if( N>0 ){
17436     sqlite3StrAccumAppend(pAccum, zSpaces, N);
17437   }
17438 }
17439
17440 /*
17441 ** On machines with a small stack size, you can redefine the
17442 ** SQLITE_PRINT_BUF_SIZE to be less than 350.
17443 */
17444 #ifndef SQLITE_PRINT_BUF_SIZE
17445 # if defined(SQLITE_SMALL_STACK)
17446 #   define SQLITE_PRINT_BUF_SIZE 50
17447 # else
17448 #   define SQLITE_PRINT_BUF_SIZE 350
17449 # endif
17450 #endif
17451 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
17452
17453 /*
17454 ** The root program.  All variations call this core.
17455 **
17456 ** INPUTS:
17457 **   func   This is a pointer to a function taking three arguments
17458 **            1. A pointer to anything.  Same as the "arg" parameter.
17459 **            2. A pointer to the list of characters to be output
17460 **               (Note, this list is NOT null terminated.)
17461 **            3. An integer number of characters to be output.
17462 **               (Note: This number might be zero.)
17463 **
17464 **   arg    This is the pointer to anything which will be passed as the
17465 **          first argument to "func".  Use it for whatever you like.
17466 **
17467 **   fmt    This is the format string, as in the usual print.
17468 **
17469 **   ap     This is a pointer to a list of arguments.  Same as in
17470 **          vfprint.
17471 **
17472 ** OUTPUTS:
17473 **          The return value is the total number of characters sent to
17474 **          the function "func".  Returns -1 on a error.
17475 **
17476 ** Note that the order in which automatic variables are declared below
17477 ** seems to make a big difference in determining how fast this beast
17478 ** will run.
17479 */
17480 SQLITE_PRIVATE void sqlite3VXPrintf(
17481   StrAccum *pAccum,                  /* Accumulate results here */
17482   int useExtended,                   /* Allow extended %-conversions */
17483   const char *fmt,                   /* Format string */
17484   va_list ap                         /* arguments */
17485 ){
17486   int c;                     /* Next character in the format string */
17487   char *bufpt;               /* Pointer to the conversion buffer */
17488   int precision;             /* Precision of the current field */
17489   int length;                /* Length of the field */
17490   int idx;                   /* A general purpose loop counter */
17491   int width;                 /* Width of the current field */
17492   etByte flag_leftjustify;   /* True if "-" flag is present */
17493   etByte flag_plussign;      /* True if "+" flag is present */
17494   etByte flag_blanksign;     /* True if " " flag is present */
17495   etByte flag_alternateform; /* True if "#" flag is present */
17496   etByte flag_altform2;      /* True if "!" flag is present */
17497   etByte flag_zeropad;       /* True if field width constant starts with zero */
17498   etByte flag_long;          /* True if "l" flag is present */
17499   etByte flag_longlong;      /* True if the "ll" flag is present */
17500   etByte done;               /* Loop termination flag */
17501   sqlite_uint64 longvalue;   /* Value for integer types */
17502   LONGDOUBLE_TYPE realvalue; /* Value for real types */
17503   const et_info *infop;      /* Pointer to the appropriate info structure */
17504   char buf[etBUFSIZE];       /* Conversion buffer */
17505   char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
17506   etByte xtype = 0;          /* Conversion paradigm */
17507   char *zExtra;              /* Extra memory used for etTCLESCAPE conversions */
17508 #ifndef SQLITE_OMIT_FLOATING_POINT
17509   int  exp, e2;              /* exponent of real numbers */
17510   double rounder;            /* Used for rounding floating point values */
17511   etByte flag_dp;            /* True if decimal point should be shown */
17512   etByte flag_rtz;           /* True if trailing zeros should be removed */
17513   etByte flag_exp;           /* True to force display of the exponent */
17514   int nsd;                   /* Number of significant digits returned */
17515 #endif
17516
17517   length = 0;
17518   bufpt = 0;
17519   for(; (c=(*fmt))!=0; ++fmt){
17520     if( c!='%' ){
17521       int amt;
17522       bufpt = (char *)fmt;
17523       amt = 1;
17524       while( (c=(*++fmt))!='%' && c!=0 ) amt++;
17525       sqlite3StrAccumAppend(pAccum, bufpt, amt);
17526       if( c==0 ) break;
17527     }
17528     if( (c=(*++fmt))==0 ){
17529       sqlite3StrAccumAppend(pAccum, "%", 1);
17530       break;
17531     }
17532     /* Find out what flags are present */
17533     flag_leftjustify = flag_plussign = flag_blanksign = 
17534      flag_alternateform = flag_altform2 = flag_zeropad = 0;
17535     done = 0;
17536     do{
17537       switch( c ){
17538         case '-':   flag_leftjustify = 1;     break;
17539         case '+':   flag_plussign = 1;        break;
17540         case ' ':   flag_blanksign = 1;       break;
17541         case '#':   flag_alternateform = 1;   break;
17542         case '!':   flag_altform2 = 1;        break;
17543         case '0':   flag_zeropad = 1;         break;
17544         default:    done = 1;                 break;
17545       }
17546     }while( !done && (c=(*++fmt))!=0 );
17547     /* Get the field width */
17548     width = 0;
17549     if( c=='*' ){
17550       width = va_arg(ap,int);
17551       if( width<0 ){
17552         flag_leftjustify = 1;
17553         width = -width;
17554       }
17555       c = *++fmt;
17556     }else{
17557       while( c>='0' && c<='9' ){
17558         width = width*10 + c - '0';
17559         c = *++fmt;
17560       }
17561     }
17562     if( width > etBUFSIZE-10 ){
17563       width = etBUFSIZE-10;
17564     }
17565     /* Get the precision */
17566     if( c=='.' ){
17567       precision = 0;
17568       c = *++fmt;
17569       if( c=='*' ){
17570         precision = va_arg(ap,int);
17571         if( precision<0 ) precision = -precision;
17572         c = *++fmt;
17573       }else{
17574         while( c>='0' && c<='9' ){
17575           precision = precision*10 + c - '0';
17576           c = *++fmt;
17577         }
17578       }
17579     }else{
17580       precision = -1;
17581     }
17582     /* Get the conversion type modifier */
17583     if( c=='l' ){
17584       flag_long = 1;
17585       c = *++fmt;
17586       if( c=='l' ){
17587         flag_longlong = 1;
17588         c = *++fmt;
17589       }else{
17590         flag_longlong = 0;
17591       }
17592     }else{
17593       flag_long = flag_longlong = 0;
17594     }
17595     /* Fetch the info entry for the field */
17596     infop = &fmtinfo[0];
17597     xtype = etINVALID;
17598     for(idx=0; idx<ArraySize(fmtinfo); idx++){
17599       if( c==fmtinfo[idx].fmttype ){
17600         infop = &fmtinfo[idx];
17601         if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
17602           xtype = infop->type;
17603         }else{
17604           return;
17605         }
17606         break;
17607       }
17608     }
17609     zExtra = 0;
17610
17611
17612     /* Limit the precision to prevent overflowing buf[] during conversion */
17613     if( precision>etBUFSIZE-40 && (infop->flags & FLAG_STRING)==0 ){
17614       precision = etBUFSIZE-40;
17615     }
17616
17617     /*
17618     ** At this point, variables are initialized as follows:
17619     **
17620     **   flag_alternateform          TRUE if a '#' is present.
17621     **   flag_altform2               TRUE if a '!' is present.
17622     **   flag_plussign               TRUE if a '+' is present.
17623     **   flag_leftjustify            TRUE if a '-' is present or if the
17624     **                               field width was negative.
17625     **   flag_zeropad                TRUE if the width began with 0.
17626     **   flag_long                   TRUE if the letter 'l' (ell) prefixed
17627     **                               the conversion character.
17628     **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
17629     **                               the conversion character.
17630     **   flag_blanksign              TRUE if a ' ' is present.
17631     **   width                       The specified field width.  This is
17632     **                               always non-negative.  Zero is the default.
17633     **   precision                   The specified precision.  The default
17634     **                               is -1.
17635     **   xtype                       The class of the conversion.
17636     **   infop                       Pointer to the appropriate info struct.
17637     */
17638     switch( xtype ){
17639       case etPOINTER:
17640         flag_longlong = sizeof(char*)==sizeof(i64);
17641         flag_long = sizeof(char*)==sizeof(long int);
17642         /* Fall through into the next case */
17643       case etORDINAL:
17644       case etRADIX:
17645         if( infop->flags & FLAG_SIGNED ){
17646           i64 v;
17647           if( flag_longlong ){
17648             v = va_arg(ap,i64);
17649           }else if( flag_long ){
17650             v = va_arg(ap,long int);
17651           }else{
17652             v = va_arg(ap,int);
17653           }
17654           if( v<0 ){
17655             longvalue = -v;
17656             prefix = '-';
17657           }else{
17658             longvalue = v;
17659             if( flag_plussign )        prefix = '+';
17660             else if( flag_blanksign )  prefix = ' ';
17661             else                       prefix = 0;
17662           }
17663         }else{
17664           if( flag_longlong ){
17665             longvalue = va_arg(ap,u64);
17666           }else if( flag_long ){
17667             longvalue = va_arg(ap,unsigned long int);
17668           }else{
17669             longvalue = va_arg(ap,unsigned int);
17670           }
17671           prefix = 0;
17672         }
17673         if( longvalue==0 ) flag_alternateform = 0;
17674         if( flag_zeropad && precision<width-(prefix!=0) ){
17675           precision = width-(prefix!=0);
17676         }
17677         bufpt = &buf[etBUFSIZE-1];
17678         if( xtype==etORDINAL ){
17679           static const char zOrd[] = "thstndrd";
17680           int x = (int)(longvalue % 10);
17681           if( x>=4 || (longvalue/10)%10==1 ){
17682             x = 0;
17683           }
17684           buf[etBUFSIZE-3] = zOrd[x*2];
17685           buf[etBUFSIZE-2] = zOrd[x*2+1];
17686           bufpt -= 2;
17687         }
17688         {
17689           register const char *cset;      /* Use registers for speed */
17690           register int base;
17691           cset = &aDigits[infop->charset];
17692           base = infop->base;
17693           do{                                           /* Convert to ascii */
17694             *(--bufpt) = cset[longvalue%base];
17695             longvalue = longvalue/base;
17696           }while( longvalue>0 );
17697         }
17698         length = (int)(&buf[etBUFSIZE-1]-bufpt);
17699         for(idx=precision-length; idx>0; idx--){
17700           *(--bufpt) = '0';                             /* Zero pad */
17701         }
17702         if( prefix ) *(--bufpt) = prefix;               /* Add sign */
17703         if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
17704           const char *pre;
17705           char x;
17706           pre = &aPrefix[infop->prefix];
17707           for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
17708         }
17709         length = (int)(&buf[etBUFSIZE-1]-bufpt);
17710         break;
17711       case etFLOAT:
17712       case etEXP:
17713       case etGENERIC:
17714         realvalue = va_arg(ap,double);
17715 #ifdef SQLITE_OMIT_FLOATING_POINT
17716         length = 0;
17717 #else
17718         if( precision<0 ) precision = 6;         /* Set default precision */
17719         if( precision>etBUFSIZE/2-10 ) precision = etBUFSIZE/2-10;
17720         if( realvalue<0.0 ){
17721           realvalue = -realvalue;
17722           prefix = '-';
17723         }else{
17724           if( flag_plussign )          prefix = '+';
17725           else if( flag_blanksign )    prefix = ' ';
17726           else                         prefix = 0;
17727         }
17728         if( xtype==etGENERIC && precision>0 ) precision--;
17729 #if 0
17730         /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */
17731         for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
17732 #else
17733         /* It makes more sense to use 0.5 */
17734         for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
17735 #endif
17736         if( xtype==etFLOAT ) realvalue += rounder;
17737         /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
17738         exp = 0;
17739         if( sqlite3IsNaN((double)realvalue) ){
17740           bufpt = "NaN";
17741           length = 3;
17742           break;
17743         }
17744         if( realvalue>0.0 ){
17745           while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
17746           while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
17747           while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
17748           while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
17749           while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
17750           if( exp>350 ){
17751             if( prefix=='-' ){
17752               bufpt = "-Inf";
17753             }else if( prefix=='+' ){
17754               bufpt = "+Inf";
17755             }else{
17756               bufpt = "Inf";
17757             }
17758             length = sqlite3Strlen30(bufpt);
17759             break;
17760           }
17761         }
17762         bufpt = buf;
17763         /*
17764         ** If the field type is etGENERIC, then convert to either etEXP
17765         ** or etFLOAT, as appropriate.
17766         */
17767         flag_exp = xtype==etEXP;
17768         if( xtype!=etFLOAT ){
17769           realvalue += rounder;
17770           if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
17771         }
17772         if( xtype==etGENERIC ){
17773           flag_rtz = !flag_alternateform;
17774           if( exp<-4 || exp>precision ){
17775             xtype = etEXP;
17776           }else{
17777             precision = precision - exp;
17778             xtype = etFLOAT;
17779           }
17780         }else{
17781           flag_rtz = 0;
17782         }
17783         if( xtype==etEXP ){
17784           e2 = 0;
17785         }else{
17786           e2 = exp;
17787         }
17788         nsd = 0;
17789         flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
17790         /* The sign in front of the number */
17791         if( prefix ){
17792           *(bufpt++) = prefix;
17793         }
17794         /* Digits prior to the decimal point */
17795         if( e2<0 ){
17796           *(bufpt++) = '0';
17797         }else{
17798           for(; e2>=0; e2--){
17799             *(bufpt++) = et_getdigit(&realvalue,&nsd);
17800           }
17801         }
17802         /* The decimal point */
17803         if( flag_dp ){
17804           *(bufpt++) = '.';
17805         }
17806         /* "0" digits after the decimal point but before the first
17807         ** significant digit of the number */
17808         for(e2++; e2<0; precision--, e2++){
17809           assert( precision>0 );
17810           *(bufpt++) = '0';
17811         }
17812         /* Significant digits after the decimal point */
17813         while( (precision--)>0 ){
17814           *(bufpt++) = et_getdigit(&realvalue,&nsd);
17815         }
17816         /* Remove trailing zeros and the "." if no digits follow the "." */
17817         if( flag_rtz && flag_dp ){
17818           while( bufpt[-1]=='0' ) *(--bufpt) = 0;
17819           assert( bufpt>buf );
17820           if( bufpt[-1]=='.' ){
17821             if( flag_altform2 ){
17822               *(bufpt++) = '0';
17823             }else{
17824               *(--bufpt) = 0;
17825             }
17826           }
17827         }
17828         /* Add the "eNNN" suffix */
17829         if( flag_exp || xtype==etEXP ){
17830           *(bufpt++) = aDigits[infop->charset];
17831           if( exp<0 ){
17832             *(bufpt++) = '-'; exp = -exp;
17833           }else{
17834             *(bufpt++) = '+';
17835           }
17836           if( exp>=100 ){
17837             *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
17838             exp %= 100;
17839           }
17840           *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
17841           *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
17842         }
17843         *bufpt = 0;
17844
17845         /* The converted number is in buf[] and zero terminated. Output it.
17846         ** Note that the number is in the usual order, not reversed as with
17847         ** integer conversions. */
17848         length = (int)(bufpt-buf);
17849         bufpt = buf;
17850
17851         /* Special case:  Add leading zeros if the flag_zeropad flag is
17852         ** set and we are not left justified */
17853         if( flag_zeropad && !flag_leftjustify && length < width){
17854           int i;
17855           int nPad = width - length;
17856           for(i=width; i>=nPad; i--){
17857             bufpt[i] = bufpt[i-nPad];
17858           }
17859           i = prefix!=0;
17860           while( nPad-- ) bufpt[i++] = '0';
17861           length = width;
17862         }
17863 #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
17864         break;
17865       case etSIZE:
17866         *(va_arg(ap,int*)) = pAccum->nChar;
17867         length = width = 0;
17868         break;
17869       case etPERCENT:
17870         buf[0] = '%';
17871         bufpt = buf;
17872         length = 1;
17873         break;
17874       case etCHARX:
17875         c = va_arg(ap,int);
17876         buf[0] = (char)c;
17877         if( precision>=0 ){
17878           for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
17879           length = precision;
17880         }else{
17881           length =1;
17882         }
17883         bufpt = buf;
17884         break;
17885       case etSTRING:
17886       case etDYNSTRING:
17887         bufpt = va_arg(ap,char*);
17888         if( bufpt==0 ){
17889           bufpt = "";
17890         }else if( xtype==etDYNSTRING ){
17891           zExtra = bufpt;
17892         }
17893         if( precision>=0 ){
17894           for(length=0; length<precision && bufpt[length]; length++){}
17895         }else{
17896           length = sqlite3Strlen30(bufpt);
17897         }
17898         break;
17899       case etSQLESCAPE:
17900       case etSQLESCAPE2:
17901       case etSQLESCAPE3: {
17902         int i, j, k, n, isnull;
17903         int needQuote;
17904         char ch;
17905         char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
17906         char *escarg = va_arg(ap,char*);
17907         isnull = escarg==0;
17908         if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
17909         k = precision;
17910         for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
17911           if( ch==q )  n++;
17912         }
17913         needQuote = !isnull && xtype==etSQLESCAPE2;
17914         n += i + 1 + needQuote*2;
17915         if( n>etBUFSIZE ){
17916           bufpt = zExtra = sqlite3Malloc( n );
17917           if( bufpt==0 ){
17918             pAccum->mallocFailed = 1;
17919             return;
17920           }
17921         }else{
17922           bufpt = buf;
17923         }
17924         j = 0;
17925         if( needQuote ) bufpt[j++] = q;
17926         k = i;
17927         for(i=0; i<k; i++){
17928           bufpt[j++] = ch = escarg[i];
17929           if( ch==q ) bufpt[j++] = ch;
17930         }
17931         if( needQuote ) bufpt[j++] = q;
17932         bufpt[j] = 0;
17933         length = j;
17934         /* The precision in %q and %Q means how many input characters to
17935         ** consume, not the length of the output...
17936         ** if( precision>=0 && precision<length ) length = precision; */
17937         break;
17938       }
17939       case etTOKEN: {
17940         Token *pToken = va_arg(ap, Token*);
17941         if( pToken ){
17942           sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
17943         }
17944         length = width = 0;
17945         break;
17946       }
17947       case etSRCLIST: {
17948         SrcList *pSrc = va_arg(ap, SrcList*);
17949         int k = va_arg(ap, int);
17950         struct SrcList_item *pItem = &pSrc->a[k];
17951         assert( k>=0 && k<pSrc->nSrc );
17952         if( pItem->zDatabase ){
17953           sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
17954           sqlite3StrAccumAppend(pAccum, ".", 1);
17955         }
17956         sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
17957         length = width = 0;
17958         break;
17959       }
17960       default: {
17961         assert( xtype==etINVALID );
17962         return;
17963       }
17964     }/* End switch over the format type */
17965     /*
17966     ** The text of the conversion is pointed to by "bufpt" and is
17967     ** "length" characters long.  The field width is "width".  Do
17968     ** the output.
17969     */
17970     if( !flag_leftjustify ){
17971       register int nspace;
17972       nspace = width-length;
17973       if( nspace>0 ){
17974         appendSpace(pAccum, nspace);
17975       }
17976     }
17977     if( length>0 ){
17978       sqlite3StrAccumAppend(pAccum, bufpt, length);
17979     }
17980     if( flag_leftjustify ){
17981       register int nspace;
17982       nspace = width-length;
17983       if( nspace>0 ){
17984         appendSpace(pAccum, nspace);
17985       }
17986     }
17987     if( zExtra ){
17988       sqlite3_free(zExtra);
17989     }
17990   }/* End for loop over the format string */
17991 } /* End of function */
17992
17993 /*
17994 ** Append N bytes of text from z to the StrAccum object.
17995 */
17996 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
17997   assert( z!=0 || N==0 );
17998   if( p->tooBig | p->mallocFailed ){
17999     testcase(p->tooBig);
18000     testcase(p->mallocFailed);
18001     return;
18002   }
18003   if( N<0 ){
18004     N = sqlite3Strlen30(z);
18005   }
18006   if( N==0 || NEVER(z==0) ){
18007     return;
18008   }
18009   if( p->nChar+N >= p->nAlloc ){
18010     char *zNew;
18011     if( !p->useMalloc ){
18012       p->tooBig = 1;
18013       N = p->nAlloc - p->nChar - 1;
18014       if( N<=0 ){
18015         return;
18016       }
18017     }else{
18018       i64 szNew = p->nChar;
18019       szNew += N + 1;
18020       if( szNew > p->mxAlloc ){
18021         sqlite3StrAccumReset(p);
18022         p->tooBig = 1;
18023         return;
18024       }else{
18025         p->nAlloc = (int)szNew;
18026       }
18027       zNew = sqlite3DbMallocRaw(p->db, p->nAlloc );
18028       if( zNew ){
18029         memcpy(zNew, p->zText, p->nChar);
18030         sqlite3StrAccumReset(p);
18031         p->zText = zNew;
18032       }else{
18033         p->mallocFailed = 1;
18034         sqlite3StrAccumReset(p);
18035         return;
18036       }
18037     }
18038   }
18039   memcpy(&p->zText[p->nChar], z, N);
18040   p->nChar += N;
18041 }
18042
18043 /*
18044 ** Finish off a string by making sure it is zero-terminated.
18045 ** Return a pointer to the resulting string.  Return a NULL
18046 ** pointer if any kind of error was encountered.
18047 */
18048 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
18049   if( p->zText ){
18050     p->zText[p->nChar] = 0;
18051     if( p->useMalloc && p->zText==p->zBase ){
18052       p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
18053       if( p->zText ){
18054         memcpy(p->zText, p->zBase, p->nChar+1);
18055       }else{
18056         p->mallocFailed = 1;
18057       }
18058     }
18059   }
18060   return p->zText;
18061 }
18062
18063 /*
18064 ** Reset an StrAccum string.  Reclaim all malloced memory.
18065 */
18066 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
18067   if( p->zText!=p->zBase ){
18068     sqlite3DbFree(p->db, p->zText);
18069   }
18070   p->zText = 0;
18071 }
18072
18073 /*
18074 ** Initialize a string accumulator
18075 */
18076 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
18077   p->zText = p->zBase = zBase;
18078   p->db = 0;
18079   p->nChar = 0;
18080   p->nAlloc = n;
18081   p->mxAlloc = mx;
18082   p->useMalloc = 1;
18083   p->tooBig = 0;
18084   p->mallocFailed = 0;
18085 }
18086
18087 /*
18088 ** Print into memory obtained from sqliteMalloc().  Use the internal
18089 ** %-conversion extensions.
18090 */
18091 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
18092   char *z;
18093   char zBase[SQLITE_PRINT_BUF_SIZE];
18094   StrAccum acc;
18095   assert( db!=0 );
18096   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
18097                       db->aLimit[SQLITE_LIMIT_LENGTH]);
18098   acc.db = db;
18099   sqlite3VXPrintf(&acc, 1, zFormat, ap);
18100   z = sqlite3StrAccumFinish(&acc);
18101   if( acc.mallocFailed ){
18102     db->mallocFailed = 1;
18103   }
18104   return z;
18105 }
18106
18107 /*
18108 ** Print into memory obtained from sqliteMalloc().  Use the internal
18109 ** %-conversion extensions.
18110 */
18111 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
18112   va_list ap;
18113   char *z;
18114   va_start(ap, zFormat);
18115   z = sqlite3VMPrintf(db, zFormat, ap);
18116   va_end(ap);
18117   return z;
18118 }
18119
18120 /*
18121 ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
18122 ** the string and before returnning.  This routine is intended to be used
18123 ** to modify an existing string.  For example:
18124 **
18125 **       x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
18126 **
18127 */
18128 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
18129   va_list ap;
18130   char *z;
18131   va_start(ap, zFormat);
18132   z = sqlite3VMPrintf(db, zFormat, ap);
18133   va_end(ap);
18134   sqlite3DbFree(db, zStr);
18135   return z;
18136 }
18137
18138 /*
18139 ** Print into memory obtained from sqlite3_malloc().  Omit the internal
18140 ** %-conversion extensions.
18141 */
18142 SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
18143   char *z;
18144   char zBase[SQLITE_PRINT_BUF_SIZE];
18145   StrAccum acc;
18146 #ifndef SQLITE_OMIT_AUTOINIT
18147   if( sqlite3_initialize() ) return 0;
18148 #endif
18149   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
18150   sqlite3VXPrintf(&acc, 0, zFormat, ap);
18151   z = sqlite3StrAccumFinish(&acc);
18152   return z;
18153 }
18154
18155 /*
18156 ** Print into memory obtained from sqlite3_malloc()().  Omit the internal
18157 ** %-conversion extensions.
18158 */
18159 SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
18160   va_list ap;
18161   char *z;
18162 #ifndef SQLITE_OMIT_AUTOINIT
18163   if( sqlite3_initialize() ) return 0;
18164 #endif
18165   va_start(ap, zFormat);
18166   z = sqlite3_vmprintf(zFormat, ap);
18167   va_end(ap);
18168   return z;
18169 }
18170
18171 /*
18172 ** sqlite3_snprintf() works like snprintf() except that it ignores the
18173 ** current locale settings.  This is important for SQLite because we
18174 ** are not able to use a "," as the decimal point in place of "." as
18175 ** specified by some locales.
18176 */
18177 SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
18178   char *z;
18179   va_list ap;
18180   StrAccum acc;
18181
18182   if( n<=0 ){
18183     return zBuf;
18184   }
18185   sqlite3StrAccumInit(&acc, zBuf, n, 0);
18186   acc.useMalloc = 0;
18187   va_start(ap,zFormat);
18188   sqlite3VXPrintf(&acc, 0, zFormat, ap);
18189   va_end(ap);
18190   z = sqlite3StrAccumFinish(&acc);
18191   return z;
18192 }
18193
18194 /*
18195 ** This is the routine that actually formats the sqlite3_log() message.
18196 ** We house it in a separate routine from sqlite3_log() to avoid using
18197 ** stack space on small-stack systems when logging is disabled.
18198 **
18199 ** sqlite3_log() must render into a static buffer.  It cannot dynamically
18200 ** allocate memory because it might be called while the memory allocator
18201 ** mutex is held.
18202 */
18203 static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
18204   StrAccum acc;                          /* String accumulator */
18205   char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
18206
18207   sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
18208   acc.useMalloc = 0;
18209   sqlite3VXPrintf(&acc, 0, zFormat, ap);
18210   sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
18211                            sqlite3StrAccumFinish(&acc));
18212 }
18213
18214 /*
18215 ** Format and write a message to the log if logging is enabled.
18216 */
18217 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
18218   va_list ap;                             /* Vararg list */
18219   if( sqlite3GlobalConfig.xLog ){
18220     va_start(ap, zFormat);
18221     renderLogMsg(iErrCode, zFormat, ap);
18222     va_end(ap);
18223   }
18224 }
18225
18226 #if defined(SQLITE_DEBUG)
18227 /*
18228 ** A version of printf() that understands %lld.  Used for debugging.
18229 ** The printf() built into some versions of windows does not understand %lld
18230 ** and segfaults if you give it a long long int.
18231 */
18232 SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
18233   va_list ap;
18234   StrAccum acc;
18235   char zBuf[500];
18236   sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
18237   acc.useMalloc = 0;
18238   va_start(ap,zFormat);
18239   sqlite3VXPrintf(&acc, 0, zFormat, ap);
18240   va_end(ap);
18241   sqlite3StrAccumFinish(&acc);
18242   fprintf(stdout,"%s", zBuf);
18243   fflush(stdout);
18244 }
18245 #endif
18246
18247 #ifndef SQLITE_OMIT_TRACE
18248 /*
18249 ** variable-argument wrapper around sqlite3VXPrintf().
18250 */
18251 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
18252   va_list ap;
18253   va_start(ap,zFormat);
18254   sqlite3VXPrintf(p, 1, zFormat, ap);
18255   va_end(ap);
18256 }
18257 #endif
18258
18259 /************** End of printf.c **********************************************/
18260 /************** Begin file random.c ******************************************/
18261 /*
18262 ** 2001 September 15
18263 **
18264 ** The author disclaims copyright to this source code.  In place of
18265 ** a legal notice, here is a blessing:
18266 **
18267 **    May you do good and not evil.
18268 **    May you find forgiveness for yourself and forgive others.
18269 **    May you share freely, never taking more than you give.
18270 **
18271 *************************************************************************
18272 ** This file contains code to implement a pseudo-random number
18273 ** generator (PRNG) for SQLite.
18274 **
18275 ** Random numbers are used by some of the database backends in order
18276 ** to generate random integer keys for tables or random filenames.
18277 */
18278
18279
18280 /* All threads share a single random number generator.
18281 ** This structure is the current state of the generator.
18282 */
18283 static SQLITE_WSD struct sqlite3PrngType {
18284   unsigned char isInit;          /* True if initialized */
18285   unsigned char i, j;            /* State variables */
18286   unsigned char s[256];          /* State variables */
18287 } sqlite3Prng;
18288
18289 /*
18290 ** Get a single 8-bit random value from the RC4 PRNG.  The Mutex
18291 ** must be held while executing this routine.
18292 **
18293 ** Why not just use a library random generator like lrand48() for this?
18294 ** Because the OP_NewRowid opcode in the VDBE depends on having a very
18295 ** good source of random numbers.  The lrand48() library function may
18296 ** well be good enough.  But maybe not.  Or maybe lrand48() has some
18297 ** subtle problems on some systems that could cause problems.  It is hard
18298 ** to know.  To minimize the risk of problems due to bad lrand48()
18299 ** implementations, SQLite uses this random number generator based
18300 ** on RC4, which we know works very well.
18301 **
18302 ** (Later):  Actually, OP_NewRowid does not depend on a good source of
18303 ** randomness any more.  But we will leave this code in all the same.
18304 */
18305 static u8 randomByte(void){
18306   unsigned char t;
18307
18308
18309   /* The "wsdPrng" macro will resolve to the pseudo-random number generator
18310   ** state vector.  If writable static data is unsupported on the target,
18311   ** we have to locate the state vector at run-time.  In the more common
18312   ** case where writable static data is supported, wsdPrng can refer directly
18313   ** to the "sqlite3Prng" state vector declared above.
18314   */
18315 #ifdef SQLITE_OMIT_WSD
18316   struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
18317 # define wsdPrng p[0]
18318 #else
18319 # define wsdPrng sqlite3Prng
18320 #endif
18321
18322
18323   /* Initialize the state of the random number generator once,
18324   ** the first time this routine is called.  The seed value does
18325   ** not need to contain a lot of randomness since we are not
18326   ** trying to do secure encryption or anything like that...
18327   **
18328   ** Nothing in this file or anywhere else in SQLite does any kind of
18329   ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
18330   ** number generator) not as an encryption device.
18331   */
18332   if( !wsdPrng.isInit ){
18333     int i;
18334     char k[256];
18335     wsdPrng.j = 0;
18336     wsdPrng.i = 0;
18337     sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
18338     for(i=0; i<256; i++){
18339       wsdPrng.s[i] = (u8)i;
18340     }
18341     for(i=0; i<256; i++){
18342       wsdPrng.j += wsdPrng.s[i] + k[i];
18343       t = wsdPrng.s[wsdPrng.j];
18344       wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
18345       wsdPrng.s[i] = t;
18346     }
18347     wsdPrng.isInit = 1;
18348   }
18349
18350   /* Generate and return single random byte
18351   */
18352   wsdPrng.i++;
18353   t = wsdPrng.s[wsdPrng.i];
18354   wsdPrng.j += t;
18355   wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
18356   wsdPrng.s[wsdPrng.j] = t;
18357   t += wsdPrng.s[wsdPrng.i];
18358   return wsdPrng.s[t];
18359 }
18360
18361 /*
18362 ** Return N random bytes.
18363 */
18364 SQLITE_API void sqlite3_randomness(int N, void *pBuf){
18365   unsigned char *zBuf = pBuf;
18366 #if SQLITE_THREADSAFE
18367   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
18368 #endif
18369   sqlite3_mutex_enter(mutex);
18370   while( N-- ){
18371     *(zBuf++) = randomByte();
18372   }
18373   sqlite3_mutex_leave(mutex);
18374 }
18375
18376 #ifndef SQLITE_OMIT_BUILTIN_TEST
18377 /*
18378 ** For testing purposes, we sometimes want to preserve the state of
18379 ** PRNG and restore the PRNG to its saved state at a later time, or
18380 ** to reset the PRNG to its initial state.  These routines accomplish
18381 ** those tasks.
18382 **
18383 ** The sqlite3_test_control() interface calls these routines to
18384 ** control the PRNG.
18385 */
18386 static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
18387 SQLITE_PRIVATE void sqlite3PrngSaveState(void){
18388   memcpy(
18389     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
18390     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
18391     sizeof(sqlite3Prng)
18392   );
18393 }
18394 SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
18395   memcpy(
18396     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
18397     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
18398     sizeof(sqlite3Prng)
18399   );
18400 }
18401 SQLITE_PRIVATE void sqlite3PrngResetState(void){
18402   GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
18403 }
18404 #endif /* SQLITE_OMIT_BUILTIN_TEST */
18405
18406 /************** End of random.c **********************************************/
18407 /************** Begin file utf.c *********************************************/
18408 /*
18409 ** 2004 April 13
18410 **
18411 ** The author disclaims copyright to this source code.  In place of
18412 ** a legal notice, here is a blessing:
18413 **
18414 **    May you do good and not evil.
18415 **    May you find forgiveness for yourself and forgive others.
18416 **    May you share freely, never taking more than you give.
18417 **
18418 *************************************************************************
18419 ** This file contains routines used to translate between UTF-8, 
18420 ** UTF-16, UTF-16BE, and UTF-16LE.
18421 **
18422 ** Notes on UTF-8:
18423 **
18424 **   Byte-0    Byte-1    Byte-2    Byte-3    Value
18425 **  0xxxxxxx                                 00000000 00000000 0xxxxxxx
18426 **  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
18427 **  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
18428 **  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
18429 **
18430 **
18431 ** Notes on UTF-16:  (with wwww+1==uuuuu)
18432 **
18433 **      Word-0               Word-1          Value
18434 **  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
18435 **  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
18436 **
18437 **
18438 ** BOM or Byte Order Mark:
18439 **     0xff 0xfe   little-endian utf-16 follows
18440 **     0xfe 0xff   big-endian utf-16 follows
18441 **
18442 */
18443 /************** Include vdbeInt.h in the middle of utf.c *********************/
18444 /************** Begin file vdbeInt.h *****************************************/
18445 /*
18446 ** 2003 September 6
18447 **
18448 ** The author disclaims copyright to this source code.  In place of
18449 ** a legal notice, here is a blessing:
18450 **
18451 **    May you do good and not evil.
18452 **    May you find forgiveness for yourself and forgive others.
18453 **    May you share freely, never taking more than you give.
18454 **
18455 *************************************************************************
18456 ** This is the header file for information that is private to the
18457 ** VDBE.  This information used to all be at the top of the single
18458 ** source code file "vdbe.c".  When that file became too big (over
18459 ** 6000 lines long) it was split up into several smaller files and
18460 ** this header information was factored out.
18461 */
18462 #ifndef _VDBEINT_H_
18463 #define _VDBEINT_H_
18464
18465 /*
18466 ** SQL is translated into a sequence of instructions to be
18467 ** executed by a virtual machine.  Each instruction is an instance
18468 ** of the following structure.
18469 */
18470 typedef struct VdbeOp Op;
18471
18472 /*
18473 ** Boolean values
18474 */
18475 typedef unsigned char Bool;
18476
18477 /*
18478 ** A cursor is a pointer into a single BTree within a database file.
18479 ** The cursor can seek to a BTree entry with a particular key, or
18480 ** loop over all entries of the Btree.  You can also insert new BTree
18481 ** entries or retrieve the key or data from the entry that the cursor
18482 ** is currently pointing to.
18483 ** 
18484 ** Every cursor that the virtual machine has open is represented by an
18485 ** instance of the following structure.
18486 **
18487 ** If the VdbeCursor.isTriggerRow flag is set it means that this cursor is
18488 ** really a single row that represents the NEW or OLD pseudo-table of
18489 ** a row trigger.  The data for the row is stored in VdbeCursor.pData and
18490 ** the rowid is in VdbeCursor.iKey.
18491 */
18492 struct VdbeCursor {
18493   BtCursor *pCursor;    /* The cursor structure of the backend */
18494   int iDb;              /* Index of cursor database in db->aDb[] (or -1) */
18495   i64 lastRowid;        /* Last rowid from a Next or NextIdx operation */
18496   Bool zeroed;          /* True if zeroed out and ready for reuse */
18497   Bool rowidIsValid;    /* True if lastRowid is valid */
18498   Bool atFirst;         /* True if pointing to first entry */
18499   Bool useRandomRowid;  /* Generate new record numbers semi-randomly */
18500   Bool nullRow;         /* True if pointing to a row with no data */
18501   Bool deferredMoveto;  /* A call to sqlite3BtreeMoveto() is needed */
18502   Bool isTable;         /* True if a table requiring integer keys */
18503   Bool isIndex;         /* True if an index containing keys only - no data */
18504   i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */
18505   Btree *pBt;           /* Separate file holding temporary table */
18506   int pseudoTableReg;   /* Register holding pseudotable content. */
18507   KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
18508   int nField;           /* Number of fields in the header */
18509   i64 seqCount;         /* Sequence counter */
18510   sqlite3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
18511   const sqlite3_module *pModule;     /* Module for cursor pVtabCursor */
18512
18513   /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or 
18514   ** OP_IsUnique opcode on this cursor. */
18515   int seekResult;
18516
18517   /* Cached information about the header for the data record that the
18518   ** cursor is currently pointing to.  Only valid if cacheStatus matches
18519   ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
18520   ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
18521   ** the cache is out of date.
18522   **
18523   ** aRow might point to (ephemeral) data for the current row, or it might
18524   ** be NULL.
18525   */
18526   u32 cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
18527   int payloadSize;      /* Total number of bytes in the record */
18528   u32 *aType;           /* Type values for all entries in the record */
18529   u32 *aOffset;         /* Cached offsets to the start of each columns data */
18530   u8 *aRow;             /* Data for the current row, if all on one page */
18531 };
18532 typedef struct VdbeCursor VdbeCursor;
18533
18534 /*
18535 ** When a sub-program is executed (OP_Program), a structure of this type
18536 ** is allocated to store the current value of the program counter, as
18537 ** well as the current memory cell array and various other frame specific
18538 ** values stored in the Vdbe struct. When the sub-program is finished, 
18539 ** these values are copied back to the Vdbe from the VdbeFrame structure,
18540 ** restoring the state of the VM to as it was before the sub-program
18541 ** began executing.
18542 **
18543 ** Frames are stored in a linked list headed at Vdbe.pParent. Vdbe.pParent
18544 ** is the parent of the current frame, or zero if the current frame
18545 ** is the main Vdbe program.
18546 */
18547 typedef struct VdbeFrame VdbeFrame;
18548 struct VdbeFrame {
18549   Vdbe *v;                /* VM this frame belongs to */
18550   int pc;                 /* Program Counter */
18551   Op *aOp;                /* Program instructions */
18552   int nOp;                /* Size of aOp array */
18553   Mem *aMem;              /* Array of memory cells */
18554   int nMem;               /* Number of entries in aMem */
18555   VdbeCursor **apCsr;     /* Element of Vdbe cursors */
18556   u16 nCursor;            /* Number of entries in apCsr */
18557   void *token;            /* Copy of SubProgram.token */
18558   int nChildMem;          /* Number of memory cells for child frame */
18559   int nChildCsr;          /* Number of cursors for child frame */
18560   i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
18561   int nChange;            /* Statement changes (Vdbe.nChanges)     */
18562   VdbeFrame *pParent;     /* Parent of this frame */
18563 };
18564
18565 #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
18566
18567 /*
18568 ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
18569 */
18570 #define CACHE_STALE 0
18571
18572 /*
18573 ** Internally, the vdbe manipulates nearly all SQL values as Mem
18574 ** structures. Each Mem struct may cache multiple representations (string,
18575 ** integer etc.) of the same value.  A value (and therefore Mem structure)
18576 ** has the following properties:
18577 **
18578 ** Each value has a manifest type. The manifest type of the value stored
18579 ** in a Mem struct is returned by the MemType(Mem*) macro. The type is
18580 ** one of SQLITE_NULL, SQLITE_INTEGER, SQLITE_REAL, SQLITE_TEXT or
18581 ** SQLITE_BLOB.
18582 */
18583 struct Mem {
18584   union {
18585     i64 i;              /* Integer value. */
18586     int nZero;          /* Used when bit MEM_Zero is set in flags */
18587     FuncDef *pDef;      /* Used only when flags==MEM_Agg */
18588     RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
18589     VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */
18590   } u;
18591   double r;           /* Real value */
18592   sqlite3 *db;        /* The associated database connection */
18593   char *z;            /* String or BLOB value */
18594   int n;              /* Number of characters in string value, excluding '\0' */
18595   u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
18596   u8  type;           /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
18597   u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
18598   void (*xDel)(void *);  /* If not null, call this function to delete Mem.z */
18599   char *zMalloc;      /* Dynamic buffer allocated by sqlite3_malloc() */
18600 };
18601
18602 /* One or more of the following flags are set to indicate the validOK
18603 ** representations of the value stored in the Mem struct.
18604 **
18605 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
18606 ** No other flags may be set in this case.
18607 **
18608 ** If the MEM_Str flag is set then Mem.z points at a string representation.
18609 ** Usually this is encoded in the same unicode encoding as the main
18610 ** database (see below for exceptions). If the MEM_Term flag is also
18611 ** set, then the string is nul terminated. The MEM_Int and MEM_Real 
18612 ** flags may coexist with the MEM_Str flag.
18613 **
18614 ** Multiple of these values can appear in Mem.flags.  But only one
18615 ** at a time can appear in Mem.type.
18616 */
18617 #define MEM_Null      0x0001   /* Value is NULL */
18618 #define MEM_Str       0x0002   /* Value is a string */
18619 #define MEM_Int       0x0004   /* Value is an integer */
18620 #define MEM_Real      0x0008   /* Value is a real number */
18621 #define MEM_Blob      0x0010   /* Value is a BLOB */
18622 #define MEM_RowSet    0x0020   /* Value is a RowSet object */
18623 #define MEM_Frame     0x0040   /* Value is a VdbeFrame object */
18624 #define MEM_TypeMask  0x00ff   /* Mask of type bits */
18625
18626 /* Whenever Mem contains a valid string or blob representation, one of
18627 ** the following flags must be set to determine the memory management
18628 ** policy for Mem.z.  The MEM_Term flag tells us whether or not the
18629 ** string is \000 or \u0000 terminated
18630 */
18631 #define MEM_Term      0x0200   /* String rep is nul terminated */
18632 #define MEM_Dyn       0x0400   /* Need to call sqliteFree() on Mem.z */
18633 #define MEM_Static    0x0800   /* Mem.z points to a static string */
18634 #define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
18635 #define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
18636 #define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
18637
18638 #ifdef SQLITE_OMIT_INCRBLOB
18639   #undef MEM_Zero
18640   #define MEM_Zero 0x0000
18641 #endif
18642
18643
18644 /*
18645 ** Clear any existing type flags from a Mem and replace them with f
18646 */
18647 #define MemSetTypeFlag(p, f) \
18648    ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
18649
18650
18651 /* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
18652 ** additional information about auxiliary information bound to arguments
18653 ** of the function.  This is used to implement the sqlite3_get_auxdata()
18654 ** and sqlite3_set_auxdata() APIs.  The "auxdata" is some auxiliary data
18655 ** that can be associated with a constant argument to a function.  This
18656 ** allows functions such as "regexp" to compile their constant regular
18657 ** expression argument once and reused the compiled code for multiple
18658 ** invocations.
18659 */
18660 struct VdbeFunc {
18661   FuncDef *pFunc;               /* The definition of the function */
18662   int nAux;                     /* Number of entries allocated for apAux[] */
18663   struct AuxData {
18664     void *pAux;                   /* Aux data for the i-th argument */
18665     void (*xDelete)(void *);      /* Destructor for the aux data */
18666   } apAux[1];                   /* One slot for each function argument */
18667 };
18668
18669 /*
18670 ** The "context" argument for a installable function.  A pointer to an
18671 ** instance of this structure is the first argument to the routines used
18672 ** implement the SQL functions.
18673 **
18674 ** There is a typedef for this structure in sqlite.h.  So all routines,
18675 ** even the public interface to SQLite, can use a pointer to this structure.
18676 ** But this file is the only place where the internal details of this
18677 ** structure are known.
18678 **
18679 ** This structure is defined inside of vdbeInt.h because it uses substructures
18680 ** (Mem) which are only defined there.
18681 */
18682 struct sqlite3_context {
18683   FuncDef *pFunc;       /* Pointer to function information.  MUST BE FIRST */
18684   VdbeFunc *pVdbeFunc;  /* Auxilary data, if created. */
18685   Mem s;                /* The return value is stored here */
18686   Mem *pMem;            /* Memory cell used to store aggregate context */
18687   int isError;          /* Error code returned by the function. */
18688   CollSeq *pColl;       /* Collating sequence */
18689 };
18690
18691 /*
18692 ** A Set structure is used for quick testing to see if a value
18693 ** is part of a small set.  Sets are used to implement code like
18694 ** this:
18695 **            x.y IN ('hi','hoo','hum')
18696 */
18697 typedef struct Set Set;
18698 struct Set {
18699   Hash hash;             /* A set is just a hash table */
18700   HashElem *prev;        /* Previously accessed hash elemen */
18701 };
18702
18703 /*
18704 ** An instance of the virtual machine.  This structure contains the complete
18705 ** state of the virtual machine.
18706 **
18707 ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_compile()
18708 ** is really a pointer to an instance of this structure.
18709 **
18710 ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
18711 ** any virtual table method invocations made by the vdbe program. It is
18712 ** set to 2 for xDestroy method calls and 1 for all other methods. This
18713 ** variable is used for two purposes: to allow xDestroy methods to execute
18714 ** "DROP TABLE" statements and to prevent some nasty side effects of
18715 ** malloc failure when SQLite is invoked recursively by a virtual table 
18716 ** method function.
18717 */
18718 struct Vdbe {
18719   sqlite3 *db;            /* The database connection that owns this statement */
18720   Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */
18721   int nOp;                /* Number of instructions in the program */
18722   int nOpAlloc;           /* Number of slots allocated for aOp[] */
18723   Op *aOp;                /* Space to hold the virtual machine's program */
18724   int nLabel;             /* Number of labels used */
18725   int nLabelAlloc;        /* Number of slots allocated in aLabel[] */
18726   int *aLabel;            /* Space to hold the labels */
18727   Mem **apArg;            /* Arguments to currently executing user function */
18728   Mem *aColName;          /* Column names to return */
18729   Mem *pResultSet;        /* Pointer to an array of results */
18730   u16 nResColumn;         /* Number of columns in one row of the result set */
18731   u16 nCursor;            /* Number of slots in apCsr[] */
18732   VdbeCursor **apCsr;     /* One element of this array for each open cursor */
18733   u8 errorAction;         /* Recovery action to do in case of an error */
18734   u8 okVar;               /* True if azVar[] has been initialized */
18735   ynVar nVar;             /* Number of entries in aVar[] */
18736   Mem *aVar;              /* Values for the OP_Variable opcode. */
18737   char **azVar;           /* Name of variables */
18738   u32 magic;              /* Magic number for sanity checking */
18739   int nMem;               /* Number of memory locations currently allocated */
18740   Mem *aMem;              /* The memory locations */
18741   u32 cacheCtr;           /* VdbeCursor row cache generation counter */
18742   int pc;                 /* The program counter */
18743   int rc;                 /* Value to return */
18744   char *zErrMsg;          /* Error message written here */
18745   u8 explain;             /* True if EXPLAIN present on SQL command */
18746   u8 changeCntOn;         /* True to update the change-counter */
18747   u8 expired;             /* True if the VM needs to be recompiled */
18748   u8 runOnlyOnce;         /* Automatically expire on reset */
18749   u8 minWriteFileFormat;  /* Minimum file format for writable database files */
18750   u8 inVtabMethod;        /* See comments above */
18751   u8 usesStmtJournal;     /* True if uses a statement journal */
18752   u8 readOnly;            /* True for read-only statements */
18753   u8 isPrepareV2;         /* True if prepared with prepare_v2() */
18754   int nChange;            /* Number of db changes made since last reset */
18755   int btreeMask;          /* Bitmask of db->aDb[] entries referenced */
18756   i64 startTime;          /* Time when query started - used for profiling */
18757   BtreeMutexArray aMutex; /* An array of Btree used here and needing locks */
18758   int aCounter[3];        /* Counters used by sqlite3_stmt_status() */
18759   char *zSql;             /* Text of the SQL statement that generated this */
18760   void *pFree;            /* Free this when deleting the vdbe */
18761   i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
18762   i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
18763   int iStatement;         /* Statement number (or 0 if has not opened stmt) */
18764 #ifdef SQLITE_DEBUG
18765   FILE *trace;            /* Write an execution trace here, if not NULL */
18766 #endif
18767   VdbeFrame *pFrame;      /* Parent frame */
18768   int nFrame;             /* Number of frames in pFrame list */
18769   u32 expmask;            /* Binding to these vars invalidates VM */
18770 };
18771
18772 /*
18773 ** The following are allowed values for Vdbe.magic
18774 */
18775 #define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
18776 #define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
18777 #define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
18778 #define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
18779
18780 /*
18781 ** Function prototypes
18782 */
18783 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
18784 void sqliteVdbePopStack(Vdbe*,int);
18785 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
18786 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
18787 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
18788 #endif
18789 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
18790 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
18791 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
18792 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
18793 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
18794
18795 int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
18796 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
18797 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);
18798 SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
18799 SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
18800 SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
18801 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
18802 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
18803 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
18804 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
18805 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
18806 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
18807 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
18808 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
18809 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
18810 #ifdef SQLITE_OMIT_FLOATING_POINT
18811 # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
18812 #else
18813 SQLITE_PRIVATE   void sqlite3VdbeMemSetDouble(Mem*, double);
18814 #endif
18815 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
18816 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
18817 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
18818 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
18819 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
18820 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
18821 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
18822 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
18823 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
18824 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
18825 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
18826 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
18827 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
18828 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
18829 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
18830 SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
18831 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
18832 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
18833 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
18834 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
18835 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem);
18836
18837 #ifndef SQLITE_OMIT_FOREIGN_KEY
18838 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
18839 #else
18840 # define sqlite3VdbeCheckFk(p,i) 0
18841 #endif
18842
18843 #ifndef SQLITE_OMIT_SHARED_CACHE
18844 SQLITE_PRIVATE void sqlite3VdbeMutexArrayEnter(Vdbe *p);
18845 #else
18846 # define sqlite3VdbeMutexArrayEnter(p)
18847 #endif
18848
18849 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
18850 #ifdef SQLITE_DEBUG
18851 SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
18852 SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
18853 #endif
18854 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
18855
18856 #ifndef SQLITE_OMIT_INCRBLOB
18857 SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
18858 #else
18859   #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
18860 #endif
18861
18862 #endif /* !defined(_VDBEINT_H_) */
18863
18864 /************** End of vdbeInt.h *********************************************/
18865 /************** Continuing where we left off in utf.c ************************/
18866
18867 #ifndef SQLITE_AMALGAMATION
18868 /*
18869 ** The following constant value is used by the SQLITE_BIGENDIAN and
18870 ** SQLITE_LITTLEENDIAN macros.
18871 */
18872 SQLITE_PRIVATE const int sqlite3one = 1;
18873 #endif /* SQLITE_AMALGAMATION */
18874
18875 /*
18876 ** This lookup table is used to help decode the first byte of
18877 ** a multi-byte UTF8 character.
18878 */
18879 static const unsigned char sqlite3Utf8Trans1[] = {
18880   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
18881   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
18882   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
18883   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
18884   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
18885   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
18886   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
18887   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
18888 };
18889
18890
18891 #define WRITE_UTF8(zOut, c) {                          \
18892   if( c<0x00080 ){                                     \
18893     *zOut++ = (u8)(c&0xFF);                            \
18894   }                                                    \
18895   else if( c<0x00800 ){                                \
18896     *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
18897     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
18898   }                                                    \
18899   else if( c<0x10000 ){                                \
18900     *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
18901     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
18902     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
18903   }else{                                               \
18904     *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
18905     *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
18906     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
18907     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
18908   }                                                    \
18909 }
18910
18911 #define WRITE_UTF16LE(zOut, c) {                                    \
18912   if( c<=0xFFFF ){                                                  \
18913     *zOut++ = (u8)(c&0x00FF);                                       \
18914     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
18915   }else{                                                            \
18916     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
18917     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
18918     *zOut++ = (u8)(c&0x00FF);                                       \
18919     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
18920   }                                                                 \
18921 }
18922
18923 #define WRITE_UTF16BE(zOut, c) {                                    \
18924   if( c<=0xFFFF ){                                                  \
18925     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
18926     *zOut++ = (u8)(c&0x00FF);                                       \
18927   }else{                                                            \
18928     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
18929     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
18930     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
18931     *zOut++ = (u8)(c&0x00FF);                                       \
18932   }                                                                 \
18933 }
18934
18935 #define READ_UTF16LE(zIn, TERM, c){                                   \
18936   c = (*zIn++);                                                       \
18937   c += ((*zIn++)<<8);                                                 \
18938   if( c>=0xD800 && c<0xE000 && TERM ){                                \
18939     int c2 = (*zIn++);                                                \
18940     c2 += ((*zIn++)<<8);                                              \
18941     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
18942   }                                                                   \
18943 }
18944
18945 #define READ_UTF16BE(zIn, TERM, c){                                   \
18946   c = ((*zIn++)<<8);                                                  \
18947   c += (*zIn++);                                                      \
18948   if( c>=0xD800 && c<0xE000 && TERM ){                                \
18949     int c2 = ((*zIn++)<<8);                                           \
18950     c2 += (*zIn++);                                                   \
18951     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
18952   }                                                                   \
18953 }
18954
18955 /*
18956 ** Translate a single UTF-8 character.  Return the unicode value.
18957 **
18958 ** During translation, assume that the byte that zTerm points
18959 ** is a 0x00.
18960 **
18961 ** Write a pointer to the next unread byte back into *pzNext.
18962 **
18963 ** Notes On Invalid UTF-8:
18964 **
18965 **  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
18966 **     be encoded as a multi-byte character.  Any multi-byte character that
18967 **     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
18968 **
18969 **  *  This routine never allows a UTF16 surrogate value to be encoded.
18970 **     If a multi-byte character attempts to encode a value between
18971 **     0xd800 and 0xe000 then it is rendered as 0xfffd.
18972 **
18973 **  *  Bytes in the range of 0x80 through 0xbf which occur as the first
18974 **     byte of a character are interpreted as single-byte characters
18975 **     and rendered as themselves even though they are technically
18976 **     invalid characters.
18977 **
18978 **  *  This routine accepts an infinite number of different UTF8 encodings
18979 **     for unicode values 0x80 and greater.  It do not change over-length
18980 **     encodings to 0xfffd as some systems recommend.
18981 */
18982 #define READ_UTF8(zIn, zTerm, c)                           \
18983   c = *(zIn++);                                            \
18984   if( c>=0xc0 ){                                           \
18985     c = sqlite3Utf8Trans1[c-0xc0];                         \
18986     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
18987       c = (c<<6) + (0x3f & *(zIn++));                      \
18988     }                                                      \
18989     if( c<0x80                                             \
18990         || (c&0xFFFFF800)==0xD800                          \
18991         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
18992   }
18993 SQLITE_PRIVATE int sqlite3Utf8Read(
18994   const unsigned char *zIn,       /* First byte of UTF-8 character */
18995   const unsigned char **pzNext    /* Write first byte past UTF-8 char here */
18996 ){
18997   int c;
18998
18999   /* Same as READ_UTF8() above but without the zTerm parameter.
19000   ** For this routine, we assume the UTF8 string is always zero-terminated.
19001   */
19002   c = *(zIn++);
19003   if( c>=0xc0 ){
19004     c = sqlite3Utf8Trans1[c-0xc0];
19005     while( (*zIn & 0xc0)==0x80 ){
19006       c = (c<<6) + (0x3f & *(zIn++));
19007     }
19008     if( c<0x80
19009         || (c&0xFFFFF800)==0xD800
19010         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
19011   }
19012   *pzNext = zIn;
19013   return c;
19014 }
19015
19016
19017
19018
19019 /*
19020 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
19021 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
19022 */ 
19023 /* #define TRANSLATE_TRACE 1 */
19024
19025 #ifndef SQLITE_OMIT_UTF16
19026 /*
19027 ** This routine transforms the internal text encoding used by pMem to
19028 ** desiredEnc. It is an error if the string is already of the desired
19029 ** encoding, or if *pMem does not contain a string value.
19030 */
19031 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
19032   int len;                    /* Maximum length of output string in bytes */
19033   unsigned char *zOut;                  /* Output buffer */
19034   unsigned char *zIn;                   /* Input iterator */
19035   unsigned char *zTerm;                 /* End of input */
19036   unsigned char *z;                     /* Output iterator */
19037   unsigned int c;
19038
19039   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
19040   assert( pMem->flags&MEM_Str );
19041   assert( pMem->enc!=desiredEnc );
19042   assert( pMem->enc!=0 );
19043   assert( pMem->n>=0 );
19044
19045 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
19046   {
19047     char zBuf[100];
19048     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
19049     fprintf(stderr, "INPUT:  %s\n", zBuf);
19050   }
19051 #endif
19052
19053   /* If the translation is between UTF-16 little and big endian, then 
19054   ** all that is required is to swap the byte order. This case is handled
19055   ** differently from the others.
19056   */
19057   if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
19058     u8 temp;
19059     int rc;
19060     rc = sqlite3VdbeMemMakeWriteable(pMem);
19061     if( rc!=SQLITE_OK ){
19062       assert( rc==SQLITE_NOMEM );
19063       return SQLITE_NOMEM;
19064     }
19065     zIn = (u8*)pMem->z;
19066     zTerm = &zIn[pMem->n&~1];
19067     while( zIn<zTerm ){
19068       temp = *zIn;
19069       *zIn = *(zIn+1);
19070       zIn++;
19071       *zIn++ = temp;
19072     }
19073     pMem->enc = desiredEnc;
19074     goto translate_out;
19075   }
19076
19077   /* Set len to the maximum number of bytes required in the output buffer. */
19078   if( desiredEnc==SQLITE_UTF8 ){
19079     /* When converting from UTF-16, the maximum growth results from
19080     ** translating a 2-byte character to a 4-byte UTF-8 character.
19081     ** A single byte is required for the output string
19082     ** nul-terminator.
19083     */
19084     pMem->n &= ~1;
19085     len = pMem->n * 2 + 1;
19086   }else{
19087     /* When converting from UTF-8 to UTF-16 the maximum growth is caused
19088     ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
19089     ** character. Two bytes are required in the output buffer for the
19090     ** nul-terminator.
19091     */
19092     len = pMem->n * 2 + 2;
19093   }
19094
19095   /* Set zIn to point at the start of the input buffer and zTerm to point 1
19096   ** byte past the end.
19097   **
19098   ** Variable zOut is set to point at the output buffer, space obtained
19099   ** from sqlite3_malloc().
19100   */
19101   zIn = (u8*)pMem->z;
19102   zTerm = &zIn[pMem->n];
19103   zOut = sqlite3DbMallocRaw(pMem->db, len);
19104   if( !zOut ){
19105     return SQLITE_NOMEM;
19106   }
19107   z = zOut;
19108
19109   if( pMem->enc==SQLITE_UTF8 ){
19110     if( desiredEnc==SQLITE_UTF16LE ){
19111       /* UTF-8 -> UTF-16 Little-endian */
19112       while( zIn<zTerm ){
19113         /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
19114         READ_UTF8(zIn, zTerm, c);
19115         WRITE_UTF16LE(z, c);
19116       }
19117     }else{
19118       assert( desiredEnc==SQLITE_UTF16BE );
19119       /* UTF-8 -> UTF-16 Big-endian */
19120       while( zIn<zTerm ){
19121         /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
19122         READ_UTF8(zIn, zTerm, c);
19123         WRITE_UTF16BE(z, c);
19124       }
19125     }
19126     pMem->n = (int)(z - zOut);
19127     *z++ = 0;
19128   }else{
19129     assert( desiredEnc==SQLITE_UTF8 );
19130     if( pMem->enc==SQLITE_UTF16LE ){
19131       /* UTF-16 Little-endian -> UTF-8 */
19132       while( zIn<zTerm ){
19133         READ_UTF16LE(zIn, zIn<zTerm, c); 
19134         WRITE_UTF8(z, c);
19135       }
19136     }else{
19137       /* UTF-16 Big-endian -> UTF-8 */
19138       while( zIn<zTerm ){
19139         READ_UTF16BE(zIn, zIn<zTerm, c); 
19140         WRITE_UTF8(z, c);
19141       }
19142     }
19143     pMem->n = (int)(z - zOut);
19144   }
19145   *z = 0;
19146   assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
19147
19148   sqlite3VdbeMemRelease(pMem);
19149   pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
19150   pMem->enc = desiredEnc;
19151   pMem->flags |= (MEM_Term|MEM_Dyn);
19152   pMem->z = (char*)zOut;
19153   pMem->zMalloc = pMem->z;
19154
19155 translate_out:
19156 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
19157   {
19158     char zBuf[100];
19159     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
19160     fprintf(stderr, "OUTPUT: %s\n", zBuf);
19161   }
19162 #endif
19163   return SQLITE_OK;
19164 }
19165
19166 /*
19167 ** This routine checks for a byte-order mark at the beginning of the 
19168 ** UTF-16 string stored in *pMem. If one is present, it is removed and
19169 ** the encoding of the Mem adjusted. This routine does not do any
19170 ** byte-swapping, it just sets Mem.enc appropriately.
19171 **
19172 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
19173 ** changed by this function.
19174 */
19175 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
19176   int rc = SQLITE_OK;
19177   u8 bom = 0;
19178
19179   assert( pMem->n>=0 );
19180   if( pMem->n>1 ){
19181     u8 b1 = *(u8 *)pMem->z;
19182     u8 b2 = *(((u8 *)pMem->z) + 1);
19183     if( b1==0xFE && b2==0xFF ){
19184       bom = SQLITE_UTF16BE;
19185     }
19186     if( b1==0xFF && b2==0xFE ){
19187       bom = SQLITE_UTF16LE;
19188     }
19189   }
19190   
19191   if( bom ){
19192     rc = sqlite3VdbeMemMakeWriteable(pMem);
19193     if( rc==SQLITE_OK ){
19194       pMem->n -= 2;
19195       memmove(pMem->z, &pMem->z[2], pMem->n);
19196       pMem->z[pMem->n] = '\0';
19197       pMem->z[pMem->n+1] = '\0';
19198       pMem->flags |= MEM_Term;
19199       pMem->enc = bom;
19200     }
19201   }
19202   return rc;
19203 }
19204 #endif /* SQLITE_OMIT_UTF16 */
19205
19206 /*
19207 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
19208 ** return the number of unicode characters in pZ up to (but not including)
19209 ** the first 0x00 byte. If nByte is not less than zero, return the
19210 ** number of unicode characters in the first nByte of pZ (or up to 
19211 ** the first 0x00, whichever comes first).
19212 */
19213 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
19214   int r = 0;
19215   const u8 *z = (const u8*)zIn;
19216   const u8 *zTerm;
19217   if( nByte>=0 ){
19218     zTerm = &z[nByte];
19219   }else{
19220     zTerm = (const u8*)(-1);
19221   }
19222   assert( z<=zTerm );
19223   while( *z!=0 && z<zTerm ){
19224     SQLITE_SKIP_UTF8(z);
19225     r++;
19226   }
19227   return r;
19228 }
19229
19230 /* This test function is not currently used by the automated test-suite. 
19231 ** Hence it is only available in debug builds.
19232 */
19233 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
19234 /*
19235 ** Translate UTF-8 to UTF-8.
19236 **
19237 ** This has the effect of making sure that the string is well-formed
19238 ** UTF-8.  Miscoded characters are removed.
19239 **
19240 ** The translation is done in-place (since it is impossible for the
19241 ** correct UTF-8 encoding to be longer than a malformed encoding).
19242 */
19243 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
19244   unsigned char *zOut = zIn;
19245   unsigned char *zStart = zIn;
19246   u32 c;
19247
19248   while( zIn[0] ){
19249     c = sqlite3Utf8Read(zIn, (const u8**)&zIn);
19250     if( c!=0xfffd ){
19251       WRITE_UTF8(zOut, c);
19252     }
19253   }
19254   *zOut = 0;
19255   return (int)(zOut - zStart);
19256 }
19257 #endif
19258
19259 #ifndef SQLITE_OMIT_UTF16
19260 /*
19261 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
19262 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
19263 ** be freed by the calling function.
19264 **
19265 ** NULL is returned if there is an allocation error.
19266 */
19267 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
19268   Mem m;
19269   memset(&m, 0, sizeof(m));
19270   m.db = db;
19271   sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
19272   sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
19273   if( db->mallocFailed ){
19274     sqlite3VdbeMemRelease(&m);
19275     m.z = 0;
19276   }
19277   assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
19278   assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
19279   assert( (m.flags & MEM_Dyn)!=0 || db->mallocFailed );
19280   assert( m.z || db->mallocFailed );
19281   return m.z;
19282 }
19283
19284 /*
19285 ** Convert a UTF-8 string to the UTF-16 encoding specified by parameter
19286 ** enc. A pointer to the new string is returned, and the value of *pnOut
19287 ** is set to the length of the returned string in bytes. The call should
19288 ** arrange to call sqlite3DbFree() on the returned pointer when it is
19289 ** no longer required.
19290 ** 
19291 ** If a malloc failure occurs, NULL is returned and the db.mallocFailed
19292 ** flag set.
19293 */
19294 #ifdef SQLITE_ENABLE_STAT2
19295 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *db, u8 enc, char *z, int n, int *pnOut){
19296   Mem m;
19297   memset(&m, 0, sizeof(m));
19298   m.db = db;
19299   sqlite3VdbeMemSetStr(&m, z, n, SQLITE_UTF8, SQLITE_STATIC);
19300   if( sqlite3VdbeMemTranslate(&m, enc) ){
19301     assert( db->mallocFailed );
19302     return 0;
19303   }
19304   assert( m.z==m.zMalloc );
19305   *pnOut = m.n;
19306   return m.z;
19307 }
19308 #endif
19309
19310 /*
19311 ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
19312 ** Return the number of bytes in the first nChar unicode characters
19313 ** in pZ.  nChar must be non-negative.
19314 */
19315 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
19316   int c;
19317   unsigned char const *z = zIn;
19318   int n = 0;
19319   
19320   if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
19321     while( n<nChar ){
19322       READ_UTF16BE(z, 1, c);
19323       n++;
19324     }
19325   }else{
19326     while( n<nChar ){
19327       READ_UTF16LE(z, 1, c);
19328       n++;
19329     }
19330   }
19331   return (int)(z-(unsigned char const *)zIn);
19332 }
19333
19334 #if defined(SQLITE_TEST)
19335 /*
19336 ** This routine is called from the TCL test function "translate_selftest".
19337 ** It checks that the primitives for serializing and deserializing
19338 ** characters in each encoding are inverses of each other.
19339 */
19340 SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
19341   unsigned int i, t;
19342   unsigned char zBuf[20];
19343   unsigned char *z;
19344   int n;
19345   unsigned int c;
19346
19347   for(i=0; i<0x00110000; i++){
19348     z = zBuf;
19349     WRITE_UTF8(z, i);
19350     n = (int)(z-zBuf);
19351     assert( n>0 && n<=4 );
19352     z[0] = 0;
19353     z = zBuf;
19354     c = sqlite3Utf8Read(z, (const u8**)&z);
19355     t = i;
19356     if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
19357     if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
19358     assert( c==t );
19359     assert( (z-zBuf)==n );
19360   }
19361   for(i=0; i<0x00110000; i++){
19362     if( i>=0xD800 && i<0xE000 ) continue;
19363     z = zBuf;
19364     WRITE_UTF16LE(z, i);
19365     n = (int)(z-zBuf);
19366     assert( n>0 && n<=4 );
19367     z[0] = 0;
19368     z = zBuf;
19369     READ_UTF16LE(z, 1, c);
19370     assert( c==i );
19371     assert( (z-zBuf)==n );
19372   }
19373   for(i=0; i<0x00110000; i++){
19374     if( i>=0xD800 && i<0xE000 ) continue;
19375     z = zBuf;
19376     WRITE_UTF16BE(z, i);
19377     n = (int)(z-zBuf);
19378     assert( n>0 && n<=4 );
19379     z[0] = 0;
19380     z = zBuf;
19381     READ_UTF16BE(z, 1, c);
19382     assert( c==i );
19383     assert( (z-zBuf)==n );
19384   }
19385 }
19386 #endif /* SQLITE_TEST */
19387 #endif /* SQLITE_OMIT_UTF16 */
19388
19389 /************** End of utf.c *************************************************/
19390 /************** Begin file util.c ********************************************/
19391 /*
19392 ** 2001 September 15
19393 **
19394 ** The author disclaims copyright to this source code.  In place of
19395 ** a legal notice, here is a blessing:
19396 **
19397 **    May you do good and not evil.
19398 **    May you find forgiveness for yourself and forgive others.
19399 **    May you share freely, never taking more than you give.
19400 **
19401 *************************************************************************
19402 ** Utility functions used throughout sqlite.
19403 **
19404 ** This file contains functions for allocating memory, comparing
19405 ** strings, and stuff like that.
19406 **
19407 */
19408 #ifdef SQLITE_HAVE_ISNAN
19409 # include <math.h>
19410 #endif
19411
19412 /*
19413 ** Routine needed to support the testcase() macro.
19414 */
19415 #ifdef SQLITE_COVERAGE_TEST
19416 SQLITE_PRIVATE void sqlite3Coverage(int x){
19417   static int dummy = 0;
19418   dummy += x;
19419 }
19420 #endif
19421
19422 #ifndef SQLITE_OMIT_FLOATING_POINT
19423 /*
19424 ** Return true if the floating point value is Not a Number (NaN).
19425 **
19426 ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
19427 ** Otherwise, we have our own implementation that works on most systems.
19428 */
19429 SQLITE_PRIVATE int sqlite3IsNaN(double x){
19430   int rc;   /* The value return */
19431 #if !defined(SQLITE_HAVE_ISNAN)
19432   /*
19433   ** Systems that support the isnan() library function should probably
19434   ** make use of it by compiling with -DSQLITE_HAVE_ISNAN.  But we have
19435   ** found that many systems do not have a working isnan() function so
19436   ** this implementation is provided as an alternative.
19437   **
19438   ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
19439   ** On the other hand, the use of -ffast-math comes with the following
19440   ** warning:
19441   **
19442   **      This option [-ffast-math] should never be turned on by any
19443   **      -O option since it can result in incorrect output for programs
19444   **      which depend on an exact implementation of IEEE or ISO 
19445   **      rules/specifications for math functions.
19446   **
19447   ** Under MSVC, this NaN test may fail if compiled with a floating-
19448   ** point precision mode other than /fp:precise.  From the MSDN 
19449   ** documentation:
19450   **
19451   **      The compiler [with /fp:precise] will properly handle comparisons 
19452   **      involving NaN. For example, x != x evaluates to true if x is NaN 
19453   **      ...
19454   */
19455 #ifdef __FAST_MATH__
19456 # error SQLite will not work correctly with the -ffast-math option of GCC.
19457 #endif
19458   volatile double y = x;
19459   volatile double z = y;
19460   rc = (y!=z);
19461 #else  /* if defined(SQLITE_HAVE_ISNAN) */
19462   rc = isnan(x);
19463 #endif /* SQLITE_HAVE_ISNAN */
19464   testcase( rc );
19465   return rc;
19466 }
19467 #endif /* SQLITE_OMIT_FLOATING_POINT */
19468
19469 /*
19470 ** Compute a string length that is limited to what can be stored in
19471 ** lower 30 bits of a 32-bit signed integer.
19472 **
19473 ** The value returned will never be negative.  Nor will it ever be greater
19474 ** than the actual length of the string.  For very long strings (greater
19475 ** than 1GiB) the value returned might be less than the true string length.
19476 */
19477 SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
19478   const char *z2 = z;
19479   if( z==0 ) return 0;
19480   while( *z2 ){ z2++; }
19481   return 0x3fffffff & (int)(z2 - z);
19482 }
19483
19484 /*
19485 ** Set the most recent error code and error string for the sqlite
19486 ** handle "db". The error code is set to "err_code".
19487 **
19488 ** If it is not NULL, string zFormat specifies the format of the
19489 ** error string in the style of the printf functions: The following
19490 ** format characters are allowed:
19491 **
19492 **      %s      Insert a string
19493 **      %z      A string that should be freed after use
19494 **      %d      Insert an integer
19495 **      %T      Insert a token
19496 **      %S      Insert the first element of a SrcList
19497 **
19498 ** zFormat and any string tokens that follow it are assumed to be
19499 ** encoded in UTF-8.
19500 **
19501 ** To clear the most recent error for sqlite handle "db", sqlite3Error
19502 ** should be called with err_code set to SQLITE_OK and zFormat set
19503 ** to NULL.
19504 */
19505 SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
19506   if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
19507     db->errCode = err_code;
19508     if( zFormat ){
19509       char *z;
19510       va_list ap;
19511       va_start(ap, zFormat);
19512       z = sqlite3VMPrintf(db, zFormat, ap);
19513       va_end(ap);
19514       sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
19515     }else{
19516       sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
19517     }
19518   }
19519 }
19520
19521 /*
19522 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
19523 ** The following formatting characters are allowed:
19524 **
19525 **      %s      Insert a string
19526 **      %z      A string that should be freed after use
19527 **      %d      Insert an integer
19528 **      %T      Insert a token
19529 **      %S      Insert the first element of a SrcList
19530 **
19531 ** This function should be used to report any error that occurs whilst
19532 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
19533 ** last thing the sqlite3_prepare() function does is copy the error
19534 ** stored by this function into the database handle using sqlite3Error().
19535 ** Function sqlite3Error() should be used during statement execution
19536 ** (sqlite3_step() etc.).
19537 */
19538 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
19539   char *zMsg;
19540   va_list ap;
19541   sqlite3 *db = pParse->db;
19542   va_start(ap, zFormat);
19543   zMsg = sqlite3VMPrintf(db, zFormat, ap);
19544   va_end(ap);
19545   if( db->suppressErr ){
19546     sqlite3DbFree(db, zMsg);
19547   }else{
19548     pParse->nErr++;
19549     sqlite3DbFree(db, pParse->zErrMsg);
19550     pParse->zErrMsg = zMsg;
19551     pParse->rc = SQLITE_ERROR;
19552   }
19553 }
19554
19555 /*
19556 ** Convert an SQL-style quoted string into a normal string by removing
19557 ** the quote characters.  The conversion is done in-place.  If the
19558 ** input does not begin with a quote character, then this routine
19559 ** is a no-op.
19560 **
19561 ** The input string must be zero-terminated.  A new zero-terminator
19562 ** is added to the dequoted string.
19563 **
19564 ** The return value is -1 if no dequoting occurs or the length of the
19565 ** dequoted string, exclusive of the zero terminator, if dequoting does
19566 ** occur.
19567 **
19568 ** 2002-Feb-14: This routine is extended to remove MS-Access style
19569 ** brackets from around identifers.  For example:  "[a-b-c]" becomes
19570 ** "a-b-c".
19571 */
19572 SQLITE_PRIVATE int sqlite3Dequote(char *z){
19573   char quote;
19574   int i, j;
19575   if( z==0 ) return -1;
19576   quote = z[0];
19577   switch( quote ){
19578     case '\'':  break;
19579     case '"':   break;
19580     case '`':   break;                /* For MySQL compatibility */
19581     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
19582     default:    return -1;
19583   }
19584   for(i=1, j=0; ALWAYS(z[i]); i++){
19585     if( z[i]==quote ){
19586       if( z[i+1]==quote ){
19587         z[j++] = quote;
19588         i++;
19589       }else{
19590         break;
19591       }
19592     }else{
19593       z[j++] = z[i];
19594     }
19595   }
19596   z[j] = 0;
19597   return j;
19598 }
19599
19600 /* Convenient short-hand */
19601 #define UpperToLower sqlite3UpperToLower
19602
19603 /*
19604 ** Some systems have stricmp().  Others have strcasecmp().  Because
19605 ** there is no consistency, we will define our own.
19606 */
19607 SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
19608   register unsigned char *a, *b;
19609   a = (unsigned char *)zLeft;
19610   b = (unsigned char *)zRight;
19611   while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
19612   return UpperToLower[*a] - UpperToLower[*b];
19613 }
19614 SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
19615   register unsigned char *a, *b;
19616   a = (unsigned char *)zLeft;
19617   b = (unsigned char *)zRight;
19618   while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
19619   return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
19620 }
19621
19622 /*
19623 ** Return TRUE if z is a pure numeric string.  Return FALSE and leave
19624 ** *realnum unchanged if the string contains any character which is not
19625 ** part of a number.
19626 **
19627 ** If the string is pure numeric, set *realnum to TRUE if the string
19628 ** contains the '.' character or an "E+000" style exponentiation suffix.
19629 ** Otherwise set *realnum to FALSE.  Note that just becaue *realnum is
19630 ** false does not mean that the number can be successfully converted into
19631 ** an integer - it might be too big.
19632 **
19633 ** An empty string is considered non-numeric.
19634 */
19635 SQLITE_PRIVATE int sqlite3IsNumber(const char *z, int *realnum, u8 enc){
19636   int incr = (enc==SQLITE_UTF8?1:2);
19637   if( enc==SQLITE_UTF16BE ) z++;
19638   if( *z=='-' || *z=='+' ) z += incr;
19639   if( !sqlite3Isdigit(*z) ){
19640     return 0;
19641   }
19642   z += incr;
19643   *realnum = 0;
19644   while( sqlite3Isdigit(*z) ){ z += incr; }
19645 #ifndef SQLITE_OMIT_FLOATING_POINT
19646   if( *z=='.' ){
19647     z += incr;
19648     if( !sqlite3Isdigit(*z) ) return 0;
19649     while( sqlite3Isdigit(*z) ){ z += incr; }
19650     *realnum = 1;
19651   }
19652   if( *z=='e' || *z=='E' ){
19653     z += incr;
19654     if( *z=='+' || *z=='-' ) z += incr;
19655     if( !sqlite3Isdigit(*z) ) return 0;
19656     while( sqlite3Isdigit(*z) ){ z += incr; }
19657     *realnum = 1;
19658   }
19659 #endif
19660   return *z==0;
19661 }
19662
19663 /*
19664 ** The string z[] is an ASCII representation of a real number.
19665 ** Convert this string to a double.
19666 **
19667 ** This routine assumes that z[] really is a valid number.  If it
19668 ** is not, the result is undefined.
19669 **
19670 ** This routine is used instead of the library atof() function because
19671 ** the library atof() might want to use "," as the decimal point instead
19672 ** of "." depending on how locale is set.  But that would cause problems
19673 ** for SQL.  So this routine always uses "." regardless of locale.
19674 */
19675 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult){
19676 #ifndef SQLITE_OMIT_FLOATING_POINT
19677   const char *zBegin = z;
19678   /* sign * significand * (10 ^ (esign * exponent)) */
19679   int sign = 1;   /* sign of significand */
19680   i64 s = 0;      /* significand */
19681   int d = 0;      /* adjust exponent for shifting decimal point */
19682   int esign = 1;  /* sign of exponent */
19683   int e = 0;      /* exponent */
19684   double result;
19685   int nDigits = 0;
19686
19687   /* skip leading spaces */
19688   while( sqlite3Isspace(*z) ) z++;
19689   /* get sign of significand */
19690   if( *z=='-' ){
19691     sign = -1;
19692     z++;
19693   }else if( *z=='+' ){
19694     z++;
19695   }
19696   /* skip leading zeroes */
19697   while( z[0]=='0' ) z++, nDigits++;
19698
19699   /* copy max significant digits to significand */
19700   while( sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
19701     s = s*10 + (*z - '0');
19702     z++, nDigits++;
19703   }
19704   /* skip non-significant significand digits
19705   ** (increase exponent by d to shift decimal left) */
19706   while( sqlite3Isdigit(*z) ) z++, nDigits++, d++;
19707
19708   /* if decimal point is present */
19709   if( *z=='.' ){
19710     z++;
19711     /* copy digits from after decimal to significand
19712     ** (decrease exponent by d to shift decimal right) */
19713     while( sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
19714       s = s*10 + (*z - '0');
19715       z++, nDigits++, d--;
19716     }
19717     /* skip non-significant digits */
19718     while( sqlite3Isdigit(*z) ) z++, nDigits++;
19719   }
19720
19721   /* if exponent is present */
19722   if( *z=='e' || *z=='E' ){
19723     z++;
19724     /* get sign of exponent */
19725     if( *z=='-' ){
19726       esign = -1;
19727       z++;
19728     }else if( *z=='+' ){
19729       z++;
19730     }
19731     /* copy digits to exponent */
19732     while( sqlite3Isdigit(*z) ){
19733       e = e*10 + (*z - '0');
19734       z++;
19735     }
19736   }
19737
19738   /* adjust exponent by d, and update sign */
19739   e = (e*esign) + d;
19740   if( e<0 ) {
19741     esign = -1;
19742     e *= -1;
19743   } else {
19744     esign = 1;
19745   }
19746
19747   /* if 0 significand */
19748   if( !s ) {
19749     /* In the IEEE 754 standard, zero is signed.
19750     ** Add the sign if we've seen at least one digit */
19751     result = (sign<0 && nDigits) ? -(double)0 : (double)0;
19752   } else {
19753     /* attempt to reduce exponent */
19754     if( esign>0 ){
19755       while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
19756     }else{
19757       while( !(s%10) && e>0 ) e--,s/=10;
19758     }
19759
19760     /* adjust the sign of significand */
19761     s = sign<0 ? -s : s;
19762
19763     /* if exponent, scale significand as appropriate
19764     ** and store in result. */
19765     if( e ){
19766       double scale = 1.0;
19767       /* attempt to handle extremely small/large numbers better */
19768       if( e>307 && e<342 ){
19769         while( e%308 ) { scale *= 1.0e+1; e -= 1; }
19770         if( esign<0 ){
19771           result = s / scale;
19772           result /= 1.0e+308;
19773         }else{
19774           result = s * scale;
19775           result *= 1.0e+308;
19776         }
19777       }else{
19778         /* 1.0e+22 is the largest power of 10 than can be 
19779         ** represented exactly. */
19780         while( e%22 ) { scale *= 1.0e+1; e -= 1; }
19781         while( e>0 ) { scale *= 1.0e+22; e -= 22; }
19782         if( esign<0 ){
19783           result = s / scale;
19784         }else{
19785           result = s * scale;
19786         }
19787       }
19788     } else {
19789       result = (double)s;
19790     }
19791   }
19792
19793   /* store the result */
19794   *pResult = result;
19795
19796   /* return number of characters used */
19797   return (int)(z - zBegin);
19798 #else
19799   return sqlite3Atoi64(z, pResult);
19800 #endif /* SQLITE_OMIT_FLOATING_POINT */
19801 }
19802
19803 /*
19804 ** Compare the 19-character string zNum against the text representation
19805 ** value 2^63:  9223372036854775808.  Return negative, zero, or positive
19806 ** if zNum is less than, equal to, or greater than the string.
19807 **
19808 ** Unlike memcmp() this routine is guaranteed to return the difference
19809 ** in the values of the last digit if the only difference is in the
19810 ** last digit.  So, for example,
19811 **
19812 **      compare2pow63("9223372036854775800")
19813 **
19814 ** will return -8.
19815 */
19816 static int compare2pow63(const char *zNum){
19817   int c;
19818   c = memcmp(zNum,"922337203685477580",18)*10;
19819   if( c==0 ){
19820     c = zNum[18] - '8';
19821     testcase( c==(-1) );
19822     testcase( c==0 );
19823     testcase( c==(+1) );
19824   }
19825   return c;
19826 }
19827
19828
19829 /*
19830 ** Return TRUE if zNum is a 64-bit signed integer and write
19831 ** the value of the integer into *pNum.  If zNum is not an integer
19832 ** or is an integer that is too large to be expressed with 64 bits,
19833 ** then return false.
19834 **
19835 ** When this routine was originally written it dealt with only
19836 ** 32-bit numbers.  At that time, it was much faster than the
19837 ** atoi() library routine in RedHat 7.2.
19838 */
19839 SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum){
19840   i64 v = 0;
19841   int neg;
19842   int i, c;
19843   const char *zStart;
19844   while( sqlite3Isspace(*zNum) ) zNum++;
19845   if( *zNum=='-' ){
19846     neg = 1;
19847     zNum++;
19848   }else if( *zNum=='+' ){
19849     neg = 0;
19850     zNum++;
19851   }else{
19852     neg = 0;
19853   }
19854   zStart = zNum;
19855   while( zNum[0]=='0' ){ zNum++; } /* Skip over leading zeros. Ticket #2454 */
19856   for(i=0; (c=zNum[i])>='0' && c<='9'; i++){
19857     v = v*10 + c - '0';
19858   }
19859   *pNum = neg ? -v : v;
19860   testcase( i==18 );
19861   testcase( i==19 );
19862   testcase( i==20 );
19863   if( c!=0 || (i==0 && zStart==zNum) || i>19 ){
19864     /* zNum is empty or contains non-numeric text or is longer
19865     ** than 19 digits (thus guaranting that it is too large) */
19866     return 0;
19867   }else if( i<19 ){
19868     /* Less than 19 digits, so we know that it fits in 64 bits */
19869     return 1;
19870   }else{
19871     /* 19-digit numbers must be no larger than 9223372036854775807 if positive
19872     ** or 9223372036854775808 if negative.  Note that 9223372036854665808
19873     ** is 2^63. */
19874     return compare2pow63(zNum)<neg;
19875   }
19876 }
19877
19878 /*
19879 ** The string zNum represents an unsigned integer.  The zNum string
19880 ** consists of one or more digit characters and is terminated by
19881 ** a zero character.  Any stray characters in zNum result in undefined
19882 ** behavior.
19883 **
19884 ** If the unsigned integer that zNum represents will fit in a
19885 ** 64-bit signed integer, return TRUE.  Otherwise return FALSE.
19886 **
19887 ** If the negFlag parameter is true, that means that zNum really represents
19888 ** a negative number.  (The leading "-" is omitted from zNum.)  This
19889 ** parameter is needed to determine a boundary case.  A string
19890 ** of "9223373036854775808" returns false if negFlag is false or true
19891 ** if negFlag is true.
19892 **
19893 ** Leading zeros are ignored.
19894 */
19895 SQLITE_PRIVATE int sqlite3FitsIn64Bits(const char *zNum, int negFlag){
19896   int i;
19897   int neg = 0;
19898
19899   assert( zNum[0]>='0' && zNum[0]<='9' ); /* zNum is an unsigned number */
19900
19901   if( negFlag ) neg = 1-neg;
19902   while( *zNum=='0' ){
19903     zNum++;   /* Skip leading zeros.  Ticket #2454 */
19904   }
19905   for(i=0; zNum[i]; i++){ assert( zNum[i]>='0' && zNum[i]<='9' ); }
19906   testcase( i==18 );
19907   testcase( i==19 );
19908   testcase( i==20 );
19909   if( i<19 ){
19910     /* Guaranteed to fit if less than 19 digits */
19911     return 1;
19912   }else if( i>19 ){
19913     /* Guaranteed to be too big if greater than 19 digits */
19914     return 0;
19915   }else{
19916     /* Compare against 2^63. */
19917     return compare2pow63(zNum)<neg;
19918   }
19919 }
19920
19921 /*
19922 ** If zNum represents an integer that will fit in 32-bits, then set
19923 ** *pValue to that integer and return true.  Otherwise return false.
19924 **
19925 ** Any non-numeric characters that following zNum are ignored.
19926 ** This is different from sqlite3Atoi64() which requires the
19927 ** input number to be zero-terminated.
19928 */
19929 SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
19930   sqlite_int64 v = 0;
19931   int i, c;
19932   int neg = 0;
19933   if( zNum[0]=='-' ){
19934     neg = 1;
19935     zNum++;
19936   }else if( zNum[0]=='+' ){
19937     zNum++;
19938   }
19939   while( zNum[0]=='0' ) zNum++;
19940   for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
19941     v = v*10 + c;
19942   }
19943
19944   /* The longest decimal representation of a 32 bit integer is 10 digits:
19945   **
19946   **             1234567890
19947   **     2^31 -> 2147483648
19948   */
19949   testcase( i==10 );
19950   if( i>10 ){
19951     return 0;
19952   }
19953   testcase( v-neg==2147483647 );
19954   if( v-neg>2147483647 ){
19955     return 0;
19956   }
19957   if( neg ){
19958     v = -v;
19959   }
19960   *pValue = (int)v;
19961   return 1;
19962 }
19963
19964 /*
19965 ** The variable-length integer encoding is as follows:
19966 **
19967 ** KEY:
19968 **         A = 0xxxxxxx    7 bits of data and one flag bit
19969 **         B = 1xxxxxxx    7 bits of data and one flag bit
19970 **         C = xxxxxxxx    8 bits of data
19971 **
19972 **  7 bits - A
19973 ** 14 bits - BA
19974 ** 21 bits - BBA
19975 ** 28 bits - BBBA
19976 ** 35 bits - BBBBA
19977 ** 42 bits - BBBBBA
19978 ** 49 bits - BBBBBBA
19979 ** 56 bits - BBBBBBBA
19980 ** 64 bits - BBBBBBBBC
19981 */
19982
19983 /*
19984 ** Write a 64-bit variable-length integer to memory starting at p[0].
19985 ** The length of data write will be between 1 and 9 bytes.  The number
19986 ** of bytes written is returned.
19987 **
19988 ** A variable-length integer consists of the lower 7 bits of each byte
19989 ** for all bytes that have the 8th bit set and one byte with the 8th
19990 ** bit clear.  Except, if we get to the 9th byte, it stores the full
19991 ** 8 bits and is the last byte.
19992 */
19993 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
19994   int i, j, n;
19995   u8 buf[10];
19996   if( v & (((u64)0xff000000)<<32) ){
19997     p[8] = (u8)v;
19998     v >>= 8;
19999     for(i=7; i>=0; i--){
20000       p[i] = (u8)((v & 0x7f) | 0x80);
20001       v >>= 7;
20002     }
20003     return 9;
20004   }    
20005   n = 0;
20006   do{
20007     buf[n++] = (u8)((v & 0x7f) | 0x80);
20008     v >>= 7;
20009   }while( v!=0 );
20010   buf[0] &= 0x7f;
20011   assert( n<=9 );
20012   for(i=0, j=n-1; j>=0; j--, i++){
20013     p[i] = buf[j];
20014   }
20015   return n;
20016 }
20017
20018 /*
20019 ** This routine is a faster version of sqlite3PutVarint() that only
20020 ** works for 32-bit positive integers and which is optimized for
20021 ** the common case of small integers.  A MACRO version, putVarint32,
20022 ** is provided which inlines the single-byte case.  All code should use
20023 ** the MACRO version as this function assumes the single-byte case has
20024 ** already been handled.
20025 */
20026 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
20027 #ifndef putVarint32
20028   if( (v & ~0x7f)==0 ){
20029     p[0] = v;
20030     return 1;
20031   }
20032 #endif
20033   if( (v & ~0x3fff)==0 ){
20034     p[0] = (u8)((v>>7) | 0x80);
20035     p[1] = (u8)(v & 0x7f);
20036     return 2;
20037   }
20038   return sqlite3PutVarint(p, v);
20039 }
20040
20041 /*
20042 ** Bitmasks used by sqlite3GetVarint().  These precomputed constants
20043 ** are defined here rather than simply putting the constant expressions
20044 ** inline in order to work around bugs in the RVT compiler.
20045 **
20046 ** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
20047 **
20048 ** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
20049 */
20050 #define SLOT_2_0     0x001fc07f
20051 #define SLOT_4_2_0   0xf01fc07f
20052
20053
20054 /*
20055 ** Read a 64-bit variable-length integer from memory starting at p[0].
20056 ** Return the number of bytes read.  The value is stored in *v.
20057 */
20058 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
20059   u32 a,b,s;
20060
20061   a = *p;
20062   /* a: p0 (unmasked) */
20063   if (!(a&0x80))
20064   {
20065     *v = a;
20066     return 1;
20067   }
20068
20069   p++;
20070   b = *p;
20071   /* b: p1 (unmasked) */
20072   if (!(b&0x80))
20073   {
20074     a &= 0x7f;
20075     a = a<<7;
20076     a |= b;
20077     *v = a;
20078     return 2;
20079   }
20080
20081   /* Verify that constants are precomputed correctly */
20082   assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
20083   assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
20084
20085   p++;
20086   a = a<<14;
20087   a |= *p;
20088   /* a: p0<<14 | p2 (unmasked) */
20089   if (!(a&0x80))
20090   {
20091     a &= SLOT_2_0;
20092     b &= 0x7f;
20093     b = b<<7;
20094     a |= b;
20095     *v = a;
20096     return 3;
20097   }
20098
20099   /* CSE1 from below */
20100   a &= SLOT_2_0;
20101   p++;
20102   b = b<<14;
20103   b |= *p;
20104   /* b: p1<<14 | p3 (unmasked) */
20105   if (!(b&0x80))
20106   {
20107     b &= SLOT_2_0;
20108     /* moved CSE1 up */
20109     /* a &= (0x7f<<14)|(0x7f); */
20110     a = a<<7;
20111     a |= b;
20112     *v = a;
20113     return 4;
20114   }
20115
20116   /* a: p0<<14 | p2 (masked) */
20117   /* b: p1<<14 | p3 (unmasked) */
20118   /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
20119   /* moved CSE1 up */
20120   /* a &= (0x7f<<14)|(0x7f); */
20121   b &= SLOT_2_0;
20122   s = a;
20123   /* s: p0<<14 | p2 (masked) */
20124
20125   p++;
20126   a = a<<14;
20127   a |= *p;
20128   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
20129   if (!(a&0x80))
20130   {
20131     /* we can skip these cause they were (effectively) done above in calc'ing s */
20132     /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
20133     /* b &= (0x7f<<14)|(0x7f); */
20134     b = b<<7;
20135     a |= b;
20136     s = s>>18;
20137     *v = ((u64)s)<<32 | a;
20138     return 5;
20139   }
20140
20141   /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
20142   s = s<<7;
20143   s |= b;
20144   /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
20145
20146   p++;
20147   b = b<<14;
20148   b |= *p;
20149   /* b: p1<<28 | p3<<14 | p5 (unmasked) */
20150   if (!(b&0x80))
20151   {
20152     /* we can skip this cause it was (effectively) done above in calc'ing s */
20153     /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
20154     a &= SLOT_2_0;
20155     a = a<<7;
20156     a |= b;
20157     s = s>>18;
20158     *v = ((u64)s)<<32 | a;
20159     return 6;
20160   }
20161
20162   p++;
20163   a = a<<14;
20164   a |= *p;
20165   /* a: p2<<28 | p4<<14 | p6 (unmasked) */
20166   if (!(a&0x80))
20167   {
20168     a &= SLOT_4_2_0;
20169     b &= SLOT_2_0;
20170     b = b<<7;
20171     a |= b;
20172     s = s>>11;
20173     *v = ((u64)s)<<32 | a;
20174     return 7;
20175   }
20176
20177   /* CSE2 from below */
20178   a &= SLOT_2_0;
20179   p++;
20180   b = b<<14;
20181   b |= *p;
20182   /* b: p3<<28 | p5<<14 | p7 (unmasked) */
20183   if (!(b&0x80))
20184   {
20185     b &= SLOT_4_2_0;
20186     /* moved CSE2 up */
20187     /* a &= (0x7f<<14)|(0x7f); */
20188     a = a<<7;
20189     a |= b;
20190     s = s>>4;
20191     *v = ((u64)s)<<32 | a;
20192     return 8;
20193   }
20194
20195   p++;
20196   a = a<<15;
20197   a |= *p;
20198   /* a: p4<<29 | p6<<15 | p8 (unmasked) */
20199
20200   /* moved CSE2 up */
20201   /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
20202   b &= SLOT_2_0;
20203   b = b<<8;
20204   a |= b;
20205
20206   s = s<<4;
20207   b = p[-4];
20208   b &= 0x7f;
20209   b = b>>3;
20210   s |= b;
20211
20212   *v = ((u64)s)<<32 | a;
20213
20214   return 9;
20215 }
20216
20217 /*
20218 ** Read a 32-bit variable-length integer from memory starting at p[0].
20219 ** Return the number of bytes read.  The value is stored in *v.
20220 **
20221 ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
20222 ** integer, then set *v to 0xffffffff.
20223 **
20224 ** A MACRO version, getVarint32, is provided which inlines the 
20225 ** single-byte case.  All code should use the MACRO version as 
20226 ** this function assumes the single-byte case has already been handled.
20227 */
20228 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
20229   u32 a,b;
20230
20231   /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
20232   ** by the getVarin32() macro */
20233   a = *p;
20234   /* a: p0 (unmasked) */
20235 #ifndef getVarint32
20236   if (!(a&0x80))
20237   {
20238     /* Values between 0 and 127 */
20239     *v = a;
20240     return 1;
20241   }
20242 #endif
20243
20244   /* The 2-byte case */
20245   p++;
20246   b = *p;
20247   /* b: p1 (unmasked) */
20248   if (!(b&0x80))
20249   {
20250     /* Values between 128 and 16383 */
20251     a &= 0x7f;
20252     a = a<<7;
20253     *v = a | b;
20254     return 2;
20255   }
20256
20257   /* The 3-byte case */
20258   p++;
20259   a = a<<14;
20260   a |= *p;
20261   /* a: p0<<14 | p2 (unmasked) */
20262   if (!(a&0x80))
20263   {
20264     /* Values between 16384 and 2097151 */
20265     a &= (0x7f<<14)|(0x7f);
20266     b &= 0x7f;
20267     b = b<<7;
20268     *v = a | b;
20269     return 3;
20270   }
20271
20272   /* A 32-bit varint is used to store size information in btrees.
20273   ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
20274   ** A 3-byte varint is sufficient, for example, to record the size
20275   ** of a 1048569-byte BLOB or string.
20276   **
20277   ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
20278   ** rare larger cases can be handled by the slower 64-bit varint
20279   ** routine.
20280   */
20281 #if 1
20282   {
20283     u64 v64;
20284     u8 n;
20285
20286     p -= 2;
20287     n = sqlite3GetVarint(p, &v64);
20288     assert( n>3 && n<=9 );
20289     if( (v64 & SQLITE_MAX_U32)!=v64 ){
20290       *v = 0xffffffff;
20291     }else{
20292       *v = (u32)v64;
20293     }
20294     return n;
20295   }
20296
20297 #else
20298   /* For following code (kept for historical record only) shows an
20299   ** unrolling for the 3- and 4-byte varint cases.  This code is
20300   ** slightly faster, but it is also larger and much harder to test.
20301   */
20302   p++;
20303   b = b<<14;
20304   b |= *p;
20305   /* b: p1<<14 | p3 (unmasked) */
20306   if (!(b&0x80))
20307   {
20308     /* Values between 2097152 and 268435455 */
20309     b &= (0x7f<<14)|(0x7f);
20310     a &= (0x7f<<14)|(0x7f);
20311     a = a<<7;
20312     *v = a | b;
20313     return 4;
20314   }
20315
20316   p++;
20317   a = a<<14;
20318   a |= *p;
20319   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
20320   if (!(a&0x80))
20321   {
20322     /* Values  between 268435456 and 34359738367 */
20323     a &= SLOT_4_2_0;
20324     b &= SLOT_4_2_0;
20325     b = b<<7;
20326     *v = a | b;
20327     return 5;
20328   }
20329
20330   /* We can only reach this point when reading a corrupt database
20331   ** file.  In that case we are not in any hurry.  Use the (relatively
20332   ** slow) general-purpose sqlite3GetVarint() routine to extract the
20333   ** value. */
20334   {
20335     u64 v64;
20336     u8 n;
20337
20338     p -= 4;
20339     n = sqlite3GetVarint(p, &v64);
20340     assert( n>5 && n<=9 );
20341     *v = (u32)v64;
20342     return n;
20343   }
20344 #endif
20345 }
20346
20347 /*
20348 ** Return the number of bytes that will be needed to store the given
20349 ** 64-bit integer.
20350 */
20351 SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
20352   int i = 0;
20353   do{
20354     i++;
20355     v >>= 7;
20356   }while( v!=0 && ALWAYS(i<9) );
20357   return i;
20358 }
20359
20360
20361 /*
20362 ** Read or write a four-byte big-endian integer value.
20363 */
20364 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
20365   return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
20366 }
20367 SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
20368   p[0] = (u8)(v>>24);
20369   p[1] = (u8)(v>>16);
20370   p[2] = (u8)(v>>8);
20371   p[3] = (u8)v;
20372 }
20373
20374
20375
20376 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
20377 /*
20378 ** Translate a single byte of Hex into an integer.
20379 ** This routine only works if h really is a valid hexadecimal
20380 ** character:  0..9a..fA..F
20381 */
20382 static u8 hexToInt(int h){
20383   assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
20384 #ifdef SQLITE_ASCII
20385   h += 9*(1&(h>>6));
20386 #endif
20387 #ifdef SQLITE_EBCDIC
20388   h += 9*(1&~(h>>4));
20389 #endif
20390   return (u8)(h & 0xf);
20391 }
20392 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
20393
20394 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
20395 /*
20396 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
20397 ** value.  Return a pointer to its binary value.  Space to hold the
20398 ** binary value has been obtained from malloc and must be freed by
20399 ** the calling routine.
20400 */
20401 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
20402   char *zBlob;
20403   int i;
20404
20405   zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
20406   n--;
20407   if( zBlob ){
20408     for(i=0; i<n; i+=2){
20409       zBlob[i/2] = (hexToInt(z[i])<<4) | hexToInt(z[i+1]);
20410     }
20411     zBlob[i/2] = 0;
20412   }
20413   return zBlob;
20414 }
20415 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
20416
20417 /*
20418 ** Log an error that is an API call on a connection pointer that should
20419 ** not have been used.  The "type" of connection pointer is given as the
20420 ** argument.  The zType is a word like "NULL" or "closed" or "invalid".
20421 */
20422 static void logBadConnection(const char *zType){
20423   sqlite3_log(SQLITE_MISUSE, 
20424      "API call with %s database connection pointer",
20425      zType
20426   );
20427 }
20428
20429 /*
20430 ** Check to make sure we have a valid db pointer.  This test is not
20431 ** foolproof but it does provide some measure of protection against
20432 ** misuse of the interface such as passing in db pointers that are
20433 ** NULL or which have been previously closed.  If this routine returns
20434 ** 1 it means that the db pointer is valid and 0 if it should not be
20435 ** dereferenced for any reason.  The calling function should invoke
20436 ** SQLITE_MISUSE immediately.
20437 **
20438 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
20439 ** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
20440 ** open properly and is not fit for general use but which can be
20441 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
20442 */
20443 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
20444   u32 magic;
20445   if( db==0 ){
20446     logBadConnection("NULL");
20447     return 0;
20448   }
20449   magic = db->magic;
20450   if( magic!=SQLITE_MAGIC_OPEN ){
20451     if( sqlite3SafetyCheckSickOrOk(db) ){
20452       testcase( sqlite3GlobalConfig.xLog!=0 );
20453       logBadConnection("unopened");
20454     }
20455     return 0;
20456   }else{
20457     return 1;
20458   }
20459 }
20460 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
20461   u32 magic;
20462   magic = db->magic;
20463   if( magic!=SQLITE_MAGIC_SICK &&
20464       magic!=SQLITE_MAGIC_OPEN &&
20465       magic!=SQLITE_MAGIC_BUSY ){
20466     testcase( sqlite3GlobalConfig.xLog!=0 );
20467     logBadConnection("invalid");
20468     return 0;
20469   }else{
20470     return 1;
20471   }
20472 }
20473
20474 /************** End of util.c ************************************************/
20475 /************** Begin file hash.c ********************************************/
20476 /*
20477 ** 2001 September 22
20478 **
20479 ** The author disclaims copyright to this source code.  In place of
20480 ** a legal notice, here is a blessing:
20481 **
20482 **    May you do good and not evil.
20483 **    May you find forgiveness for yourself and forgive others.
20484 **    May you share freely, never taking more than you give.
20485 **
20486 *************************************************************************
20487 ** This is the implementation of generic hash-tables
20488 ** used in SQLite.
20489 */
20490
20491 /* Turn bulk memory into a hash table object by initializing the
20492 ** fields of the Hash structure.
20493 **
20494 ** "pNew" is a pointer to the hash table that is to be initialized.
20495 */
20496 SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
20497   assert( pNew!=0 );
20498   pNew->first = 0;
20499   pNew->count = 0;
20500   pNew->htsize = 0;
20501   pNew->ht = 0;
20502 }
20503
20504 /* Remove all entries from a hash table.  Reclaim all memory.
20505 ** Call this routine to delete a hash table or to reset a hash table
20506 ** to the empty state.
20507 */
20508 SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
20509   HashElem *elem;         /* For looping over all elements of the table */
20510
20511   assert( pH!=0 );
20512   elem = pH->first;
20513   pH->first = 0;
20514   sqlite3_free(pH->ht);
20515   pH->ht = 0;
20516   pH->htsize = 0;
20517   while( elem ){
20518     HashElem *next_elem = elem->next;
20519     sqlite3_free(elem);
20520     elem = next_elem;
20521   }
20522   pH->count = 0;
20523 }
20524
20525 /*
20526 ** The hashing function.
20527 */
20528 static unsigned int strHash(const char *z, int nKey){
20529   int h = 0;
20530   assert( nKey>=0 );
20531   while( nKey > 0  ){
20532     h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
20533     nKey--;
20534   }
20535   return h;
20536 }
20537
20538
20539 /* Link pNew element into the hash table pH.  If pEntry!=0 then also
20540 ** insert pNew into the pEntry hash bucket.
20541 */
20542 static void insertElement(
20543   Hash *pH,              /* The complete hash table */
20544   struct _ht *pEntry,    /* The entry into which pNew is inserted */
20545   HashElem *pNew         /* The element to be inserted */
20546 ){
20547   HashElem *pHead;       /* First element already in pEntry */
20548   if( pEntry ){
20549     pHead = pEntry->count ? pEntry->chain : 0;
20550     pEntry->count++;
20551     pEntry->chain = pNew;
20552   }else{
20553     pHead = 0;
20554   }
20555   if( pHead ){
20556     pNew->next = pHead;
20557     pNew->prev = pHead->prev;
20558     if( pHead->prev ){ pHead->prev->next = pNew; }
20559     else             { pH->first = pNew; }
20560     pHead->prev = pNew;
20561   }else{
20562     pNew->next = pH->first;
20563     if( pH->first ){ pH->first->prev = pNew; }
20564     pNew->prev = 0;
20565     pH->first = pNew;
20566   }
20567 }
20568
20569
20570 /* Resize the hash table so that it cantains "new_size" buckets.
20571 **
20572 ** The hash table might fail to resize if sqlite3_malloc() fails or
20573 ** if the new size is the same as the prior size.
20574 ** Return TRUE if the resize occurs and false if not.
20575 */
20576 static int rehash(Hash *pH, unsigned int new_size){
20577   struct _ht *new_ht;            /* The new hash table */
20578   HashElem *elem, *next_elem;    /* For looping over existing elements */
20579
20580 #if SQLITE_MALLOC_SOFT_LIMIT>0
20581   if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
20582     new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
20583   }
20584   if( new_size==pH->htsize ) return 0;
20585 #endif
20586
20587   /* The inability to allocates space for a larger hash table is
20588   ** a performance hit but it is not a fatal error.  So mark the
20589   ** allocation as a benign.
20590   */
20591   sqlite3BeginBenignMalloc();
20592   new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
20593   sqlite3EndBenignMalloc();
20594
20595   if( new_ht==0 ) return 0;
20596   sqlite3_free(pH->ht);
20597   pH->ht = new_ht;
20598   pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
20599   memset(new_ht, 0, new_size*sizeof(struct _ht));
20600   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
20601     unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
20602     next_elem = elem->next;
20603     insertElement(pH, &new_ht[h], elem);
20604   }
20605   return 1;
20606 }
20607
20608 /* This function (for internal use only) locates an element in an
20609 ** hash table that matches the given key.  The hash for this key has
20610 ** already been computed and is passed as the 4th parameter.
20611 */
20612 static HashElem *findElementGivenHash(
20613   const Hash *pH,     /* The pH to be searched */
20614   const char *pKey,   /* The key we are searching for */
20615   int nKey,           /* Bytes in key (not counting zero terminator) */
20616   unsigned int h      /* The hash for this key. */
20617 ){
20618   HashElem *elem;                /* Used to loop thru the element list */
20619   int count;                     /* Number of elements left to test */
20620
20621   if( pH->ht ){
20622     struct _ht *pEntry = &pH->ht[h];
20623     elem = pEntry->chain;
20624     count = pEntry->count;
20625   }else{
20626     elem = pH->first;
20627     count = pH->count;
20628   }
20629   while( count-- && ALWAYS(elem) ){
20630     if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){ 
20631       return elem;
20632     }
20633     elem = elem->next;
20634   }
20635   return 0;
20636 }
20637
20638 /* Remove a single entry from the hash table given a pointer to that
20639 ** element and a hash on the element's key.
20640 */
20641 static void removeElementGivenHash(
20642   Hash *pH,         /* The pH containing "elem" */
20643   HashElem* elem,   /* The element to be removed from the pH */
20644   unsigned int h    /* Hash value for the element */
20645 ){
20646   struct _ht *pEntry;
20647   if( elem->prev ){
20648     elem->prev->next = elem->next; 
20649   }else{
20650     pH->first = elem->next;
20651   }
20652   if( elem->next ){
20653     elem->next->prev = elem->prev;
20654   }
20655   if( pH->ht ){
20656     pEntry = &pH->ht[h];
20657     if( pEntry->chain==elem ){
20658       pEntry->chain = elem->next;
20659     }
20660     pEntry->count--;
20661     assert( pEntry->count>=0 );
20662   }
20663   sqlite3_free( elem );
20664   pH->count--;
20665   if( pH->count<=0 ){
20666     assert( pH->first==0 );
20667     assert( pH->count==0 );
20668     sqlite3HashClear(pH);
20669   }
20670 }
20671
20672 /* Attempt to locate an element of the hash table pH with a key
20673 ** that matches pKey,nKey.  Return the data for this element if it is
20674 ** found, or NULL if there is no match.
20675 */
20676 SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
20677   HashElem *elem;    /* The element that matches key */
20678   unsigned int h;    /* A hash on key */
20679
20680   assert( pH!=0 );
20681   assert( pKey!=0 );
20682   assert( nKey>=0 );
20683   if( pH->ht ){
20684     h = strHash(pKey, nKey) % pH->htsize;
20685   }else{
20686     h = 0;
20687   }
20688   elem = findElementGivenHash(pH, pKey, nKey, h);
20689   return elem ? elem->data : 0;
20690 }
20691
20692 /* Insert an element into the hash table pH.  The key is pKey,nKey
20693 ** and the data is "data".
20694 **
20695 ** If no element exists with a matching key, then a new
20696 ** element is created and NULL is returned.
20697 **
20698 ** If another element already exists with the same key, then the
20699 ** new data replaces the old data and the old data is returned.
20700 ** The key is not copied in this instance.  If a malloc fails, then
20701 ** the new data is returned and the hash table is unchanged.
20702 **
20703 ** If the "data" parameter to this function is NULL, then the
20704 ** element corresponding to "key" is removed from the hash table.
20705 */
20706 SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
20707   unsigned int h;       /* the hash of the key modulo hash table size */
20708   HashElem *elem;       /* Used to loop thru the element list */
20709   HashElem *new_elem;   /* New element added to the pH */
20710
20711   assert( pH!=0 );
20712   assert( pKey!=0 );
20713   assert( nKey>=0 );
20714   if( pH->htsize ){
20715     h = strHash(pKey, nKey) % pH->htsize;
20716   }else{
20717     h = 0;
20718   }
20719   elem = findElementGivenHash(pH,pKey,nKey,h);
20720   if( elem ){
20721     void *old_data = elem->data;
20722     if( data==0 ){
20723       removeElementGivenHash(pH,elem,h);
20724     }else{
20725       elem->data = data;
20726       elem->pKey = pKey;
20727       assert(nKey==elem->nKey);
20728     }
20729     return old_data;
20730   }
20731   if( data==0 ) return 0;
20732   new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
20733   if( new_elem==0 ) return data;
20734   new_elem->pKey = pKey;
20735   new_elem->nKey = nKey;
20736   new_elem->data = data;
20737   pH->count++;
20738   if( pH->count>=10 && pH->count > 2*pH->htsize ){
20739     if( rehash(pH, pH->count*2) ){
20740       assert( pH->htsize>0 );
20741       h = strHash(pKey, nKey) % pH->htsize;
20742     }
20743   }
20744   if( pH->ht ){
20745     insertElement(pH, &pH->ht[h], new_elem);
20746   }else{
20747     insertElement(pH, 0, new_elem);
20748   }
20749   return 0;
20750 }
20751
20752 /************** End of hash.c ************************************************/
20753 /************** Begin file opcodes.c *****************************************/
20754 /* Automatically generated.  Do not edit */
20755 /* See the mkopcodec.awk script for details. */
20756 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
20757 SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
20758  static const char *const azName[] = { "?",
20759      /*   1 */ "Goto",
20760      /*   2 */ "Gosub",
20761      /*   3 */ "Return",
20762      /*   4 */ "Yield",
20763      /*   5 */ "HaltIfNull",
20764      /*   6 */ "Halt",
20765      /*   7 */ "Integer",
20766      /*   8 */ "Int64",
20767      /*   9 */ "String",
20768      /*  10 */ "Null",
20769      /*  11 */ "Blob",
20770      /*  12 */ "Variable",
20771      /*  13 */ "Move",
20772      /*  14 */ "Copy",
20773      /*  15 */ "SCopy",
20774      /*  16 */ "ResultRow",
20775      /*  17 */ "CollSeq",
20776      /*  18 */ "Function",
20777      /*  19 */ "Not",
20778      /*  20 */ "AddImm",
20779      /*  21 */ "MustBeInt",
20780      /*  22 */ "RealAffinity",
20781      /*  23 */ "Permutation",
20782      /*  24 */ "Compare",
20783      /*  25 */ "Jump",
20784      /*  26 */ "If",
20785      /*  27 */ "IfNot",
20786      /*  28 */ "Column",
20787      /*  29 */ "Affinity",
20788      /*  30 */ "MakeRecord",
20789      /*  31 */ "Count",
20790      /*  32 */ "Savepoint",
20791      /*  33 */ "AutoCommit",
20792      /*  34 */ "Transaction",
20793      /*  35 */ "ReadCookie",
20794      /*  36 */ "SetCookie",
20795      /*  37 */ "VerifyCookie",
20796      /*  38 */ "OpenRead",
20797      /*  39 */ "OpenWrite",
20798      /*  40 */ "OpenAutoindex",
20799      /*  41 */ "OpenEphemeral",
20800      /*  42 */ "OpenPseudo",
20801      /*  43 */ "Close",
20802      /*  44 */ "SeekLt",
20803      /*  45 */ "SeekLe",
20804      /*  46 */ "SeekGe",
20805      /*  47 */ "SeekGt",
20806      /*  48 */ "Seek",
20807      /*  49 */ "NotFound",
20808      /*  50 */ "Found",
20809      /*  51 */ "IsUnique",
20810      /*  52 */ "NotExists",
20811      /*  53 */ "Sequence",
20812      /*  54 */ "NewRowid",
20813      /*  55 */ "Insert",
20814      /*  56 */ "InsertInt",
20815      /*  57 */ "Delete",
20816      /*  58 */ "ResetCount",
20817      /*  59 */ "RowKey",
20818      /*  60 */ "RowData",
20819      /*  61 */ "Rowid",
20820      /*  62 */ "NullRow",
20821      /*  63 */ "Last",
20822      /*  64 */ "Sort",
20823      /*  65 */ "Rewind",
20824      /*  66 */ "Prev",
20825      /*  67 */ "Next",
20826      /*  68 */ "Or",
20827      /*  69 */ "And",
20828      /*  70 */ "IdxInsert",
20829      /*  71 */ "IdxDelete",
20830      /*  72 */ "IdxRowid",
20831      /*  73 */ "IsNull",
20832      /*  74 */ "NotNull",
20833      /*  75 */ "Ne",
20834      /*  76 */ "Eq",
20835      /*  77 */ "Gt",
20836      /*  78 */ "Le",
20837      /*  79 */ "Lt",
20838      /*  80 */ "Ge",
20839      /*  81 */ "IdxLT",
20840      /*  82 */ "BitAnd",
20841      /*  83 */ "BitOr",
20842      /*  84 */ "ShiftLeft",
20843      /*  85 */ "ShiftRight",
20844      /*  86 */ "Add",
20845      /*  87 */ "Subtract",
20846      /*  88 */ "Multiply",
20847      /*  89 */ "Divide",
20848      /*  90 */ "Remainder",
20849      /*  91 */ "Concat",
20850      /*  92 */ "IdxGE",
20851      /*  93 */ "BitNot",
20852      /*  94 */ "String8",
20853      /*  95 */ "Destroy",
20854      /*  96 */ "Clear",
20855      /*  97 */ "CreateIndex",
20856      /*  98 */ "CreateTable",
20857      /*  99 */ "ParseSchema",
20858      /* 100 */ "LoadAnalysis",
20859      /* 101 */ "DropTable",
20860      /* 102 */ "DropIndex",
20861      /* 103 */ "DropTrigger",
20862      /* 104 */ "IntegrityCk",
20863      /* 105 */ "RowSetAdd",
20864      /* 106 */ "RowSetRead",
20865      /* 107 */ "RowSetTest",
20866      /* 108 */ "Program",
20867      /* 109 */ "Param",
20868      /* 110 */ "FkCounter",
20869      /* 111 */ "FkIfZero",
20870      /* 112 */ "MemMax",
20871      /* 113 */ "IfPos",
20872      /* 114 */ "IfNeg",
20873      /* 115 */ "IfZero",
20874      /* 116 */ "AggStep",
20875      /* 117 */ "AggFinal",
20876      /* 118 */ "Checkpoint",
20877      /* 119 */ "JournalMode",
20878      /* 120 */ "Vacuum",
20879      /* 121 */ "IncrVacuum",
20880      /* 122 */ "Expire",
20881      /* 123 */ "TableLock",
20882      /* 124 */ "VBegin",
20883      /* 125 */ "VCreate",
20884      /* 126 */ "VDestroy",
20885      /* 127 */ "VOpen",
20886      /* 128 */ "VFilter",
20887      /* 129 */ "VColumn",
20888      /* 130 */ "Real",
20889      /* 131 */ "VNext",
20890      /* 132 */ "VRename",
20891      /* 133 */ "VUpdate",
20892      /* 134 */ "Pagecount",
20893      /* 135 */ "Trace",
20894      /* 136 */ "Noop",
20895      /* 137 */ "Explain",
20896      /* 138 */ "NotUsed_138",
20897      /* 139 */ "NotUsed_139",
20898      /* 140 */ "NotUsed_140",
20899      /* 141 */ "ToText",
20900      /* 142 */ "ToBlob",
20901      /* 143 */ "ToNumeric",
20902      /* 144 */ "ToInt",
20903      /* 145 */ "ToReal",
20904   };
20905   return azName[i];
20906 }
20907 #endif
20908
20909 /************** End of opcodes.c *********************************************/
20910 /************** Begin file os_os2.c ******************************************/
20911 /*
20912 ** 2006 Feb 14
20913 **
20914 ** The author disclaims copyright to this source code.  In place of
20915 ** a legal notice, here is a blessing:
20916 **
20917 **    May you do good and not evil.
20918 **    May you find forgiveness for yourself and forgive others.
20919 **    May you share freely, never taking more than you give.
20920 **
20921 ******************************************************************************
20922 **
20923 ** This file contains code that is specific to OS/2.
20924 */
20925
20926
20927 #if SQLITE_OS_OS2
20928
20929 /*
20930 ** A Note About Memory Allocation:
20931 **
20932 ** This driver uses malloc()/free() directly rather than going through
20933 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
20934 ** are designed for use on embedded systems where memory is scarce and
20935 ** malloc failures happen frequently.  OS/2 does not typically run on
20936 ** embedded systems, and when it does the developers normally have bigger
20937 ** problems to worry about than running out of memory.  So there is not
20938 ** a compelling need to use the wrappers.
20939 **
20940 ** But there is a good reason to not use the wrappers.  If we use the
20941 ** wrappers then we will get simulated malloc() failures within this
20942 ** driver.  And that causes all kinds of problems for our tests.  We
20943 ** could enhance SQLite to deal with simulated malloc failures within
20944 ** the OS driver, but the code to deal with those failure would not
20945 ** be exercised on Linux (which does not need to malloc() in the driver)
20946 ** and so we would have difficulty writing coverage tests for that
20947 ** code.  Better to leave the code out, we think.
20948 **
20949 ** The point of this discussion is as follows:  When creating a new
20950 ** OS layer for an embedded system, if you use this file as an example,
20951 ** avoid the use of malloc()/free().  Those routines work ok on OS/2
20952 ** desktops but not so well in embedded systems.
20953 */
20954
20955 /*
20956 ** Macros used to determine whether or not to use threads.
20957 */
20958 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE
20959 # define SQLITE_OS2_THREADS 1
20960 #endif
20961
20962 /*
20963 ** Include code that is common to all os_*.c files
20964 */
20965 /************** Include os_common.h in the middle of os_os2.c ****************/
20966 /************** Begin file os_common.h ***************************************/
20967 /*
20968 ** 2004 May 22
20969 **
20970 ** The author disclaims copyright to this source code.  In place of
20971 ** a legal notice, here is a blessing:
20972 **
20973 **    May you do good and not evil.
20974 **    May you find forgiveness for yourself and forgive others.
20975 **    May you share freely, never taking more than you give.
20976 **
20977 ******************************************************************************
20978 **
20979 ** This file contains macros and a little bit of code that is common to
20980 ** all of the platform-specific files (os_*.c) and is #included into those
20981 ** files.
20982 **
20983 ** This file should be #included by the os_*.c files only.  It is not a
20984 ** general purpose header file.
20985 */
20986 #ifndef _OS_COMMON_H_
20987 #define _OS_COMMON_H_
20988
20989 /*
20990 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
20991 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
20992 ** switch.  The following code should catch this problem at compile-time.
20993 */
20994 #ifdef MEMORY_DEBUG
20995 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
20996 #endif
20997
20998 #ifdef SQLITE_DEBUG
20999 SQLITE_PRIVATE int sqlite3OSTrace = 0;
21000 #define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
21001 #else
21002 #define OSTRACE(X)
21003 #endif
21004
21005 /*
21006 ** Macros for performance tracing.  Normally turned off.  Only works
21007 ** on i486 hardware.
21008 */
21009 #ifdef SQLITE_PERFORMANCE_TRACE
21010
21011 /* 
21012 ** hwtime.h contains inline assembler code for implementing 
21013 ** high-performance timing routines.
21014 */
21015 /************** Include hwtime.h in the middle of os_common.h ****************/
21016 /************** Begin file hwtime.h ******************************************/
21017 /*
21018 ** 2008 May 27
21019 **
21020 ** The author disclaims copyright to this source code.  In place of
21021 ** a legal notice, here is a blessing:
21022 **
21023 **    May you do good and not evil.
21024 **    May you find forgiveness for yourself and forgive others.
21025 **    May you share freely, never taking more than you give.
21026 **
21027 ******************************************************************************
21028 **
21029 ** This file contains inline asm code for retrieving "high-performance"
21030 ** counters for x86 class CPUs.
21031 */
21032 #ifndef _HWTIME_H_
21033 #define _HWTIME_H_
21034
21035 /*
21036 ** The following routine only works on pentium-class (or newer) processors.
21037 ** It uses the RDTSC opcode to read the cycle count value out of the
21038 ** processor and returns that value.  This can be used for high-res
21039 ** profiling.
21040 */
21041 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
21042       (defined(i386) || defined(__i386__) || defined(_M_IX86))
21043
21044   #if defined(__GNUC__)
21045
21046   __inline__ sqlite_uint64 sqlite3Hwtime(void){
21047      unsigned int lo, hi;
21048      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
21049      return (sqlite_uint64)hi << 32 | lo;
21050   }
21051
21052   #elif defined(_MSC_VER)
21053
21054   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
21055      __asm {
21056         rdtsc
21057         ret       ; return value at EDX:EAX
21058      }
21059   }
21060
21061   #endif
21062
21063 #elif (defined(__GNUC__) && defined(__x86_64__))
21064
21065   __inline__ sqlite_uint64 sqlite3Hwtime(void){
21066       unsigned long val;
21067       __asm__ __volatile__ ("rdtsc" : "=A" (val));
21068       return val;
21069   }
21070  
21071 #elif (defined(__GNUC__) && defined(__ppc__))
21072
21073   __inline__ sqlite_uint64 sqlite3Hwtime(void){
21074       unsigned long long retval;
21075       unsigned long junk;
21076       __asm__ __volatile__ ("\n\
21077           1:      mftbu   %1\n\
21078                   mftb    %L0\n\
21079                   mftbu   %0\n\
21080                   cmpw    %0,%1\n\
21081                   bne     1b"
21082                   : "=r" (retval), "=r" (junk));
21083       return retval;
21084   }
21085
21086 #else
21087
21088   #error Need implementation of sqlite3Hwtime() for your platform.
21089
21090   /*
21091   ** To compile without implementing sqlite3Hwtime() for your platform,
21092   ** you can remove the above #error and use the following
21093   ** stub function.  You will lose timing support for many
21094   ** of the debugging and testing utilities, but it should at
21095   ** least compile and run.
21096   */
21097 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
21098
21099 #endif
21100
21101 #endif /* !defined(_HWTIME_H_) */
21102
21103 /************** End of hwtime.h **********************************************/
21104 /************** Continuing where we left off in os_common.h ******************/
21105
21106 static sqlite_uint64 g_start;
21107 static sqlite_uint64 g_elapsed;
21108 #define TIMER_START       g_start=sqlite3Hwtime()
21109 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
21110 #define TIMER_ELAPSED     g_elapsed
21111 #else
21112 #define TIMER_START
21113 #define TIMER_END
21114 #define TIMER_ELAPSED     ((sqlite_uint64)0)
21115 #endif
21116
21117 /*
21118 ** If we compile with the SQLITE_TEST macro set, then the following block
21119 ** of code will give us the ability to simulate a disk I/O error.  This
21120 ** is used for testing the I/O recovery logic.
21121 */
21122 #ifdef SQLITE_TEST
21123 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
21124 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
21125 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
21126 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
21127 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
21128 SQLITE_API int sqlite3_diskfull_pending = 0;
21129 SQLITE_API int sqlite3_diskfull = 0;
21130 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
21131 #define SimulateIOError(CODE)  \
21132   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
21133        || sqlite3_io_error_pending-- == 1 )  \
21134               { local_ioerr(); CODE; }
21135 static void local_ioerr(){
21136   IOTRACE(("IOERR\n"));
21137   sqlite3_io_error_hit++;
21138   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
21139 }
21140 #define SimulateDiskfullError(CODE) \
21141    if( sqlite3_diskfull_pending ){ \
21142      if( sqlite3_diskfull_pending == 1 ){ \
21143        local_ioerr(); \
21144        sqlite3_diskfull = 1; \
21145        sqlite3_io_error_hit = 1; \
21146        CODE; \
21147      }else{ \
21148        sqlite3_diskfull_pending--; \
21149      } \
21150    }
21151 #else
21152 #define SimulateIOErrorBenign(X)
21153 #define SimulateIOError(A)
21154 #define SimulateDiskfullError(A)
21155 #endif
21156
21157 /*
21158 ** When testing, keep a count of the number of open files.
21159 */
21160 #ifdef SQLITE_TEST
21161 SQLITE_API int sqlite3_open_file_count = 0;
21162 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
21163 #else
21164 #define OpenCounter(X)
21165 #endif
21166
21167 #endif /* !defined(_OS_COMMON_H_) */
21168
21169 /************** End of os_common.h *******************************************/
21170 /************** Continuing where we left off in os_os2.c *********************/
21171
21172 /*
21173 ** The os2File structure is subclass of sqlite3_file specific for the OS/2
21174 ** protability layer.
21175 */
21176 typedef struct os2File os2File;
21177 struct os2File {
21178   const sqlite3_io_methods *pMethod;  /* Always the first entry */
21179   HFILE h;                  /* Handle for accessing the file */
21180   char* pathToDel;          /* Name of file to delete on close, NULL if not */
21181   unsigned char locktype;   /* Type of lock currently held on this file */
21182 };
21183
21184 #define LOCK_TIMEOUT 10L /* the default locking timeout */
21185
21186 /*****************************************************************************
21187 ** The next group of routines implement the I/O methods specified
21188 ** by the sqlite3_io_methods object.
21189 ******************************************************************************/
21190
21191 /*
21192 ** Close a file.
21193 */
21194 static int os2Close( sqlite3_file *id ){
21195   APIRET rc = NO_ERROR;
21196   os2File *pFile;
21197   if( id && (pFile = (os2File*)id) != 0 ){
21198     OSTRACE(( "CLOSE %d\n", pFile->h ));
21199     rc = DosClose( pFile->h );
21200     pFile->locktype = NO_LOCK;
21201     if( pFile->pathToDel != NULL ){
21202       rc = DosForceDelete( (PSZ)pFile->pathToDel );
21203       free( pFile->pathToDel );
21204       pFile->pathToDel = NULL;
21205     }
21206     id = 0;
21207     OpenCounter( -1 );
21208   }
21209
21210   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
21211 }
21212
21213 /*
21214 ** Read data from a file into a buffer.  Return SQLITE_OK if all
21215 ** bytes were read successfully and SQLITE_IOERR if anything goes
21216 ** wrong.
21217 */
21218 static int os2Read(
21219   sqlite3_file *id,               /* File to read from */
21220   void *pBuf,                     /* Write content into this buffer */
21221   int amt,                        /* Number of bytes to read */
21222   sqlite3_int64 offset            /* Begin reading at this offset */
21223 ){
21224   ULONG fileLocation = 0L;
21225   ULONG got;
21226   os2File *pFile = (os2File*)id;
21227   assert( id!=0 );
21228   SimulateIOError( return SQLITE_IOERR_READ );
21229   OSTRACE(( "READ %d lock=%d\n", pFile->h, pFile->locktype ));
21230   if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
21231     return SQLITE_IOERR;
21232   }
21233   if( DosRead( pFile->h, pBuf, amt, &got ) != NO_ERROR ){
21234     return SQLITE_IOERR_READ;
21235   }
21236   if( got == (ULONG)amt )
21237     return SQLITE_OK;
21238   else {
21239     /* Unread portions of the input buffer must be zero-filled */
21240     memset(&((char*)pBuf)[got], 0, amt-got);
21241     return SQLITE_IOERR_SHORT_READ;
21242   }
21243 }
21244
21245 /*
21246 ** Write data from a buffer into a file.  Return SQLITE_OK on success
21247 ** or some other error code on failure.
21248 */
21249 static int os2Write(
21250   sqlite3_file *id,               /* File to write into */
21251   const void *pBuf,               /* The bytes to be written */
21252   int amt,                        /* Number of bytes to write */
21253   sqlite3_int64 offset            /* Offset into the file to begin writing at */
21254 ){
21255   ULONG fileLocation = 0L;
21256   APIRET rc = NO_ERROR;
21257   ULONG wrote;
21258   os2File *pFile = (os2File*)id;
21259   assert( id!=0 );
21260   SimulateIOError( return SQLITE_IOERR_WRITE );
21261   SimulateDiskfullError( return SQLITE_FULL );
21262   OSTRACE(( "WRITE %d lock=%d\n", pFile->h, pFile->locktype ));
21263   if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
21264     return SQLITE_IOERR;
21265   }
21266   assert( amt>0 );
21267   while( amt > 0 &&
21268          ( rc = DosWrite( pFile->h, (PVOID)pBuf, amt, &wrote ) ) == NO_ERROR &&
21269          wrote > 0
21270   ){
21271     amt -= wrote;
21272     pBuf = &((char*)pBuf)[wrote];
21273   }
21274
21275   return ( rc != NO_ERROR || amt > (int)wrote ) ? SQLITE_FULL : SQLITE_OK;
21276 }
21277
21278 /*
21279 ** Truncate an open file to a specified size
21280 */
21281 static int os2Truncate( sqlite3_file *id, i64 nByte ){
21282   APIRET rc = NO_ERROR;
21283   os2File *pFile = (os2File*)id;
21284   OSTRACE(( "TRUNCATE %d %lld\n", pFile->h, nByte ));
21285   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
21286   rc = DosSetFileSize( pFile->h, nByte );
21287   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_TRUNCATE;
21288 }
21289
21290 #ifdef SQLITE_TEST
21291 /*
21292 ** Count the number of fullsyncs and normal syncs.  This is used to test
21293 ** that syncs and fullsyncs are occuring at the right times.
21294 */
21295 SQLITE_API int sqlite3_sync_count = 0;
21296 SQLITE_API int sqlite3_fullsync_count = 0;
21297 #endif
21298
21299 /*
21300 ** Make sure all writes to a particular file are committed to disk.
21301 */
21302 static int os2Sync( sqlite3_file *id, int flags ){
21303   os2File *pFile = (os2File*)id;
21304   OSTRACE(( "SYNC %d lock=%d\n", pFile->h, pFile->locktype ));
21305 #ifdef SQLITE_TEST
21306   if( flags & SQLITE_SYNC_FULL){
21307     sqlite3_fullsync_count++;
21308   }
21309   sqlite3_sync_count++;
21310 #endif
21311   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
21312   ** no-op
21313   */
21314 #ifdef SQLITE_NO_SYNC
21315   UNUSED_PARAMETER(pFile);
21316   return SQLITE_OK;
21317 #else
21318   return DosResetBuffer( pFile->h ) == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
21319 #endif
21320 }
21321
21322 /*
21323 ** Determine the current size of a file in bytes
21324 */
21325 static int os2FileSize( sqlite3_file *id, sqlite3_int64 *pSize ){
21326   APIRET rc = NO_ERROR;
21327   FILESTATUS3 fsts3FileInfo;
21328   memset(&fsts3FileInfo, 0, sizeof(fsts3FileInfo));
21329   assert( id!=0 );
21330   SimulateIOError( return SQLITE_IOERR_FSTAT );
21331   rc = DosQueryFileInfo( ((os2File*)id)->h, FIL_STANDARD, &fsts3FileInfo, sizeof(FILESTATUS3) );
21332   if( rc == NO_ERROR ){
21333     *pSize = fsts3FileInfo.cbFile;
21334     return SQLITE_OK;
21335   }else{
21336     return SQLITE_IOERR_FSTAT;
21337   }
21338 }
21339
21340 /*
21341 ** Acquire a reader lock.
21342 */
21343 static int getReadLock( os2File *pFile ){
21344   FILELOCK  LockArea,
21345             UnlockArea;
21346   APIRET res;
21347   memset(&LockArea, 0, sizeof(LockArea));
21348   memset(&UnlockArea, 0, sizeof(UnlockArea));
21349   LockArea.lOffset = SHARED_FIRST;
21350   LockArea.lRange = SHARED_SIZE;
21351   UnlockArea.lOffset = 0L;
21352   UnlockArea.lRange = 0L;
21353   res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
21354   OSTRACE(( "GETREADLOCK %d res=%d\n", pFile->h, res ));
21355   return res;
21356 }
21357
21358 /*
21359 ** Undo a readlock
21360 */
21361 static int unlockReadLock( os2File *id ){
21362   FILELOCK  LockArea,
21363             UnlockArea;
21364   APIRET res;
21365   memset(&LockArea, 0, sizeof(LockArea));
21366   memset(&UnlockArea, 0, sizeof(UnlockArea));
21367   LockArea.lOffset = 0L;
21368   LockArea.lRange = 0L;
21369   UnlockArea.lOffset = SHARED_FIRST;
21370   UnlockArea.lRange = SHARED_SIZE;
21371   res = DosSetFileLocks( id->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
21372   OSTRACE(( "UNLOCK-READLOCK file handle=%d res=%d?\n", id->h, res ));
21373   return res;
21374 }
21375
21376 /*
21377 ** Lock the file with the lock specified by parameter locktype - one
21378 ** of the following:
21379 **
21380 **     (1) SHARED_LOCK
21381 **     (2) RESERVED_LOCK
21382 **     (3) PENDING_LOCK
21383 **     (4) EXCLUSIVE_LOCK
21384 **
21385 ** Sometimes when requesting one lock state, additional lock states
21386 ** are inserted in between.  The locking might fail on one of the later
21387 ** transitions leaving the lock state different from what it started but
21388 ** still short of its goal.  The following chart shows the allowed
21389 ** transitions and the inserted intermediate states:
21390 **
21391 **    UNLOCKED -> SHARED
21392 **    SHARED -> RESERVED
21393 **    SHARED -> (PENDING) -> EXCLUSIVE
21394 **    RESERVED -> (PENDING) -> EXCLUSIVE
21395 **    PENDING -> EXCLUSIVE
21396 **
21397 ** This routine will only increase a lock.  The os2Unlock() routine
21398 ** erases all locks at once and returns us immediately to locking level 0.
21399 ** It is not possible to lower the locking level one step at a time.  You
21400 ** must go straight to locking level 0.
21401 */
21402 static int os2Lock( sqlite3_file *id, int locktype ){
21403   int rc = SQLITE_OK;       /* Return code from subroutines */
21404   APIRET res = NO_ERROR;    /* Result of an OS/2 lock call */
21405   int newLocktype;       /* Set pFile->locktype to this value before exiting */
21406   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
21407   FILELOCK  LockArea,
21408             UnlockArea;
21409   os2File *pFile = (os2File*)id;
21410   memset(&LockArea, 0, sizeof(LockArea));
21411   memset(&UnlockArea, 0, sizeof(UnlockArea));
21412   assert( pFile!=0 );
21413   OSTRACE(( "LOCK %d %d was %d\n", pFile->h, locktype, pFile->locktype ));
21414
21415   /* If there is already a lock of this type or more restrictive on the
21416   ** os2File, do nothing. Don't use the end_lock: exit path, as
21417   ** sqlite3_mutex_enter() hasn't been called yet.
21418   */
21419   if( pFile->locktype>=locktype ){
21420     OSTRACE(( "LOCK %d %d ok (already held)\n", pFile->h, locktype ));
21421     return SQLITE_OK;
21422   }
21423
21424   /* Make sure the locking sequence is correct
21425   */
21426   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
21427   assert( locktype!=PENDING_LOCK );
21428   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
21429
21430   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
21431   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
21432   ** the PENDING_LOCK byte is temporary.
21433   */
21434   newLocktype = pFile->locktype;
21435   if( pFile->locktype==NO_LOCK
21436       || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
21437   ){
21438     LockArea.lOffset = PENDING_BYTE;
21439     LockArea.lRange = 1L;
21440     UnlockArea.lOffset = 0L;
21441     UnlockArea.lRange = 0L;
21442
21443     /* wait longer than LOCK_TIMEOUT here not to have to try multiple times */
21444     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 100L, 0L );
21445     if( res == NO_ERROR ){
21446       gotPendingLock = 1;
21447       OSTRACE(( "LOCK %d pending lock boolean set.  res=%d\n", pFile->h, res ));
21448     }
21449   }
21450
21451   /* Acquire a shared lock
21452   */
21453   if( locktype==SHARED_LOCK && res == NO_ERROR ){
21454     assert( pFile->locktype==NO_LOCK );
21455     res = getReadLock(pFile);
21456     if( res == NO_ERROR ){
21457       newLocktype = SHARED_LOCK;
21458     }
21459     OSTRACE(( "LOCK %d acquire shared lock. res=%d\n", pFile->h, res ));
21460   }
21461
21462   /* Acquire a RESERVED lock
21463   */
21464   if( locktype==RESERVED_LOCK && res == NO_ERROR ){
21465     assert( pFile->locktype==SHARED_LOCK );
21466     LockArea.lOffset = RESERVED_BYTE;
21467     LockArea.lRange = 1L;
21468     UnlockArea.lOffset = 0L;
21469     UnlockArea.lRange = 0L;
21470     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21471     if( res == NO_ERROR ){
21472       newLocktype = RESERVED_LOCK;
21473     }
21474     OSTRACE(( "LOCK %d acquire reserved lock. res=%d\n", pFile->h, res ));
21475   }
21476
21477   /* Acquire a PENDING lock
21478   */
21479   if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
21480     newLocktype = PENDING_LOCK;
21481     gotPendingLock = 0;
21482     OSTRACE(( "LOCK %d acquire pending lock. pending lock boolean unset.\n",
21483                pFile->h ));
21484   }
21485
21486   /* Acquire an EXCLUSIVE lock
21487   */
21488   if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
21489     assert( pFile->locktype>=SHARED_LOCK );
21490     res = unlockReadLock(pFile);
21491     OSTRACE(( "unreadlock = %d\n", res ));
21492     LockArea.lOffset = SHARED_FIRST;
21493     LockArea.lRange = SHARED_SIZE;
21494     UnlockArea.lOffset = 0L;
21495     UnlockArea.lRange = 0L;
21496     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21497     if( res == NO_ERROR ){
21498       newLocktype = EXCLUSIVE_LOCK;
21499     }else{
21500       OSTRACE(( "OS/2 error-code = %d\n", res ));
21501       getReadLock(pFile);
21502     }
21503     OSTRACE(( "LOCK %d acquire exclusive lock.  res=%d\n", pFile->h, res ));
21504   }
21505
21506   /* If we are holding a PENDING lock that ought to be released, then
21507   ** release it now.
21508   */
21509   if( gotPendingLock && locktype==SHARED_LOCK ){
21510     int r;
21511     LockArea.lOffset = 0L;
21512     LockArea.lRange = 0L;
21513     UnlockArea.lOffset = PENDING_BYTE;
21514     UnlockArea.lRange = 1L;
21515     r = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21516     OSTRACE(( "LOCK %d unlocking pending/is shared. r=%d\n", pFile->h, r ));
21517   }
21518
21519   /* Update the state of the lock has held in the file descriptor then
21520   ** return the appropriate result code.
21521   */
21522   if( res == NO_ERROR ){
21523     rc = SQLITE_OK;
21524   }else{
21525     OSTRACE(( "LOCK FAILED %d trying for %d but got %d\n", pFile->h,
21526               locktype, newLocktype ));
21527     rc = SQLITE_BUSY;
21528   }
21529   pFile->locktype = newLocktype;
21530   OSTRACE(( "LOCK %d now %d\n", pFile->h, pFile->locktype ));
21531   return rc;
21532 }
21533
21534 /*
21535 ** This routine checks if there is a RESERVED lock held on the specified
21536 ** file by this or any other process. If such a lock is held, return
21537 ** non-zero, otherwise zero.
21538 */
21539 static int os2CheckReservedLock( sqlite3_file *id, int *pOut ){
21540   int r = 0;
21541   os2File *pFile = (os2File*)id;
21542   assert( pFile!=0 );
21543   if( pFile->locktype>=RESERVED_LOCK ){
21544     r = 1;
21545     OSTRACE(( "TEST WR-LOCK %d %d (local)\n", pFile->h, r ));
21546   }else{
21547     FILELOCK  LockArea,
21548               UnlockArea;
21549     APIRET rc = NO_ERROR;
21550     memset(&LockArea, 0, sizeof(LockArea));
21551     memset(&UnlockArea, 0, sizeof(UnlockArea));
21552     LockArea.lOffset = RESERVED_BYTE;
21553     LockArea.lRange = 1L;
21554     UnlockArea.lOffset = 0L;
21555     UnlockArea.lRange = 0L;
21556     rc = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21557     OSTRACE(( "TEST WR-LOCK %d lock reserved byte rc=%d\n", pFile->h, rc ));
21558     if( rc == NO_ERROR ){
21559       APIRET rcu = NO_ERROR; /* return code for unlocking */
21560       LockArea.lOffset = 0L;
21561       LockArea.lRange = 0L;
21562       UnlockArea.lOffset = RESERVED_BYTE;
21563       UnlockArea.lRange = 1L;
21564       rcu = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21565       OSTRACE(( "TEST WR-LOCK %d unlock reserved byte r=%d\n", pFile->h, rcu ));
21566     }
21567     r = !(rc == NO_ERROR);
21568     OSTRACE(( "TEST WR-LOCK %d %d (remote)\n", pFile->h, r ));
21569   }
21570   *pOut = r;
21571   return SQLITE_OK;
21572 }
21573
21574 /*
21575 ** Lower the locking level on file descriptor id to locktype.  locktype
21576 ** must be either NO_LOCK or SHARED_LOCK.
21577 **
21578 ** If the locking level of the file descriptor is already at or below
21579 ** the requested locking level, this routine is a no-op.
21580 **
21581 ** It is not possible for this routine to fail if the second argument
21582 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
21583 ** might return SQLITE_IOERR;
21584 */
21585 static int os2Unlock( sqlite3_file *id, int locktype ){
21586   int type;
21587   os2File *pFile = (os2File*)id;
21588   APIRET rc = SQLITE_OK;
21589   APIRET res = NO_ERROR;
21590   FILELOCK  LockArea,
21591             UnlockArea;
21592   memset(&LockArea, 0, sizeof(LockArea));
21593   memset(&UnlockArea, 0, sizeof(UnlockArea));
21594   assert( pFile!=0 );
21595   assert( locktype<=SHARED_LOCK );
21596   OSTRACE(( "UNLOCK %d to %d was %d\n", pFile->h, locktype, pFile->locktype ));
21597   type = pFile->locktype;
21598   if( type>=EXCLUSIVE_LOCK ){
21599     LockArea.lOffset = 0L;
21600     LockArea.lRange = 0L;
21601     UnlockArea.lOffset = SHARED_FIRST;
21602     UnlockArea.lRange = SHARED_SIZE;
21603     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21604     OSTRACE(( "UNLOCK %d exclusive lock res=%d\n", pFile->h, res ));
21605     if( locktype==SHARED_LOCK && getReadLock(pFile) != NO_ERROR ){
21606       /* This should never happen.  We should always be able to
21607       ** reacquire the read lock */
21608       OSTRACE(( "UNLOCK %d to %d getReadLock() failed\n", pFile->h, locktype ));
21609       rc = SQLITE_IOERR_UNLOCK;
21610     }
21611   }
21612   if( type>=RESERVED_LOCK ){
21613     LockArea.lOffset = 0L;
21614     LockArea.lRange = 0L;
21615     UnlockArea.lOffset = RESERVED_BYTE;
21616     UnlockArea.lRange = 1L;
21617     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21618     OSTRACE(( "UNLOCK %d reserved res=%d\n", pFile->h, res ));
21619   }
21620   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
21621     res = unlockReadLock(pFile);
21622     OSTRACE(( "UNLOCK %d is %d want %d res=%d\n",
21623               pFile->h, type, locktype, res ));
21624   }
21625   if( type>=PENDING_LOCK ){
21626     LockArea.lOffset = 0L;
21627     LockArea.lRange = 0L;
21628     UnlockArea.lOffset = PENDING_BYTE;
21629     UnlockArea.lRange = 1L;
21630     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21631     OSTRACE(( "UNLOCK %d pending res=%d\n", pFile->h, res ));
21632   }
21633   pFile->locktype = locktype;
21634   OSTRACE(( "UNLOCK %d now %d\n", pFile->h, pFile->locktype ));
21635   return rc;
21636 }
21637
21638 /*
21639 ** Control and query of the open file handle.
21640 */
21641 static int os2FileControl(sqlite3_file *id, int op, void *pArg){
21642   switch( op ){
21643     case SQLITE_FCNTL_LOCKSTATE: {
21644       *(int*)pArg = ((os2File*)id)->locktype;
21645       OSTRACE(( "FCNTL_LOCKSTATE %d lock=%d\n",
21646                 ((os2File*)id)->h, ((os2File*)id)->locktype ));
21647       return SQLITE_OK;
21648     }
21649   }
21650   return SQLITE_ERROR;
21651 }
21652
21653 /*
21654 ** Return the sector size in bytes of the underlying block device for
21655 ** the specified file. This is almost always 512 bytes, but may be
21656 ** larger for some devices.
21657 **
21658 ** SQLite code assumes this function cannot fail. It also assumes that
21659 ** if two files are created in the same file-system directory (i.e.
21660 ** a database and its journal file) that the sector size will be the
21661 ** same for both.
21662 */
21663 static int os2SectorSize(sqlite3_file *id){
21664   return SQLITE_DEFAULT_SECTOR_SIZE;
21665 }
21666
21667 /*
21668 ** Return a vector of device characteristics.
21669 */
21670 static int os2DeviceCharacteristics(sqlite3_file *id){
21671   return 0;
21672 }
21673
21674
21675 /*
21676 ** Character set conversion objects used by conversion routines.
21677 */
21678 static UconvObject ucUtf8 = NULL; /* convert between UTF-8 and UCS-2 */
21679 static UconvObject uclCp = NULL;  /* convert between local codepage and UCS-2 */
21680
21681 /*
21682 ** Helper function to initialize the conversion objects from and to UTF-8.
21683 */
21684 static void initUconvObjects( void ){
21685   if( UniCreateUconvObject( UTF_8, &ucUtf8 ) != ULS_SUCCESS )
21686     ucUtf8 = NULL;
21687   if ( UniCreateUconvObject( (UniChar *)L"@path=yes", &uclCp ) != ULS_SUCCESS )
21688     uclCp = NULL;
21689 }
21690
21691 /*
21692 ** Helper function to free the conversion objects from and to UTF-8.
21693 */
21694 static void freeUconvObjects( void ){
21695   if ( ucUtf8 )
21696     UniFreeUconvObject( ucUtf8 );
21697   if ( uclCp )
21698     UniFreeUconvObject( uclCp );
21699   ucUtf8 = NULL;
21700   uclCp = NULL;
21701 }
21702
21703 /*
21704 ** Helper function to convert UTF-8 filenames to local OS/2 codepage.
21705 ** The two-step process: first convert the incoming UTF-8 string
21706 ** into UCS-2 and then from UCS-2 to the current codepage.
21707 ** The returned char pointer has to be freed.
21708 */
21709 static char *convertUtf8PathToCp( const char *in ){
21710   UniChar tempPath[CCHMAXPATH];
21711   char *out = (char *)calloc( CCHMAXPATH, 1 );
21712
21713   if( !out )
21714     return NULL;
21715
21716   if( !ucUtf8 || !uclCp )
21717     initUconvObjects();
21718
21719   /* determine string for the conversion of UTF-8 which is CP1208 */
21720   if( UniStrToUcs( ucUtf8, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
21721     return out; /* if conversion fails, return the empty string */
21722
21723   /* conversion for current codepage which can be used for paths */
21724   UniStrFromUcs( uclCp, out, tempPath, CCHMAXPATH );
21725
21726   return out;
21727 }
21728
21729 /*
21730 ** Helper function to convert filenames from local codepage to UTF-8.
21731 ** The two-step process: first convert the incoming codepage-specific
21732 ** string into UCS-2 and then from UCS-2 to the codepage of UTF-8.
21733 ** The returned char pointer has to be freed.
21734 **
21735 ** This function is non-static to be able to use this in shell.c and
21736 ** similar applications that take command line arguments.
21737 */
21738 char *convertCpPathToUtf8( const char *in ){
21739   UniChar tempPath[CCHMAXPATH];
21740   char *out = (char *)calloc( CCHMAXPATH, 1 );
21741
21742   if( !out )
21743     return NULL;
21744
21745   if( !ucUtf8 || !uclCp )
21746     initUconvObjects();
21747
21748   /* conversion for current codepage which can be used for paths */
21749   if( UniStrToUcs( uclCp, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
21750     return out; /* if conversion fails, return the empty string */
21751
21752   /* determine string for the conversion of UTF-8 which is CP1208 */
21753   UniStrFromUcs( ucUtf8, out, tempPath, CCHMAXPATH );
21754
21755   return out;
21756 }
21757
21758 /*
21759 ** This vector defines all the methods that can operate on an
21760 ** sqlite3_file for os2.
21761 */
21762 static const sqlite3_io_methods os2IoMethod = {
21763   1,                        /* iVersion */
21764   os2Close,
21765   os2Read,
21766   os2Write,
21767   os2Truncate,
21768   os2Sync,
21769   os2FileSize,
21770   os2Lock,
21771   os2Unlock,
21772   os2CheckReservedLock,
21773   os2FileControl,
21774   os2SectorSize,
21775   os2DeviceCharacteristics
21776 };
21777
21778 /***************************************************************************
21779 ** Here ends the I/O methods that form the sqlite3_io_methods object.
21780 **
21781 ** The next block of code implements the VFS methods.
21782 ****************************************************************************/
21783
21784 /*
21785 ** Create a temporary file name in zBuf.  zBuf must be big enough to
21786 ** hold at pVfs->mxPathname characters.
21787 */
21788 static int getTempname(int nBuf, char *zBuf ){
21789   static const unsigned char zChars[] =
21790     "abcdefghijklmnopqrstuvwxyz"
21791     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
21792     "0123456789";
21793   int i, j;
21794   char zTempPathBuf[3];
21795   PSZ zTempPath = (PSZ)&zTempPathBuf;
21796   if( sqlite3_temp_directory ){
21797     zTempPath = sqlite3_temp_directory;
21798   }else{
21799     if( DosScanEnv( (PSZ)"TEMP", &zTempPath ) ){
21800       if( DosScanEnv( (PSZ)"TMP", &zTempPath ) ){
21801         if( DosScanEnv( (PSZ)"TMPDIR", &zTempPath ) ){
21802            ULONG ulDriveNum = 0, ulDriveMap = 0;
21803            DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap );
21804            sprintf( (char*)zTempPath, "%c:", (char)( 'A' + ulDriveNum - 1 ) );
21805         }
21806       }
21807     }
21808   }
21809   /* Strip off a trailing slashes or backslashes, otherwise we would get *
21810    * multiple (back)slashes which causes DosOpen() to fail.              *
21811    * Trailing spaces are not allowed, either.                            */
21812   j = sqlite3Strlen30(zTempPath);
21813   while( j > 0 && ( zTempPath[j-1] == '\\' || zTempPath[j-1] == '/'
21814                     || zTempPath[j-1] == ' ' ) ){
21815     j--;
21816   }
21817   zTempPath[j] = '\0';
21818   if( !sqlite3_temp_directory ){
21819     char *zTempPathUTF = convertCpPathToUtf8( zTempPath );
21820     sqlite3_snprintf( nBuf-30, zBuf,
21821                       "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPathUTF );
21822     free( zTempPathUTF );
21823   }else{
21824     sqlite3_snprintf( nBuf-30, zBuf,
21825                       "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath );
21826   }
21827   j = sqlite3Strlen30( zBuf );
21828   sqlite3_randomness( 20, &zBuf[j] );
21829   for( i = 0; i < 20; i++, j++ ){
21830     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
21831   }
21832   zBuf[j] = 0;
21833   OSTRACE(( "TEMP FILENAME: %s\n", zBuf ));
21834   return SQLITE_OK;
21835 }
21836
21837
21838 /*
21839 ** Turn a relative pathname into a full pathname.  Write the full
21840 ** pathname into zFull[].  zFull[] will be at least pVfs->mxPathname
21841 ** bytes in size.
21842 */
21843 static int os2FullPathname(
21844   sqlite3_vfs *pVfs,          /* Pointer to vfs object */
21845   const char *zRelative,      /* Possibly relative input path */
21846   int nFull,                  /* Size of output buffer in bytes */
21847   char *zFull                 /* Output buffer */
21848 ){
21849   char *zRelativeCp = convertUtf8PathToCp( zRelative );
21850   char zFullCp[CCHMAXPATH] = "\0";
21851   char *zFullUTF;
21852   APIRET rc = DosQueryPathInfo( zRelativeCp, FIL_QUERYFULLNAME, zFullCp,
21853                                 CCHMAXPATH );
21854   free( zRelativeCp );
21855   zFullUTF = convertCpPathToUtf8( zFullCp );
21856   sqlite3_snprintf( nFull, zFull, zFullUTF );
21857   free( zFullUTF );
21858   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
21859 }
21860
21861
21862 /*
21863 ** Open a file.
21864 */
21865 static int os2Open(
21866   sqlite3_vfs *pVfs,            /* Not used */
21867   const char *zName,            /* Name of the file */
21868   sqlite3_file *id,             /* Write the SQLite file handle here */
21869   int flags,                    /* Open mode flags */
21870   int *pOutFlags                /* Status return flags */
21871 ){
21872   HFILE h;
21873   ULONG ulFileAttribute = FILE_NORMAL;
21874   ULONG ulOpenFlags = 0;
21875   ULONG ulOpenMode = 0;
21876   os2File *pFile = (os2File*)id;
21877   APIRET rc = NO_ERROR;
21878   ULONG ulAction;
21879   char *zNameCp;
21880   char zTmpname[CCHMAXPATH+1];    /* Buffer to hold name of temp file */
21881
21882   /* If the second argument to this function is NULL, generate a 
21883   ** temporary file name to use 
21884   */
21885   if( !zName ){
21886     int rc = getTempname(CCHMAXPATH+1, zTmpname);
21887     if( rc!=SQLITE_OK ){
21888       return rc;
21889     }
21890     zName = zTmpname;
21891   }
21892
21893
21894   memset( pFile, 0, sizeof(*pFile) );
21895
21896   OSTRACE( "OPEN want %d\n", flags ));
21897
21898   if( flags & SQLITE_OPEN_READWRITE ){
21899     ulOpenMode |= OPEN_ACCESS_READWRITE;
21900     OSTRACE(( "OPEN read/write\n" ));
21901   }else{
21902     ulOpenMode |= OPEN_ACCESS_READONLY;
21903     OSTRACE(( "OPEN read only\n" ));
21904   }
21905
21906   if( flags & SQLITE_OPEN_CREATE ){
21907     ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW;
21908     OSTRACE(( "OPEN open new/create\n" ));
21909   }else{
21910     ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_FAIL_IF_NEW;
21911     OSTRACE(( "OPEN open existing\n" ));
21912   }
21913
21914   if( flags & SQLITE_OPEN_MAIN_DB ){
21915     ulOpenMode |= OPEN_SHARE_DENYNONE;
21916     OSTRACE(( "OPEN share read/write\n" ));
21917   }else{
21918     ulOpenMode |= OPEN_SHARE_DENYWRITE;
21919     OSTRACE(( "OPEN share read only\n" ));
21920   }
21921
21922   if( flags & SQLITE_OPEN_DELETEONCLOSE ){
21923     char pathUtf8[CCHMAXPATH];
21924 #ifdef NDEBUG /* when debugging we want to make sure it is deleted */
21925     ulFileAttribute = FILE_HIDDEN;
21926 #endif
21927     os2FullPathname( pVfs, zName, CCHMAXPATH, pathUtf8 );
21928     pFile->pathToDel = convertUtf8PathToCp( pathUtf8 );
21929     OSTRACE(( "OPEN hidden/delete on close file attributes\n" ));
21930   }else{
21931     pFile->pathToDel = NULL;
21932     OSTRACE(( "OPEN normal file attribute\n" ));
21933   }
21934
21935   /* always open in random access mode for possibly better speed */
21936   ulOpenMode |= OPEN_FLAGS_RANDOM;
21937   ulOpenMode |= OPEN_FLAGS_FAIL_ON_ERROR;
21938   ulOpenMode |= OPEN_FLAGS_NOINHERIT;
21939
21940   zNameCp = convertUtf8PathToCp( zName );
21941   rc = DosOpen( (PSZ)zNameCp,
21942                 &h,
21943                 &ulAction,
21944                 0L,
21945                 ulFileAttribute,
21946                 ulOpenFlags,
21947                 ulOpenMode,
21948                 (PEAOP2)NULL );
21949   free( zNameCp );
21950   if( rc != NO_ERROR ){
21951     OSTRACE(( "OPEN Invalid handle rc=%d: zName=%s, ulAction=%#lx, ulAttr=%#lx, ulFlags=%#lx, ulMode=%#lx\n",
21952               rc, zName, ulAction, ulFileAttribute, ulOpenFlags, ulOpenMode ));
21953     if( pFile->pathToDel )
21954       free( pFile->pathToDel );
21955     pFile->pathToDel = NULL;
21956     if( flags & SQLITE_OPEN_READWRITE ){
21957       OSTRACE(( "OPEN %d Invalid handle\n",
21958                 ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE) ));
21959       return os2Open( pVfs, zName, id,
21960                       ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE),
21961                       pOutFlags );
21962     }else{
21963       return SQLITE_CANTOPEN;
21964     }
21965   }
21966
21967   if( pOutFlags ){
21968     *pOutFlags = flags & SQLITE_OPEN_READWRITE ? SQLITE_OPEN_READWRITE : SQLITE_OPEN_READONLY;
21969   }
21970
21971   pFile->pMethod = &os2IoMethod;
21972   pFile->h = h;
21973   OpenCounter(+1);
21974   OSTRACE(( "OPEN %d pOutFlags=%d\n", pFile->h, pOutFlags ));
21975   return SQLITE_OK;
21976 }
21977
21978 /*
21979 ** Delete the named file.
21980 */
21981 static int os2Delete(
21982   sqlite3_vfs *pVfs,                     /* Not used on os2 */
21983   const char *zFilename,                 /* Name of file to delete */
21984   int syncDir                            /* Not used on os2 */
21985 ){
21986   APIRET rc = NO_ERROR;
21987   char *zFilenameCp = convertUtf8PathToCp( zFilename );
21988   SimulateIOError( return SQLITE_IOERR_DELETE );
21989   rc = DosDelete( (PSZ)zFilenameCp );
21990   free( zFilenameCp );
21991   OSTRACE(( "DELETE \"%s\"\n", zFilename ));
21992   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_DELETE;
21993 }
21994
21995 /*
21996 ** Check the existance and status of a file.
21997 */
21998 static int os2Access(
21999   sqlite3_vfs *pVfs,        /* Not used on os2 */
22000   const char *zFilename,    /* Name of file to check */
22001   int flags,                /* Type of test to make on this file */
22002   int *pOut                 /* Write results here */
22003 ){
22004   FILESTATUS3 fsts3ConfigInfo;
22005   APIRET rc = NO_ERROR;
22006   char *zFilenameCp = convertUtf8PathToCp( zFilename );
22007
22008   memset( &fsts3ConfigInfo, 0, sizeof(fsts3ConfigInfo) );
22009   rc = DosQueryPathInfo( (PSZ)zFilenameCp, FIL_STANDARD,
22010                          &fsts3ConfigInfo, sizeof(FILESTATUS3) );
22011   free( zFilenameCp );
22012   OSTRACE(( "ACCESS fsts3ConfigInfo.attrFile=%d flags=%d rc=%d\n",
22013             fsts3ConfigInfo.attrFile, flags, rc ));
22014   switch( flags ){
22015     case SQLITE_ACCESS_READ:
22016     case SQLITE_ACCESS_EXISTS:
22017       rc = (rc == NO_ERROR);
22018       OSTRACE(( "ACCESS %s access of read and exists  rc=%d\n", zFilename, rc));
22019       break;
22020     case SQLITE_ACCESS_READWRITE:
22021       rc = (rc == NO_ERROR) && ( (fsts3ConfigInfo.attrFile & FILE_READONLY) == 0 );
22022       OSTRACE(( "ACCESS %s access of read/write  rc=%d\n", zFilename, rc ));
22023       break;
22024     default:
22025       assert( !"Invalid flags argument" );
22026   }
22027   *pOut = rc;
22028   return SQLITE_OK;
22029 }
22030
22031
22032 #ifndef SQLITE_OMIT_LOAD_EXTENSION
22033 /*
22034 ** Interfaces for opening a shared library, finding entry points
22035 ** within the shared library, and closing the shared library.
22036 */
22037 /*
22038 ** Interfaces for opening a shared library, finding entry points
22039 ** within the shared library, and closing the shared library.
22040 */
22041 static void *os2DlOpen(sqlite3_vfs *pVfs, const char *zFilename){
22042   UCHAR loadErr[256];
22043   HMODULE hmod;
22044   APIRET rc;
22045   char *zFilenameCp = convertUtf8PathToCp(zFilename);
22046   rc = DosLoadModule((PSZ)loadErr, sizeof(loadErr), zFilenameCp, &hmod);
22047   free(zFilenameCp);
22048   return rc != NO_ERROR ? 0 : (void*)hmod;
22049 }
22050 /*
22051 ** A no-op since the error code is returned on the DosLoadModule call.
22052 ** os2Dlopen returns zero if DosLoadModule is not successful.
22053 */
22054 static void os2DlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
22055 /* no-op */
22056 }
22057 static void *os2DlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
22058   PFN pfn;
22059   APIRET rc;
22060   rc = DosQueryProcAddr((HMODULE)pHandle, 0L, zSymbol, &pfn);
22061   if( rc != NO_ERROR ){
22062     /* if the symbol itself was not found, search again for the same
22063      * symbol with an extra underscore, that might be needed depending
22064      * on the calling convention */
22065     char _zSymbol[256] = "_";
22066     strncat(_zSymbol, zSymbol, 255);
22067     rc = DosQueryProcAddr((HMODULE)pHandle, 0L, _zSymbol, &pfn);
22068   }
22069   return rc != NO_ERROR ? 0 : (void*)pfn;
22070 }
22071 static void os2DlClose(sqlite3_vfs *pVfs, void *pHandle){
22072   DosFreeModule((HMODULE)pHandle);
22073 }
22074 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
22075   #define os2DlOpen 0
22076   #define os2DlError 0
22077   #define os2DlSym 0
22078   #define os2DlClose 0
22079 #endif
22080
22081
22082 /*
22083 ** Write up to nBuf bytes of randomness into zBuf.
22084 */
22085 static int os2Randomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf ){
22086   int n = 0;
22087 #if defined(SQLITE_TEST)
22088   n = nBuf;
22089   memset(zBuf, 0, nBuf);
22090 #else
22091   int sizeofULong = sizeof(ULONG);
22092   if( (int)sizeof(DATETIME) <= nBuf - n ){
22093     DATETIME x;
22094     DosGetDateTime(&x);
22095     memcpy(&zBuf[n], &x, sizeof(x));
22096     n += sizeof(x);
22097   }
22098
22099   if( sizeofULong <= nBuf - n ){
22100     PPIB ppib;
22101     DosGetInfoBlocks(NULL, &ppib);
22102     memcpy(&zBuf[n], &ppib->pib_ulpid, sizeofULong);
22103     n += sizeofULong;
22104   }
22105
22106   if( sizeofULong <= nBuf - n ){
22107     PTIB ptib;
22108     DosGetInfoBlocks(&ptib, NULL);
22109     memcpy(&zBuf[n], &ptib->tib_ptib2->tib2_ultid, sizeofULong);
22110     n += sizeofULong;
22111   }
22112
22113   /* if we still haven't filled the buffer yet the following will */
22114   /* grab everything once instead of making several calls for a single item */
22115   if( sizeofULong <= nBuf - n ){
22116     ULONG ulSysInfo[QSV_MAX];
22117     DosQuerySysInfo(1L, QSV_MAX, ulSysInfo, sizeofULong * QSV_MAX);
22118
22119     memcpy(&zBuf[n], &ulSysInfo[QSV_MS_COUNT - 1], sizeofULong);
22120     n += sizeofULong;
22121
22122     if( sizeofULong <= nBuf - n ){
22123       memcpy(&zBuf[n], &ulSysInfo[QSV_TIMER_INTERVAL - 1], sizeofULong);
22124       n += sizeofULong;
22125     }
22126     if( sizeofULong <= nBuf - n ){
22127       memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_LOW - 1], sizeofULong);
22128       n += sizeofULong;
22129     }
22130     if( sizeofULong <= nBuf - n ){
22131       memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_HIGH - 1], sizeofULong);
22132       n += sizeofULong;
22133     }
22134     if( sizeofULong <= nBuf - n ){
22135       memcpy(&zBuf[n], &ulSysInfo[QSV_TOTAVAILMEM - 1], sizeofULong);
22136       n += sizeofULong;
22137     }
22138   }
22139 #endif
22140
22141   return n;
22142 }
22143
22144 /*
22145 ** Sleep for a little while.  Return the amount of time slept.
22146 ** The argument is the number of microseconds we want to sleep.
22147 ** The return value is the number of microseconds of sleep actually
22148 ** requested from the underlying operating system, a number which
22149 ** might be greater than or equal to the argument, but not less
22150 ** than the argument.
22151 */
22152 static int os2Sleep( sqlite3_vfs *pVfs, int microsec ){
22153   DosSleep( (microsec/1000) );
22154   return microsec;
22155 }
22156
22157 /*
22158 ** The following variable, if set to a non-zero value, becomes the result
22159 ** returned from sqlite3OsCurrentTime().  This is used for testing.
22160 */
22161 #ifdef SQLITE_TEST
22162 SQLITE_API int sqlite3_current_time = 0;
22163 #endif
22164
22165 /*
22166 ** Find the current time (in Universal Coordinated Time).  Write the
22167 ** current time and date as a Julian Day number into *prNow and
22168 ** return 0.  Return 1 if the time and date cannot be found.
22169 */
22170 int os2CurrentTime( sqlite3_vfs *pVfs, double *prNow ){
22171   double now;
22172   SHORT minute; /* needs to be able to cope with negative timezone offset */
22173   USHORT second, hour,
22174          day, month, year;
22175   DATETIME dt;
22176   DosGetDateTime( &dt );
22177   second = (USHORT)dt.seconds;
22178   minute = (SHORT)dt.minutes + dt.timezone;
22179   hour = (USHORT)dt.hours;
22180   day = (USHORT)dt.day;
22181   month = (USHORT)dt.month;
22182   year = (USHORT)dt.year;
22183
22184   /* Calculations from http://www.astro.keele.ac.uk/~rno/Astronomy/hjd.html
22185      http://www.astro.keele.ac.uk/~rno/Astronomy/hjd-0.1.c */
22186   /* Calculate the Julian days */
22187   now = day - 32076 +
22188     1461*(year + 4800 + (month - 14)/12)/4 +
22189     367*(month - 2 - (month - 14)/12*12)/12 -
22190     3*((year + 4900 + (month - 14)/12)/100)/4;
22191
22192   /* Add the fractional hours, mins and seconds */
22193   now += (hour + 12.0)/24.0;
22194   now += minute/1440.0;
22195   now += second/86400.0;
22196   *prNow = now;
22197 #ifdef SQLITE_TEST
22198   if( sqlite3_current_time ){
22199     *prNow = sqlite3_current_time/86400.0 + 2440587.5;
22200   }
22201 #endif
22202   return 0;
22203 }
22204
22205 static int os2GetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
22206   return 0;
22207 }
22208
22209 /*
22210 ** Initialize and deinitialize the operating system interface.
22211 */
22212 SQLITE_API int sqlite3_os_init(void){
22213   static sqlite3_vfs os2Vfs = {
22214     1,                 /* iVersion */
22215     sizeof(os2File),   /* szOsFile */
22216     CCHMAXPATH,        /* mxPathname */
22217     0,                 /* pNext */
22218     "os2",             /* zName */
22219     0,                 /* pAppData */
22220
22221     os2Open,           /* xOpen */
22222     os2Delete,         /* xDelete */
22223     os2Access,         /* xAccess */
22224     os2FullPathname,   /* xFullPathname */
22225     os2DlOpen,         /* xDlOpen */
22226     os2DlError,        /* xDlError */
22227     os2DlSym,          /* xDlSym */
22228     os2DlClose,        /* xDlClose */
22229     os2Randomness,     /* xRandomness */
22230     os2Sleep,          /* xSleep */
22231     os2CurrentTime,    /* xCurrentTime */
22232     os2GetLastError,   /* xGetLastError */
22233   };
22234   sqlite3_vfs_register(&os2Vfs, 1);
22235   initUconvObjects();
22236   return SQLITE_OK;
22237 }
22238 SQLITE_API int sqlite3_os_end(void){
22239   freeUconvObjects();
22240   return SQLITE_OK;
22241 }
22242
22243 #endif /* SQLITE_OS_OS2 */
22244
22245 /************** End of os_os2.c **********************************************/
22246 /************** Begin file os_unix.c *****************************************/
22247 /*
22248 ** 2004 May 22
22249 **
22250 ** The author disclaims copyright to this source code.  In place of
22251 ** a legal notice, here is a blessing:
22252 **
22253 **    May you do good and not evil.
22254 **    May you find forgiveness for yourself and forgive others.
22255 **    May you share freely, never taking more than you give.
22256 **
22257 ******************************************************************************
22258 **
22259 ** This file contains the VFS implementation for unix-like operating systems
22260 ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
22261 **
22262 ** There are actually several different VFS implementations in this file.
22263 ** The differences are in the way that file locking is done.  The default
22264 ** implementation uses Posix Advisory Locks.  Alternative implementations
22265 ** use flock(), dot-files, various proprietary locking schemas, or simply
22266 ** skip locking all together.
22267 **
22268 ** This source file is organized into divisions where the logic for various
22269 ** subfunctions is contained within the appropriate division.  PLEASE
22270 ** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
22271 ** in the correct division and should be clearly labeled.
22272 **
22273 ** The layout of divisions is as follows:
22274 **
22275 **   *  General-purpose declarations and utility functions.
22276 **   *  Unique file ID logic used by VxWorks.
22277 **   *  Various locking primitive implementations (all except proxy locking):
22278 **      + for Posix Advisory Locks
22279 **      + for no-op locks
22280 **      + for dot-file locks
22281 **      + for flock() locking
22282 **      + for named semaphore locks (VxWorks only)
22283 **      + for AFP filesystem locks (MacOSX only)
22284 **   *  sqlite3_file methods not associated with locking.
22285 **   *  Definitions of sqlite3_io_methods objects for all locking
22286 **      methods plus "finder" functions for each locking method.
22287 **   *  sqlite3_vfs method implementations.
22288 **   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
22289 **   *  Definitions of sqlite3_vfs objects for all locking methods
22290 **      plus implementations of sqlite3_os_init() and sqlite3_os_end().
22291 */
22292 #if SQLITE_OS_UNIX              /* This file is used on unix only */
22293
22294 /*
22295 ** There are various methods for file locking used for concurrency
22296 ** control:
22297 **
22298 **   1. POSIX locking (the default),
22299 **   2. No locking,
22300 **   3. Dot-file locking,
22301 **   4. flock() locking,
22302 **   5. AFP locking (OSX only),
22303 **   6. Named POSIX semaphores (VXWorks only),
22304 **   7. proxy locking. (OSX only)
22305 **
22306 ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
22307 ** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
22308 ** selection of the appropriate locking style based on the filesystem
22309 ** where the database is located.  
22310 */
22311 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
22312 #  if defined(__APPLE__)
22313 #    define SQLITE_ENABLE_LOCKING_STYLE 1
22314 #  else
22315 #    define SQLITE_ENABLE_LOCKING_STYLE 0
22316 #  endif
22317 #endif
22318
22319 /*
22320 ** Define the OS_VXWORKS pre-processor macro to 1 if building on 
22321 ** vxworks, or 0 otherwise.
22322 */
22323 #ifndef OS_VXWORKS
22324 #  if defined(__RTP__) || defined(_WRS_KERNEL)
22325 #    define OS_VXWORKS 1
22326 #  else
22327 #    define OS_VXWORKS 0
22328 #  endif
22329 #endif
22330
22331 /*
22332 ** These #defines should enable >2GB file support on Posix if the
22333 ** underlying operating system supports it.  If the OS lacks
22334 ** large file support, these should be no-ops.
22335 **
22336 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
22337 ** on the compiler command line.  This is necessary if you are compiling
22338 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
22339 ** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
22340 ** without this option, LFS is enable.  But LFS does not exist in the kernel
22341 ** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
22342 ** portability you should omit LFS.
22343 **
22344 ** The previous paragraph was written in 2005.  (This paragraph is written
22345 ** on 2008-11-28.) These days, all Linux kernels support large files, so
22346 ** you should probably leave LFS enabled.  But some embedded platforms might
22347 ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
22348 */
22349 #ifndef SQLITE_DISABLE_LFS
22350 # define _LARGE_FILE       1
22351 # ifndef _FILE_OFFSET_BITS
22352 #   define _FILE_OFFSET_BITS 64
22353 # endif
22354 # define _LARGEFILE_SOURCE 1
22355 #endif
22356
22357 /*
22358 ** standard include files.
22359 */
22360 #include <sys/types.h>
22361 #include <sys/stat.h>
22362 #include <fcntl.h>
22363 #include <unistd.h>
22364 #include <sys/time.h>
22365 #include <errno.h>
22366 #include <sys/mman.h>
22367
22368 #if SQLITE_ENABLE_LOCKING_STYLE
22369 # include <sys/ioctl.h>
22370 # if OS_VXWORKS
22371 #  include <semaphore.h>
22372 #  include <limits.h>
22373 # else
22374 #  include <sys/file.h>
22375 #  include <sys/param.h>
22376 # endif
22377 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
22378
22379 #if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
22380 # include <sys/mount.h>
22381 #endif
22382
22383 /*
22384 ** Allowed values of unixFile.fsFlags
22385 */
22386 #define SQLITE_FSFLAGS_IS_MSDOS     0x1
22387
22388 /*
22389 ** If we are to be thread-safe, include the pthreads header and define
22390 ** the SQLITE_UNIX_THREADS macro.
22391 */
22392 #if SQLITE_THREADSAFE
22393 # define SQLITE_UNIX_THREADS 1
22394 #endif
22395
22396 /*
22397 ** Default permissions when creating a new file
22398 */
22399 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
22400 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
22401 #endif
22402
22403 /*
22404  ** Default permissions when creating auto proxy dir
22405  */
22406 #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
22407 # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
22408 #endif
22409
22410 /*
22411 ** Maximum supported path-length.
22412 */
22413 #define MAX_PATHNAME 512
22414
22415 /*
22416 ** Only set the lastErrno if the error code is a real error and not 
22417 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
22418 */
22419 #define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
22420
22421 /* Forward references */
22422 typedef struct unixShm unixShm;               /* Connection shared memory */
22423 typedef struct unixShmNode unixShmNode;       /* Shared memory instance */
22424 typedef struct unixInodeInfo unixInodeInfo;   /* An i-node */
22425 typedef struct UnixUnusedFd UnixUnusedFd;     /* An unused file descriptor */
22426
22427 /*
22428 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
22429 ** cannot be closed immediately. In these cases, instances of the following
22430 ** structure are used to store the file descriptor while waiting for an
22431 ** opportunity to either close or reuse it.
22432 */
22433 struct UnixUnusedFd {
22434   int fd;                   /* File descriptor to close */
22435   int flags;                /* Flags this file descriptor was opened with */
22436   UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
22437 };
22438
22439 /*
22440 ** The unixFile structure is subclass of sqlite3_file specific to the unix
22441 ** VFS implementations.
22442 */
22443 typedef struct unixFile unixFile;
22444 struct unixFile {
22445   sqlite3_io_methods const *pMethod;  /* Always the first entry */
22446   unixInodeInfo *pInode;              /* Info about locks on this inode */
22447   int h;                              /* The file descriptor */
22448   int dirfd;                          /* File descriptor for the directory */
22449   unsigned char eFileLock;            /* The type of lock held on this fd */
22450   int lastErrno;                      /* The unix errno from last I/O error */
22451   void *lockingContext;               /* Locking style specific state */
22452   UnixUnusedFd *pUnused;              /* Pre-allocated UnixUnusedFd */
22453   int fileFlags;                      /* Miscellanous flags */
22454   const char *zPath;                  /* Name of the file */
22455   unixShm *pShm;                      /* Shared memory segment information */
22456 #if SQLITE_ENABLE_LOCKING_STYLE
22457   int openFlags;                      /* The flags specified at open() */
22458 #endif
22459 #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
22460   unsigned fsFlags;                   /* cached details from statfs() */
22461 #endif
22462 #if OS_VXWORKS
22463   int isDelete;                       /* Delete on close if true */
22464   struct vxworksFileId *pId;          /* Unique file ID */
22465 #endif
22466 #ifndef NDEBUG
22467   /* The next group of variables are used to track whether or not the
22468   ** transaction counter in bytes 24-27 of database files are updated
22469   ** whenever any part of the database changes.  An assertion fault will
22470   ** occur if a file is updated without also updating the transaction
22471   ** counter.  This test is made to avoid new problems similar to the
22472   ** one described by ticket #3584. 
22473   */
22474   unsigned char transCntrChng;   /* True if the transaction counter changed */
22475   unsigned char dbUpdate;        /* True if any part of database file changed */
22476   unsigned char inNormalWrite;   /* True if in a normal write operation */
22477 #endif
22478 #ifdef SQLITE_TEST
22479   /* In test mode, increase the size of this structure a bit so that 
22480   ** it is larger than the struct CrashFile defined in test6.c.
22481   */
22482   char aPadding[32];
22483 #endif
22484 };
22485
22486 /*
22487 ** The following macros define bits in unixFile.fileFlags
22488 */
22489 #define SQLITE_WHOLE_FILE_LOCKING  0x0001   /* Use whole-file locking */
22490
22491 /*
22492 ** Include code that is common to all os_*.c files
22493 */
22494 /************** Include os_common.h in the middle of os_unix.c ***************/
22495 /************** Begin file os_common.h ***************************************/
22496 /*
22497 ** 2004 May 22
22498 **
22499 ** The author disclaims copyright to this source code.  In place of
22500 ** a legal notice, here is a blessing:
22501 **
22502 **    May you do good and not evil.
22503 **    May you find forgiveness for yourself and forgive others.
22504 **    May you share freely, never taking more than you give.
22505 **
22506 ******************************************************************************
22507 **
22508 ** This file contains macros and a little bit of code that is common to
22509 ** all of the platform-specific files (os_*.c) and is #included into those
22510 ** files.
22511 **
22512 ** This file should be #included by the os_*.c files only.  It is not a
22513 ** general purpose header file.
22514 */
22515 #ifndef _OS_COMMON_H_
22516 #define _OS_COMMON_H_
22517
22518 /*
22519 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
22520 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
22521 ** switch.  The following code should catch this problem at compile-time.
22522 */
22523 #ifdef MEMORY_DEBUG
22524 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
22525 #endif
22526
22527 #ifdef SQLITE_DEBUG
22528 SQLITE_PRIVATE int sqlite3OSTrace = 0;
22529 #define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
22530 #else
22531 #define OSTRACE(X)
22532 #endif
22533
22534 /*
22535 ** Macros for performance tracing.  Normally turned off.  Only works
22536 ** on i486 hardware.
22537 */
22538 #ifdef SQLITE_PERFORMANCE_TRACE
22539
22540 /* 
22541 ** hwtime.h contains inline assembler code for implementing 
22542 ** high-performance timing routines.
22543 */
22544 /************** Include hwtime.h in the middle of os_common.h ****************/
22545 /************** Begin file hwtime.h ******************************************/
22546 /*
22547 ** 2008 May 27
22548 **
22549 ** The author disclaims copyright to this source code.  In place of
22550 ** a legal notice, here is a blessing:
22551 **
22552 **    May you do good and not evil.
22553 **    May you find forgiveness for yourself and forgive others.
22554 **    May you share freely, never taking more than you give.
22555 **
22556 ******************************************************************************
22557 **
22558 ** This file contains inline asm code for retrieving "high-performance"
22559 ** counters for x86 class CPUs.
22560 */
22561 #ifndef _HWTIME_H_
22562 #define _HWTIME_H_
22563
22564 /*
22565 ** The following routine only works on pentium-class (or newer) processors.
22566 ** It uses the RDTSC opcode to read the cycle count value out of the
22567 ** processor and returns that value.  This can be used for high-res
22568 ** profiling.
22569 */
22570 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
22571       (defined(i386) || defined(__i386__) || defined(_M_IX86))
22572
22573   #if defined(__GNUC__)
22574
22575   __inline__ sqlite_uint64 sqlite3Hwtime(void){
22576      unsigned int lo, hi;
22577      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
22578      return (sqlite_uint64)hi << 32 | lo;
22579   }
22580
22581   #elif defined(_MSC_VER)
22582
22583   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
22584      __asm {
22585         rdtsc
22586         ret       ; return value at EDX:EAX
22587      }
22588   }
22589
22590   #endif
22591
22592 #elif (defined(__GNUC__) && defined(__x86_64__))
22593
22594   __inline__ sqlite_uint64 sqlite3Hwtime(void){
22595       unsigned long val;
22596       __asm__ __volatile__ ("rdtsc" : "=A" (val));
22597       return val;
22598   }
22599  
22600 #elif (defined(__GNUC__) && defined(__ppc__))
22601
22602   __inline__ sqlite_uint64 sqlite3Hwtime(void){
22603       unsigned long long retval;
22604       unsigned long junk;
22605       __asm__ __volatile__ ("\n\
22606           1:      mftbu   %1\n\
22607                   mftb    %L0\n\
22608                   mftbu   %0\n\
22609                   cmpw    %0,%1\n\
22610                   bne     1b"
22611                   : "=r" (retval), "=r" (junk));
22612       return retval;
22613   }
22614
22615 #else
22616
22617   #error Need implementation of sqlite3Hwtime() for your platform.
22618
22619   /*
22620   ** To compile without implementing sqlite3Hwtime() for your platform,
22621   ** you can remove the above #error and use the following
22622   ** stub function.  You will lose timing support for many
22623   ** of the debugging and testing utilities, but it should at
22624   ** least compile and run.
22625   */
22626 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
22627
22628 #endif
22629
22630 #endif /* !defined(_HWTIME_H_) */
22631
22632 /************** End of hwtime.h **********************************************/
22633 /************** Continuing where we left off in os_common.h ******************/
22634
22635 static sqlite_uint64 g_start;
22636 static sqlite_uint64 g_elapsed;
22637 #define TIMER_START       g_start=sqlite3Hwtime()
22638 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
22639 #define TIMER_ELAPSED     g_elapsed
22640 #else
22641 #define TIMER_START
22642 #define TIMER_END
22643 #define TIMER_ELAPSED     ((sqlite_uint64)0)
22644 #endif
22645
22646 /*
22647 ** If we compile with the SQLITE_TEST macro set, then the following block
22648 ** of code will give us the ability to simulate a disk I/O error.  This
22649 ** is used for testing the I/O recovery logic.
22650 */
22651 #ifdef SQLITE_TEST
22652 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
22653 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
22654 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
22655 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
22656 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
22657 SQLITE_API int sqlite3_diskfull_pending = 0;
22658 SQLITE_API int sqlite3_diskfull = 0;
22659 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
22660 #define SimulateIOError(CODE)  \
22661   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
22662        || sqlite3_io_error_pending-- == 1 )  \
22663               { local_ioerr(); CODE; }
22664 static void local_ioerr(){
22665   IOTRACE(("IOERR\n"));
22666   sqlite3_io_error_hit++;
22667   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
22668 }
22669 #define SimulateDiskfullError(CODE) \
22670    if( sqlite3_diskfull_pending ){ \
22671      if( sqlite3_diskfull_pending == 1 ){ \
22672        local_ioerr(); \
22673        sqlite3_diskfull = 1; \
22674        sqlite3_io_error_hit = 1; \
22675        CODE; \
22676      }else{ \
22677        sqlite3_diskfull_pending--; \
22678      } \
22679    }
22680 #else
22681 #define SimulateIOErrorBenign(X)
22682 #define SimulateIOError(A)
22683 #define SimulateDiskfullError(A)
22684 #endif
22685
22686 /*
22687 ** When testing, keep a count of the number of open files.
22688 */
22689 #ifdef SQLITE_TEST
22690 SQLITE_API int sqlite3_open_file_count = 0;
22691 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
22692 #else
22693 #define OpenCounter(X)
22694 #endif
22695
22696 #endif /* !defined(_OS_COMMON_H_) */
22697
22698 /************** End of os_common.h *******************************************/
22699 /************** Continuing where we left off in os_unix.c ********************/
22700
22701 /*
22702 ** Define various macros that are missing from some systems.
22703 */
22704 #ifndef O_LARGEFILE
22705 # define O_LARGEFILE 0
22706 #endif
22707 #ifdef SQLITE_DISABLE_LFS
22708 # undef O_LARGEFILE
22709 # define O_LARGEFILE 0
22710 #endif
22711 #ifndef O_NOFOLLOW
22712 # define O_NOFOLLOW 0
22713 #endif
22714 #ifndef O_BINARY
22715 # define O_BINARY 0
22716 #endif
22717
22718 /*
22719 ** The DJGPP compiler environment looks mostly like Unix, but it
22720 ** lacks the fcntl() system call.  So redefine fcntl() to be something
22721 ** that always succeeds.  This means that locking does not occur under
22722 ** DJGPP.  But it is DOS - what did you expect?
22723 */
22724 #ifdef __DJGPP__
22725 # define fcntl(A,B,C) 0
22726 #endif
22727
22728 /*
22729 ** The threadid macro resolves to the thread-id or to 0.  Used for
22730 ** testing and debugging only.
22731 */
22732 #if SQLITE_THREADSAFE
22733 #define threadid pthread_self()
22734 #else
22735 #define threadid 0
22736 #endif
22737
22738
22739 /*
22740 ** Helper functions to obtain and relinquish the global mutex. The
22741 ** global mutex is used to protect the unixInodeInfo and
22742 ** vxworksFileId objects used by this file, all of which may be 
22743 ** shared by multiple threads.
22744 **
22745 ** Function unixMutexHeld() is used to assert() that the global mutex 
22746 ** is held when required. This function is only used as part of assert() 
22747 ** statements. e.g.
22748 **
22749 **   unixEnterMutex()
22750 **     assert( unixMutexHeld() );
22751 **   unixEnterLeave()
22752 */
22753 static void unixEnterMutex(void){
22754   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
22755 }
22756 static void unixLeaveMutex(void){
22757   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
22758 }
22759 #ifdef SQLITE_DEBUG
22760 static int unixMutexHeld(void) {
22761   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
22762 }
22763 #endif
22764
22765
22766 #ifdef SQLITE_DEBUG
22767 /*
22768 ** Helper function for printing out trace information from debugging
22769 ** binaries. This returns the string represetation of the supplied
22770 ** integer lock-type.
22771 */
22772 static const char *azFileLock(int eFileLock){
22773   switch( eFileLock ){
22774     case NO_LOCK: return "NONE";
22775     case SHARED_LOCK: return "SHARED";
22776     case RESERVED_LOCK: return "RESERVED";
22777     case PENDING_LOCK: return "PENDING";
22778     case EXCLUSIVE_LOCK: return "EXCLUSIVE";
22779   }
22780   return "ERROR";
22781 }
22782 #endif
22783
22784 #ifdef SQLITE_LOCK_TRACE
22785 /*
22786 ** Print out information about all locking operations.
22787 **
22788 ** This routine is used for troubleshooting locks on multithreaded
22789 ** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
22790 ** command-line option on the compiler.  This code is normally
22791 ** turned off.
22792 */
22793 static int lockTrace(int fd, int op, struct flock *p){
22794   char *zOpName, *zType;
22795   int s;
22796   int savedErrno;
22797   if( op==F_GETLK ){
22798     zOpName = "GETLK";
22799   }else if( op==F_SETLK ){
22800     zOpName = "SETLK";
22801   }else{
22802     s = fcntl(fd, op, p);
22803     sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
22804     return s;
22805   }
22806   if( p->l_type==F_RDLCK ){
22807     zType = "RDLCK";
22808   }else if( p->l_type==F_WRLCK ){
22809     zType = "WRLCK";
22810   }else if( p->l_type==F_UNLCK ){
22811     zType = "UNLCK";
22812   }else{
22813     assert( 0 );
22814   }
22815   assert( p->l_whence==SEEK_SET );
22816   s = fcntl(fd, op, p);
22817   savedErrno = errno;
22818   sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
22819      threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
22820      (int)p->l_pid, s);
22821   if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
22822     struct flock l2;
22823     l2 = *p;
22824     fcntl(fd, F_GETLK, &l2);
22825     if( l2.l_type==F_RDLCK ){
22826       zType = "RDLCK";
22827     }else if( l2.l_type==F_WRLCK ){
22828       zType = "WRLCK";
22829     }else if( l2.l_type==F_UNLCK ){
22830       zType = "UNLCK";
22831     }else{
22832       assert( 0 );
22833     }
22834     sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
22835        zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
22836   }
22837   errno = savedErrno;
22838   return s;
22839 }
22840 #define fcntl lockTrace
22841 #endif /* SQLITE_LOCK_TRACE */
22842
22843
22844
22845 /*
22846 ** This routine translates a standard POSIX errno code into something
22847 ** useful to the clients of the sqlite3 functions.  Specifically, it is
22848 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
22849 ** and a variety of "please close the file descriptor NOW" errors into 
22850 ** SQLITE_IOERR
22851 ** 
22852 ** Errors during initialization of locks, or file system support for locks,
22853 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
22854 */
22855 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
22856   switch (posixError) {
22857   case 0: 
22858     return SQLITE_OK;
22859     
22860   case EAGAIN:
22861   case ETIMEDOUT:
22862   case EBUSY:
22863   case EINTR:
22864   case ENOLCK:  
22865     /* random NFS retry error, unless during file system support 
22866      * introspection, in which it actually means what it says */
22867     return SQLITE_BUSY;
22868     
22869   case EACCES: 
22870     /* EACCES is like EAGAIN during locking operations, but not any other time*/
22871     if( (sqliteIOErr == SQLITE_IOERR_LOCK) || 
22872         (sqliteIOErr == SQLITE_IOERR_UNLOCK) || 
22873         (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
22874         (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
22875       return SQLITE_BUSY;
22876     }
22877     /* else fall through */
22878   case EPERM: 
22879     return SQLITE_PERM;
22880     
22881   case EDEADLK:
22882     return SQLITE_IOERR_BLOCKED;
22883     
22884 #if EOPNOTSUPP!=ENOTSUP
22885   case EOPNOTSUPP: 
22886     /* something went terribly awry, unless during file system support 
22887      * introspection, in which it actually means what it says */
22888 #endif
22889 #ifdef ENOTSUP
22890   case ENOTSUP: 
22891     /* invalid fd, unless during file system support introspection, in which 
22892      * it actually means what it says */
22893 #endif
22894   case EIO:
22895   case EBADF:
22896   case EINVAL:
22897   case ENOTCONN:
22898   case ENODEV:
22899   case ENXIO:
22900   case ENOENT:
22901   case ESTALE:
22902   case ENOSYS:
22903     /* these should force the client to close the file and reconnect */
22904     
22905   default: 
22906     return sqliteIOErr;
22907   }
22908 }
22909
22910
22911
22912 /******************************************************************************
22913 ****************** Begin Unique File ID Utility Used By VxWorks ***************
22914 **
22915 ** On most versions of unix, we can get a unique ID for a file by concatenating
22916 ** the device number and the inode number.  But this does not work on VxWorks.
22917 ** On VxWorks, a unique file id must be based on the canonical filename.
22918 **
22919 ** A pointer to an instance of the following structure can be used as a
22920 ** unique file ID in VxWorks.  Each instance of this structure contains
22921 ** a copy of the canonical filename.  There is also a reference count.  
22922 ** The structure is reclaimed when the number of pointers to it drops to
22923 ** zero.
22924 **
22925 ** There are never very many files open at one time and lookups are not
22926 ** a performance-critical path, so it is sufficient to put these
22927 ** structures on a linked list.
22928 */
22929 struct vxworksFileId {
22930   struct vxworksFileId *pNext;  /* Next in a list of them all */
22931   int nRef;                     /* Number of references to this one */
22932   int nName;                    /* Length of the zCanonicalName[] string */
22933   char *zCanonicalName;         /* Canonical filename */
22934 };
22935
22936 #if OS_VXWORKS
22937 /* 
22938 ** All unique filenames are held on a linked list headed by this
22939 ** variable:
22940 */
22941 static struct vxworksFileId *vxworksFileList = 0;
22942
22943 /*
22944 ** Simplify a filename into its canonical form
22945 ** by making the following changes:
22946 **
22947 **  * removing any trailing and duplicate /
22948 **  * convert /./ into just /
22949 **  * convert /A/../ where A is any simple name into just /
22950 **
22951 ** Changes are made in-place.  Return the new name length.
22952 **
22953 ** The original filename is in z[0..n-1].  Return the number of
22954 ** characters in the simplified name.
22955 */
22956 static int vxworksSimplifyName(char *z, int n){
22957   int i, j;
22958   while( n>1 && z[n-1]=='/' ){ n--; }
22959   for(i=j=0; i<n; i++){
22960     if( z[i]=='/' ){
22961       if( z[i+1]=='/' ) continue;
22962       if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
22963         i += 1;
22964         continue;
22965       }
22966       if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
22967         while( j>0 && z[j-1]!='/' ){ j--; }
22968         if( j>0 ){ j--; }
22969         i += 2;
22970         continue;
22971       }
22972     }
22973     z[j++] = z[i];
22974   }
22975   z[j] = 0;
22976   return j;
22977 }
22978
22979 /*
22980 ** Find a unique file ID for the given absolute pathname.  Return
22981 ** a pointer to the vxworksFileId object.  This pointer is the unique
22982 ** file ID.
22983 **
22984 ** The nRef field of the vxworksFileId object is incremented before
22985 ** the object is returned.  A new vxworksFileId object is created
22986 ** and added to the global list if necessary.
22987 **
22988 ** If a memory allocation error occurs, return NULL.
22989 */
22990 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
22991   struct vxworksFileId *pNew;         /* search key and new file ID */
22992   struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
22993   int n;                              /* Length of zAbsoluteName string */
22994
22995   assert( zAbsoluteName[0]=='/' );
22996   n = (int)strlen(zAbsoluteName);
22997   pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
22998   if( pNew==0 ) return 0;
22999   pNew->zCanonicalName = (char*)&pNew[1];
23000   memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
23001   n = vxworksSimplifyName(pNew->zCanonicalName, n);
23002
23003   /* Search for an existing entry that matching the canonical name.
23004   ** If found, increment the reference count and return a pointer to
23005   ** the existing file ID.
23006   */
23007   unixEnterMutex();
23008   for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
23009     if( pCandidate->nName==n 
23010      && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
23011     ){
23012        sqlite3_free(pNew);
23013        pCandidate->nRef++;
23014        unixLeaveMutex();
23015        return pCandidate;
23016     }
23017   }
23018
23019   /* No match was found.  We will make a new file ID */
23020   pNew->nRef = 1;
23021   pNew->nName = n;
23022   pNew->pNext = vxworksFileList;
23023   vxworksFileList = pNew;
23024   unixLeaveMutex();
23025   return pNew;
23026 }
23027
23028 /*
23029 ** Decrement the reference count on a vxworksFileId object.  Free
23030 ** the object when the reference count reaches zero.
23031 */
23032 static void vxworksReleaseFileId(struct vxworksFileId *pId){
23033   unixEnterMutex();
23034   assert( pId->nRef>0 );
23035   pId->nRef--;
23036   if( pId->nRef==0 ){
23037     struct vxworksFileId **pp;
23038     for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
23039     assert( *pp==pId );
23040     *pp = pId->pNext;
23041     sqlite3_free(pId);
23042   }
23043   unixLeaveMutex();
23044 }
23045 #endif /* OS_VXWORKS */
23046 /*************** End of Unique File ID Utility Used By VxWorks ****************
23047 ******************************************************************************/
23048
23049
23050 /******************************************************************************
23051 *************************** Posix Advisory Locking ****************************
23052 **
23053 ** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
23054 ** section 6.5.2.2 lines 483 through 490 specify that when a process
23055 ** sets or clears a lock, that operation overrides any prior locks set
23056 ** by the same process.  It does not explicitly say so, but this implies
23057 ** that it overrides locks set by the same process using a different
23058 ** file descriptor.  Consider this test case:
23059 **
23060 **       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
23061 **       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
23062 **
23063 ** Suppose ./file1 and ./file2 are really the same file (because
23064 ** one is a hard or symbolic link to the other) then if you set
23065 ** an exclusive lock on fd1, then try to get an exclusive lock
23066 ** on fd2, it works.  I would have expected the second lock to
23067 ** fail since there was already a lock on the file due to fd1.
23068 ** But not so.  Since both locks came from the same process, the
23069 ** second overrides the first, even though they were on different
23070 ** file descriptors opened on different file names.
23071 **
23072 ** This means that we cannot use POSIX locks to synchronize file access
23073 ** among competing threads of the same process.  POSIX locks will work fine
23074 ** to synchronize access for threads in separate processes, but not
23075 ** threads within the same process.
23076 **
23077 ** To work around the problem, SQLite has to manage file locks internally
23078 ** on its own.  Whenever a new database is opened, we have to find the
23079 ** specific inode of the database file (the inode is determined by the
23080 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
23081 ** and check for locks already existing on that inode.  When locks are
23082 ** created or removed, we have to look at our own internal record of the
23083 ** locks to see if another thread has previously set a lock on that same
23084 ** inode.
23085 **
23086 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
23087 ** For VxWorks, we have to use the alternative unique ID system based on
23088 ** canonical filename and implemented in the previous division.)
23089 **
23090 ** The sqlite3_file structure for POSIX is no longer just an integer file
23091 ** descriptor.  It is now a structure that holds the integer file
23092 ** descriptor and a pointer to a structure that describes the internal
23093 ** locks on the corresponding inode.  There is one locking structure
23094 ** per inode, so if the same inode is opened twice, both unixFile structures
23095 ** point to the same locking structure.  The locking structure keeps
23096 ** a reference count (so we will know when to delete it) and a "cnt"
23097 ** field that tells us its internal lock status.  cnt==0 means the
23098 ** file is unlocked.  cnt==-1 means the file has an exclusive lock.
23099 ** cnt>0 means there are cnt shared locks on the file.
23100 **
23101 ** Any attempt to lock or unlock a file first checks the locking
23102 ** structure.  The fcntl() system call is only invoked to set a 
23103 ** POSIX lock if the internal lock structure transitions between
23104 ** a locked and an unlocked state.
23105 **
23106 ** But wait:  there are yet more problems with POSIX advisory locks.
23107 **
23108 ** If you close a file descriptor that points to a file that has locks,
23109 ** all locks on that file that are owned by the current process are
23110 ** released.  To work around this problem, each unixInodeInfo object
23111 ** maintains a count of the number of pending locks on tha inode.
23112 ** When an attempt is made to close an unixFile, if there are
23113 ** other unixFile open on the same inode that are holding locks, the call
23114 ** to close() the file descriptor is deferred until all of the locks clear.
23115 ** The unixInodeInfo structure keeps a list of file descriptors that need to
23116 ** be closed and that list is walked (and cleared) when the last lock
23117 ** clears.
23118 **
23119 ** Yet another problem:  LinuxThreads do not play well with posix locks.
23120 **
23121 ** Many older versions of linux use the LinuxThreads library which is
23122 ** not posix compliant.  Under LinuxThreads, a lock created by thread
23123 ** A cannot be modified or overridden by a different thread B.
23124 ** Only thread A can modify the lock.  Locking behavior is correct
23125 ** if the appliation uses the newer Native Posix Thread Library (NPTL)
23126 ** on linux - with NPTL a lock created by thread A can override locks
23127 ** in thread B.  But there is no way to know at compile-time which
23128 ** threading library is being used.  So there is no way to know at
23129 ** compile-time whether or not thread A can override locks on thread B.
23130 ** One has to do a run-time check to discover the behavior of the
23131 ** current process.
23132 **
23133 ** SQLite used to support LinuxThreads.  But support for LinuxThreads
23134 ** was dropped beginning with version 3.7.0.  SQLite will still work with
23135 ** LinuxThreads provided that (1) there is no more than one connection 
23136 ** per database file in the same process and (2) database connections
23137 ** do not move across threads.
23138 */
23139
23140 /*
23141 ** An instance of the following structure serves as the key used
23142 ** to locate a particular unixInodeInfo object.
23143 */
23144 struct unixFileId {
23145   dev_t dev;                  /* Device number */
23146 #if OS_VXWORKS
23147   struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
23148 #else
23149   ino_t ino;                  /* Inode number */
23150 #endif
23151 };
23152
23153 /*
23154 ** An instance of the following structure is allocated for each open
23155 ** inode.  Or, on LinuxThreads, there is one of these structures for
23156 ** each inode opened by each thread.
23157 **
23158 ** A single inode can have multiple file descriptors, so each unixFile
23159 ** structure contains a pointer to an instance of this object and this
23160 ** object keeps a count of the number of unixFile pointing to it.
23161 */
23162 struct unixInodeInfo {
23163   struct unixFileId fileId;       /* The lookup key */
23164   int nShared;                    /* Number of SHARED locks held */
23165   int eFileLock;                  /* One of SHARED_LOCK, RESERVED_LOCK etc. */
23166   int nRef;                       /* Number of pointers to this structure */
23167   unixShmNode *pShmNode;          /* Shared memory associated with this inode */
23168   int nLock;                      /* Number of outstanding file locks */
23169   UnixUnusedFd *pUnused;          /* Unused file descriptors to close */
23170   unixInodeInfo *pNext;           /* List of all unixInodeInfo objects */
23171   unixInodeInfo *pPrev;           /*    .... doubly linked */
23172 #if defined(SQLITE_ENABLE_LOCKING_STYLE)
23173   unsigned long long sharedByte;  /* for AFP simulated shared lock */
23174 #endif
23175 #if OS_VXWORKS
23176   sem_t *pSem;                    /* Named POSIX semaphore */
23177   char aSemName[MAX_PATHNAME+2];  /* Name of that semaphore */
23178 #endif
23179 };
23180
23181 /*
23182 ** A lists of all unixInodeInfo objects.
23183 */
23184 static unixInodeInfo *inodeList = 0;
23185
23186 /*
23187 ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
23188 ** If all such file descriptors are closed without error, the list is
23189 ** cleared and SQLITE_OK returned.
23190 **
23191 ** Otherwise, if an error occurs, then successfully closed file descriptor
23192 ** entries are removed from the list, and SQLITE_IOERR_CLOSE returned. 
23193 ** not deleted and SQLITE_IOERR_CLOSE returned.
23194 */ 
23195 static int closePendingFds(unixFile *pFile){
23196   int rc = SQLITE_OK;
23197   unixInodeInfo *pInode = pFile->pInode;
23198   UnixUnusedFd *pError = 0;
23199   UnixUnusedFd *p;
23200   UnixUnusedFd *pNext;
23201   for(p=pInode->pUnused; p; p=pNext){
23202     pNext = p->pNext;
23203     if( close(p->fd) ){
23204       pFile->lastErrno = errno;
23205       rc = SQLITE_IOERR_CLOSE;
23206       p->pNext = pError;
23207       pError = p;
23208     }else{
23209       sqlite3_free(p);
23210     }
23211   }
23212   pInode->pUnused = pError;
23213   return rc;
23214 }
23215
23216 /*
23217 ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
23218 **
23219 ** The mutex entered using the unixEnterMutex() function must be held
23220 ** when this function is called.
23221 */
23222 static void releaseInodeInfo(unixFile *pFile){
23223   unixInodeInfo *pInode = pFile->pInode;
23224   assert( unixMutexHeld() );
23225   if( pInode ){
23226     pInode->nRef--;
23227     if( pInode->nRef==0 ){
23228       assert( pInode->pShmNode==0 );
23229       closePendingFds(pFile);
23230       if( pInode->pPrev ){
23231         assert( pInode->pPrev->pNext==pInode );
23232         pInode->pPrev->pNext = pInode->pNext;
23233       }else{
23234         assert( inodeList==pInode );
23235         inodeList = pInode->pNext;
23236       }
23237       if( pInode->pNext ){
23238         assert( pInode->pNext->pPrev==pInode );
23239         pInode->pNext->pPrev = pInode->pPrev;
23240       }
23241       sqlite3_free(pInode);
23242     }
23243   }
23244 }
23245
23246 /*
23247 ** Given a file descriptor, locate the unixInodeInfo object that
23248 ** describes that file descriptor.  Create a new one if necessary.  The
23249 ** return value might be uninitialized if an error occurs.
23250 **
23251 ** The mutex entered using the unixEnterMutex() function must be held
23252 ** when this function is called.
23253 **
23254 ** Return an appropriate error code.
23255 */
23256 static int findInodeInfo(
23257   unixFile *pFile,               /* Unix file with file desc used in the key */
23258   unixInodeInfo **ppInode        /* Return the unixInodeInfo object here */
23259 ){
23260   int rc;                        /* System call return code */
23261   int fd;                        /* The file descriptor for pFile */
23262   struct unixFileId fileId;      /* Lookup key for the unixInodeInfo */
23263   struct stat statbuf;           /* Low-level file information */
23264   unixInodeInfo *pInode = 0;     /* Candidate unixInodeInfo object */
23265
23266   assert( unixMutexHeld() );
23267
23268   /* Get low-level information about the file that we can used to
23269   ** create a unique name for the file.
23270   */
23271   fd = pFile->h;
23272   rc = fstat(fd, &statbuf);
23273   if( rc!=0 ){
23274     pFile->lastErrno = errno;
23275 #ifdef EOVERFLOW
23276     if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
23277 #endif
23278     return SQLITE_IOERR;
23279   }
23280
23281 #ifdef __APPLE__
23282   /* On OS X on an msdos filesystem, the inode number is reported
23283   ** incorrectly for zero-size files.  See ticket #3260.  To work
23284   ** around this problem (we consider it a bug in OS X, not SQLite)
23285   ** we always increase the file size to 1 by writing a single byte
23286   ** prior to accessing the inode number.  The one byte written is
23287   ** an ASCII 'S' character which also happens to be the first byte
23288   ** in the header of every SQLite database.  In this way, if there
23289   ** is a race condition such that another thread has already populated
23290   ** the first page of the database, no damage is done.
23291   */
23292   if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
23293     rc = write(fd, "S", 1);
23294     if( rc!=1 ){
23295       pFile->lastErrno = errno;
23296       return SQLITE_IOERR;
23297     }
23298     rc = fstat(fd, &statbuf);
23299     if( rc!=0 ){
23300       pFile->lastErrno = errno;
23301       return SQLITE_IOERR;
23302     }
23303   }
23304 #endif
23305
23306   memset(&fileId, 0, sizeof(fileId));
23307   fileId.dev = statbuf.st_dev;
23308 #if OS_VXWORKS
23309   fileId.pId = pFile->pId;
23310 #else
23311   fileId.ino = statbuf.st_ino;
23312 #endif
23313   pInode = inodeList;
23314   while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
23315     pInode = pInode->pNext;
23316   }
23317   if( pInode==0 ){
23318     pInode = sqlite3_malloc( sizeof(*pInode) );
23319     if( pInode==0 ){
23320       return SQLITE_NOMEM;
23321     }
23322     memset(pInode, 0, sizeof(*pInode));
23323     memcpy(&pInode->fileId, &fileId, sizeof(fileId));
23324     pInode->nRef = 1;
23325     pInode->pNext = inodeList;
23326     pInode->pPrev = 0;
23327     if( inodeList ) inodeList->pPrev = pInode;
23328     inodeList = pInode;
23329   }else{
23330     pInode->nRef++;
23331   }
23332   *ppInode = pInode;
23333   return SQLITE_OK;
23334 }
23335
23336
23337 /*
23338 ** This routine checks if there is a RESERVED lock held on the specified
23339 ** file by this or any other process. If such a lock is held, set *pResOut
23340 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
23341 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
23342 */
23343 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
23344   int rc = SQLITE_OK;
23345   int reserved = 0;
23346   unixFile *pFile = (unixFile*)id;
23347
23348   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
23349
23350   assert( pFile );
23351   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
23352
23353   /* Check if a thread in this process holds such a lock */
23354   if( pFile->pInode->eFileLock>SHARED_LOCK ){
23355     reserved = 1;
23356   }
23357
23358   /* Otherwise see if some other process holds it.
23359   */
23360 #ifndef __DJGPP__
23361   if( !reserved ){
23362     struct flock lock;
23363     lock.l_whence = SEEK_SET;
23364     lock.l_start = RESERVED_BYTE;
23365     lock.l_len = 1;
23366     lock.l_type = F_WRLCK;
23367     if (-1 == fcntl(pFile->h, F_GETLK, &lock)) {
23368       int tErrno = errno;
23369       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
23370       pFile->lastErrno = tErrno;
23371     } else if( lock.l_type!=F_UNLCK ){
23372       reserved = 1;
23373     }
23374   }
23375 #endif
23376   
23377   unixLeaveMutex();
23378   OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
23379
23380   *pResOut = reserved;
23381   return rc;
23382 }
23383
23384 /*
23385 ** Lock the file with the lock specified by parameter eFileLock - one
23386 ** of the following:
23387 **
23388 **     (1) SHARED_LOCK
23389 **     (2) RESERVED_LOCK
23390 **     (3) PENDING_LOCK
23391 **     (4) EXCLUSIVE_LOCK
23392 **
23393 ** Sometimes when requesting one lock state, additional lock states
23394 ** are inserted in between.  The locking might fail on one of the later
23395 ** transitions leaving the lock state different from what it started but
23396 ** still short of its goal.  The following chart shows the allowed
23397 ** transitions and the inserted intermediate states:
23398 **
23399 **    UNLOCKED -> SHARED
23400 **    SHARED -> RESERVED
23401 **    SHARED -> (PENDING) -> EXCLUSIVE
23402 **    RESERVED -> (PENDING) -> EXCLUSIVE
23403 **    PENDING -> EXCLUSIVE
23404 **
23405 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
23406 ** routine to lower a locking level.
23407 */
23408 static int unixLock(sqlite3_file *id, int eFileLock){
23409   /* The following describes the implementation of the various locks and
23410   ** lock transitions in terms of the POSIX advisory shared and exclusive
23411   ** lock primitives (called read-locks and write-locks below, to avoid
23412   ** confusion with SQLite lock names). The algorithms are complicated
23413   ** slightly in order to be compatible with windows systems simultaneously
23414   ** accessing the same database file, in case that is ever required.
23415   **
23416   ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
23417   ** byte', each single bytes at well known offsets, and the 'shared byte
23418   ** range', a range of 510 bytes at a well known offset.
23419   **
23420   ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
23421   ** byte'.  If this is successful, a random byte from the 'shared byte
23422   ** range' is read-locked and the lock on the 'pending byte' released.
23423   **
23424   ** A process may only obtain a RESERVED lock after it has a SHARED lock.
23425   ** A RESERVED lock is implemented by grabbing a write-lock on the
23426   ** 'reserved byte'. 
23427   **
23428   ** A process may only obtain a PENDING lock after it has obtained a
23429   ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
23430   ** on the 'pending byte'. This ensures that no new SHARED locks can be
23431   ** obtained, but existing SHARED locks are allowed to persist. A process
23432   ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
23433   ** This property is used by the algorithm for rolling back a journal file
23434   ** after a crash.
23435   **
23436   ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
23437   ** implemented by obtaining a write-lock on the entire 'shared byte
23438   ** range'. Since all other locks require a read-lock on one of the bytes
23439   ** within this range, this ensures that no other locks are held on the
23440   ** database. 
23441   **
23442   ** The reason a single byte cannot be used instead of the 'shared byte
23443   ** range' is that some versions of windows do not support read-locks. By
23444   ** locking a random byte from a range, concurrent SHARED locks may exist
23445   ** even if the locking primitive used is always a write-lock.
23446   */
23447   int rc = SQLITE_OK;
23448   unixFile *pFile = (unixFile*)id;
23449   unixInodeInfo *pInode = pFile->pInode;
23450   struct flock lock;
23451   int s = 0;
23452   int tErrno = 0;
23453
23454   assert( pFile );
23455   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
23456       azFileLock(eFileLock), azFileLock(pFile->eFileLock),
23457       azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
23458
23459   /* If there is already a lock of this type or more restrictive on the
23460   ** unixFile, do nothing. Don't use the end_lock: exit path, as
23461   ** unixEnterMutex() hasn't been called yet.
23462   */
23463   if( pFile->eFileLock>=eFileLock ){
23464     OSTRACE(("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
23465             azFileLock(eFileLock)));
23466     return SQLITE_OK;
23467   }
23468
23469   /* Make sure the locking sequence is correct.
23470   **  (1) We never move from unlocked to anything higher than shared lock.
23471   **  (2) SQLite never explicitly requests a pendig lock.
23472   **  (3) A shared lock is always held when a reserve lock is requested.
23473   */
23474   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
23475   assert( eFileLock!=PENDING_LOCK );
23476   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
23477
23478   /* This mutex is needed because pFile->pInode is shared across threads
23479   */
23480   unixEnterMutex();
23481   pInode = pFile->pInode;
23482
23483   /* If some thread using this PID has a lock via a different unixFile*
23484   ** handle that precludes the requested lock, return BUSY.
23485   */
23486   if( (pFile->eFileLock!=pInode->eFileLock && 
23487           (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
23488   ){
23489     rc = SQLITE_BUSY;
23490     goto end_lock;
23491   }
23492
23493   /* If a SHARED lock is requested, and some thread using this PID already
23494   ** has a SHARED or RESERVED lock, then increment reference counts and
23495   ** return SQLITE_OK.
23496   */
23497   if( eFileLock==SHARED_LOCK && 
23498       (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
23499     assert( eFileLock==SHARED_LOCK );
23500     assert( pFile->eFileLock==0 );
23501     assert( pInode->nShared>0 );
23502     pFile->eFileLock = SHARED_LOCK;
23503     pInode->nShared++;
23504     pInode->nLock++;
23505     goto end_lock;
23506   }
23507
23508
23509   /* A PENDING lock is needed before acquiring a SHARED lock and before
23510   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
23511   ** be released.
23512   */
23513   lock.l_len = 1L;
23514   lock.l_whence = SEEK_SET;
23515   if( eFileLock==SHARED_LOCK 
23516       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
23517   ){
23518     lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
23519     lock.l_start = PENDING_BYTE;
23520     s = fcntl(pFile->h, F_SETLK, &lock);
23521     if( s==(-1) ){
23522       tErrno = errno;
23523       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
23524       if( IS_LOCK_ERROR(rc) ){
23525         pFile->lastErrno = tErrno;
23526       }
23527       goto end_lock;
23528     }
23529   }
23530
23531
23532   /* If control gets to this point, then actually go ahead and make
23533   ** operating system calls for the specified lock.
23534   */
23535   if( eFileLock==SHARED_LOCK ){
23536     assert( pInode->nShared==0 );
23537     assert( pInode->eFileLock==0 );
23538
23539     /* Now get the read-lock */
23540     lock.l_start = SHARED_FIRST;
23541     lock.l_len = SHARED_SIZE;
23542     if( (s = fcntl(pFile->h, F_SETLK, &lock))==(-1) ){
23543       tErrno = errno;
23544     }
23545     /* Drop the temporary PENDING lock */
23546     lock.l_start = PENDING_BYTE;
23547     lock.l_len = 1L;
23548     lock.l_type = F_UNLCK;
23549     if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
23550       if( s != -1 ){
23551         /* This could happen with a network mount */
23552         tErrno = errno; 
23553         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK); 
23554         if( IS_LOCK_ERROR(rc) ){
23555           pFile->lastErrno = tErrno;
23556         }
23557         goto end_lock;
23558       }
23559     }
23560     if( s==(-1) ){
23561       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
23562       if( IS_LOCK_ERROR(rc) ){
23563         pFile->lastErrno = tErrno;
23564       }
23565     }else{
23566       pFile->eFileLock = SHARED_LOCK;
23567       pInode->nLock++;
23568       pInode->nShared = 1;
23569     }
23570   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
23571     /* We are trying for an exclusive lock but another thread in this
23572     ** same process is still holding a shared lock. */
23573     rc = SQLITE_BUSY;
23574   }else{
23575     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
23576     ** assumed that there is a SHARED or greater lock on the file
23577     ** already.
23578     */
23579     assert( 0!=pFile->eFileLock );
23580     lock.l_type = F_WRLCK;
23581     switch( eFileLock ){
23582       case RESERVED_LOCK:
23583         lock.l_start = RESERVED_BYTE;
23584         break;
23585       case EXCLUSIVE_LOCK:
23586         lock.l_start = SHARED_FIRST;
23587         lock.l_len = SHARED_SIZE;
23588         break;
23589       default:
23590         assert(0);
23591     }
23592     s = fcntl(pFile->h, F_SETLK, &lock);
23593     if( s==(-1) ){
23594       tErrno = errno;
23595       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
23596       if( IS_LOCK_ERROR(rc) ){
23597         pFile->lastErrno = tErrno;
23598       }
23599     }
23600   }
23601   
23602
23603 #ifndef NDEBUG
23604   /* Set up the transaction-counter change checking flags when
23605   ** transitioning from a SHARED to a RESERVED lock.  The change
23606   ** from SHARED to RESERVED marks the beginning of a normal
23607   ** write operation (not a hot journal rollback).
23608   */
23609   if( rc==SQLITE_OK
23610    && pFile->eFileLock<=SHARED_LOCK
23611    && eFileLock==RESERVED_LOCK
23612   ){
23613     pFile->transCntrChng = 0;
23614     pFile->dbUpdate = 0;
23615     pFile->inNormalWrite = 1;
23616   }
23617 #endif
23618
23619
23620   if( rc==SQLITE_OK ){
23621     pFile->eFileLock = eFileLock;
23622     pInode->eFileLock = eFileLock;
23623   }else if( eFileLock==EXCLUSIVE_LOCK ){
23624     pFile->eFileLock = PENDING_LOCK;
23625     pInode->eFileLock = PENDING_LOCK;
23626   }
23627
23628 end_lock:
23629   unixLeaveMutex();
23630   OSTRACE(("LOCK    %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock), 
23631       rc==SQLITE_OK ? "ok" : "failed"));
23632   return rc;
23633 }
23634
23635 /*
23636 ** Add the file descriptor used by file handle pFile to the corresponding
23637 ** pUnused list.
23638 */
23639 static void setPendingFd(unixFile *pFile){
23640   unixInodeInfo *pInode = pFile->pInode;
23641   UnixUnusedFd *p = pFile->pUnused;
23642   p->pNext = pInode->pUnused;
23643   pInode->pUnused = p;
23644   pFile->h = -1;
23645   pFile->pUnused = 0;
23646 }
23647
23648 /*
23649 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
23650 ** must be either NO_LOCK or SHARED_LOCK.
23651 **
23652 ** If the locking level of the file descriptor is already at or below
23653 ** the requested locking level, this routine is a no-op.
23654 ** 
23655 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
23656 ** the byte range is divided into 2 parts and the first part is unlocked then
23657 ** set to a read lock, then the other part is simply unlocked.  This works 
23658 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to 
23659 ** remove the write lock on a region when a read lock is set.
23660 */
23661 static int _posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
23662   unixFile *pFile = (unixFile*)id;
23663   unixInodeInfo *pInode;
23664   struct flock lock;
23665   int rc = SQLITE_OK;
23666   int h;
23667   int tErrno;                      /* Error code from system call errors */
23668
23669   assert( pFile );
23670   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
23671       pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
23672       getpid()));
23673
23674   assert( eFileLock<=SHARED_LOCK );
23675   if( pFile->eFileLock<=eFileLock ){
23676     return SQLITE_OK;
23677   }
23678   unixEnterMutex();
23679   h = pFile->h;
23680   pInode = pFile->pInode;
23681   assert( pInode->nShared!=0 );
23682   if( pFile->eFileLock>SHARED_LOCK ){
23683     assert( pInode->eFileLock==pFile->eFileLock );
23684     SimulateIOErrorBenign(1);
23685     SimulateIOError( h=(-1) )
23686     SimulateIOErrorBenign(0);
23687
23688 #ifndef NDEBUG
23689     /* When reducing a lock such that other processes can start
23690     ** reading the database file again, make sure that the
23691     ** transaction counter was updated if any part of the database
23692     ** file changed.  If the transaction counter is not updated,
23693     ** other connections to the same file might not realize that
23694     ** the file has changed and hence might not know to flush their
23695     ** cache.  The use of a stale cache can lead to database corruption.
23696     */
23697 #if 0
23698     assert( pFile->inNormalWrite==0
23699          || pFile->dbUpdate==0
23700          || pFile->transCntrChng==1 );
23701 #endif
23702     pFile->inNormalWrite = 0;
23703 #endif
23704
23705     /* downgrading to a shared lock on NFS involves clearing the write lock
23706     ** before establishing the readlock - to avoid a race condition we downgrade
23707     ** the lock in 2 blocks, so that part of the range will be covered by a 
23708     ** write lock until the rest is covered by a read lock:
23709     **  1:   [WWWWW]
23710     **  2:   [....W]
23711     **  3:   [RRRRW]
23712     **  4:   [RRRR.]
23713     */
23714     if( eFileLock==SHARED_LOCK ){
23715       if( handleNFSUnlock ){
23716         off_t divSize = SHARED_SIZE - 1;
23717         
23718         lock.l_type = F_UNLCK;
23719         lock.l_whence = SEEK_SET;
23720         lock.l_start = SHARED_FIRST;
23721         lock.l_len = divSize;
23722         if( fcntl(h, F_SETLK, &lock)==(-1) ){
23723           tErrno = errno;
23724           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23725           if( IS_LOCK_ERROR(rc) ){
23726             pFile->lastErrno = tErrno;
23727           }
23728           goto end_unlock;
23729         }
23730         lock.l_type = F_RDLCK;
23731         lock.l_whence = SEEK_SET;
23732         lock.l_start = SHARED_FIRST;
23733         lock.l_len = divSize;
23734         if( fcntl(h, F_SETLK, &lock)==(-1) ){
23735           tErrno = errno;
23736           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
23737           if( IS_LOCK_ERROR(rc) ){
23738             pFile->lastErrno = tErrno;
23739           }
23740           goto end_unlock;
23741         }
23742         lock.l_type = F_UNLCK;
23743         lock.l_whence = SEEK_SET;
23744         lock.l_start = SHARED_FIRST+divSize;
23745         lock.l_len = SHARED_SIZE-divSize;
23746         if( fcntl(h, F_SETLK, &lock)==(-1) ){
23747           tErrno = errno;
23748           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23749           if( IS_LOCK_ERROR(rc) ){
23750             pFile->lastErrno = tErrno;
23751           }
23752           goto end_unlock;
23753         }
23754       }else{
23755         lock.l_type = F_RDLCK;
23756         lock.l_whence = SEEK_SET;
23757         lock.l_start = SHARED_FIRST;
23758         lock.l_len = SHARED_SIZE;
23759         if( fcntl(h, F_SETLK, &lock)==(-1) ){
23760           tErrno = errno;
23761           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
23762           if( IS_LOCK_ERROR(rc) ){
23763             pFile->lastErrno = tErrno;
23764           }
23765           goto end_unlock;
23766         }
23767       }
23768     }
23769     lock.l_type = F_UNLCK;
23770     lock.l_whence = SEEK_SET;
23771     lock.l_start = PENDING_BYTE;
23772     lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
23773     if( fcntl(h, F_SETLK, &lock)!=(-1) ){
23774       pInode->eFileLock = SHARED_LOCK;
23775     }else{
23776       tErrno = errno;
23777       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23778       if( IS_LOCK_ERROR(rc) ){
23779         pFile->lastErrno = tErrno;
23780       }
23781       goto end_unlock;
23782     }
23783   }
23784   if( eFileLock==NO_LOCK ){
23785     /* Decrement the shared lock counter.  Release the lock using an
23786     ** OS call only when all threads in this same process have released
23787     ** the lock.
23788     */
23789     pInode->nShared--;
23790     if( pInode->nShared==0 ){
23791       lock.l_type = F_UNLCK;
23792       lock.l_whence = SEEK_SET;
23793       lock.l_start = lock.l_len = 0L;
23794       SimulateIOErrorBenign(1);
23795       SimulateIOError( h=(-1) )
23796       SimulateIOErrorBenign(0);
23797       if( fcntl(h, F_SETLK, &lock)!=(-1) ){
23798         pInode->eFileLock = NO_LOCK;
23799       }else{
23800         tErrno = errno;
23801         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23802         if( IS_LOCK_ERROR(rc) ){
23803           pFile->lastErrno = tErrno;
23804         }
23805         pInode->eFileLock = NO_LOCK;
23806         pFile->eFileLock = NO_LOCK;
23807       }
23808     }
23809
23810     /* Decrement the count of locks against this same file.  When the
23811     ** count reaches zero, close any other file descriptors whose close
23812     ** was deferred because of outstanding locks.
23813     */
23814     pInode->nLock--;
23815     assert( pInode->nLock>=0 );
23816     if( pInode->nLock==0 ){
23817       int rc2 = closePendingFds(pFile);
23818       if( rc==SQLITE_OK ){
23819         rc = rc2;
23820       }
23821     }
23822   }
23823         
23824 end_unlock:
23825   unixLeaveMutex();
23826   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
23827   return rc;
23828 }
23829
23830 /*
23831 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
23832 ** must be either NO_LOCK or SHARED_LOCK.
23833 **
23834 ** If the locking level of the file descriptor is already at or below
23835 ** the requested locking level, this routine is a no-op.
23836 */
23837 static int unixUnlock(sqlite3_file *id, int eFileLock){
23838   return _posixUnlock(id, eFileLock, 0);
23839 }
23840
23841 /*
23842 ** This function performs the parts of the "close file" operation 
23843 ** common to all locking schemes. It closes the directory and file
23844 ** handles, if they are valid, and sets all fields of the unixFile
23845 ** structure to 0.
23846 **
23847 ** It is *not* necessary to hold the mutex when this routine is called,
23848 ** even on VxWorks.  A mutex will be acquired on VxWorks by the
23849 ** vxworksReleaseFileId() routine.
23850 */
23851 static int closeUnixFile(sqlite3_file *id){
23852   unixFile *pFile = (unixFile*)id;
23853   if( pFile ){
23854     if( pFile->dirfd>=0 ){
23855       int err = close(pFile->dirfd);
23856       if( err ){
23857         pFile->lastErrno = errno;
23858         return SQLITE_IOERR_DIR_CLOSE;
23859       }else{
23860         pFile->dirfd=-1;
23861       }
23862     }
23863     if( pFile->h>=0 ){
23864       int err = close(pFile->h);
23865       if( err ){
23866         pFile->lastErrno = errno;
23867         return SQLITE_IOERR_CLOSE;
23868       }
23869     }
23870 #if OS_VXWORKS
23871     if( pFile->pId ){
23872       if( pFile->isDelete ){
23873         unlink(pFile->pId->zCanonicalName);
23874       }
23875       vxworksReleaseFileId(pFile->pId);
23876       pFile->pId = 0;
23877     }
23878 #endif
23879     OSTRACE(("CLOSE   %-3d\n", pFile->h));
23880     OpenCounter(-1);
23881     sqlite3_free(pFile->pUnused);
23882     memset(pFile, 0, sizeof(unixFile));
23883   }
23884   return SQLITE_OK;
23885 }
23886
23887 /*
23888 ** Close a file.
23889 */
23890 static int unixClose(sqlite3_file *id){
23891   int rc = SQLITE_OK;
23892   if( id ){
23893     unixFile *pFile = (unixFile *)id;
23894     unixUnlock(id, NO_LOCK);
23895     unixEnterMutex();
23896     if( pFile->pInode && pFile->pInode->nLock ){
23897       /* If there are outstanding locks, do not actually close the file just
23898       ** yet because that would clear those locks.  Instead, add the file
23899       ** descriptor to pInode->pUnused list.  It will be automatically closed 
23900       ** when the last lock is cleared.
23901       */
23902       setPendingFd(pFile);
23903     }
23904     releaseInodeInfo(pFile);
23905     rc = closeUnixFile(id);
23906     unixLeaveMutex();
23907   }
23908   return rc;
23909 }
23910
23911 /************** End of the posix advisory lock implementation *****************
23912 ******************************************************************************/
23913
23914 /******************************************************************************
23915 ****************************** No-op Locking **********************************
23916 **
23917 ** Of the various locking implementations available, this is by far the
23918 ** simplest:  locking is ignored.  No attempt is made to lock the database
23919 ** file for reading or writing.
23920 **
23921 ** This locking mode is appropriate for use on read-only databases
23922 ** (ex: databases that are burned into CD-ROM, for example.)  It can
23923 ** also be used if the application employs some external mechanism to
23924 ** prevent simultaneous access of the same database by two or more
23925 ** database connections.  But there is a serious risk of database
23926 ** corruption if this locking mode is used in situations where multiple
23927 ** database connections are accessing the same database file at the same
23928 ** time and one or more of those connections are writing.
23929 */
23930
23931 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
23932   UNUSED_PARAMETER(NotUsed);
23933   *pResOut = 0;
23934   return SQLITE_OK;
23935 }
23936 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
23937   UNUSED_PARAMETER2(NotUsed, NotUsed2);
23938   return SQLITE_OK;
23939 }
23940 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
23941   UNUSED_PARAMETER2(NotUsed, NotUsed2);
23942   return SQLITE_OK;
23943 }
23944
23945 /*
23946 ** Close the file.
23947 */
23948 static int nolockClose(sqlite3_file *id) {
23949   return closeUnixFile(id);
23950 }
23951
23952 /******************* End of the no-op lock implementation *********************
23953 ******************************************************************************/
23954
23955 /******************************************************************************
23956 ************************* Begin dot-file Locking ******************************
23957 **
23958 ** The dotfile locking implementation uses the existance of separate lock
23959 ** files in order to control access to the database.  This works on just
23960 ** about every filesystem imaginable.  But there are serious downsides:
23961 **
23962 **    (1)  There is zero concurrency.  A single reader blocks all other
23963 **         connections from reading or writing the database.
23964 **
23965 **    (2)  An application crash or power loss can leave stale lock files
23966 **         sitting around that need to be cleared manually.
23967 **
23968 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
23969 ** other locking strategy is available.
23970 **
23971 ** Dotfile locking works by creating a file in the same directory as the
23972 ** database and with the same name but with a ".lock" extension added.
23973 ** The existance of a lock file implies an EXCLUSIVE lock.  All other lock
23974 ** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
23975 */
23976
23977 /*
23978 ** The file suffix added to the data base filename in order to create the
23979 ** lock file.
23980 */
23981 #define DOTLOCK_SUFFIX ".lock"
23982
23983 /*
23984 ** This routine checks if there is a RESERVED lock held on the specified
23985 ** file by this or any other process. If such a lock is held, set *pResOut
23986 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
23987 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
23988 **
23989 ** In dotfile locking, either a lock exists or it does not.  So in this
23990 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
23991 ** is held on the file and false if the file is unlocked.
23992 */
23993 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
23994   int rc = SQLITE_OK;
23995   int reserved = 0;
23996   unixFile *pFile = (unixFile*)id;
23997
23998   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
23999   
24000   assert( pFile );
24001
24002   /* Check if a thread in this process holds such a lock */
24003   if( pFile->eFileLock>SHARED_LOCK ){
24004     /* Either this connection or some other connection in the same process
24005     ** holds a lock on the file.  No need to check further. */
24006     reserved = 1;
24007   }else{
24008     /* The lock is held if and only if the lockfile exists */
24009     const char *zLockFile = (const char*)pFile->lockingContext;
24010     reserved = access(zLockFile, 0)==0;
24011   }
24012   OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
24013   *pResOut = reserved;
24014   return rc;
24015 }
24016
24017 /*
24018 ** Lock the file with the lock specified by parameter eFileLock - one
24019 ** of the following:
24020 **
24021 **     (1) SHARED_LOCK
24022 **     (2) RESERVED_LOCK
24023 **     (3) PENDING_LOCK
24024 **     (4) EXCLUSIVE_LOCK
24025 **
24026 ** Sometimes when requesting one lock state, additional lock states
24027 ** are inserted in between.  The locking might fail on one of the later
24028 ** transitions leaving the lock state different from what it started but
24029 ** still short of its goal.  The following chart shows the allowed
24030 ** transitions and the inserted intermediate states:
24031 **
24032 **    UNLOCKED -> SHARED
24033 **    SHARED -> RESERVED
24034 **    SHARED -> (PENDING) -> EXCLUSIVE
24035 **    RESERVED -> (PENDING) -> EXCLUSIVE
24036 **    PENDING -> EXCLUSIVE
24037 **
24038 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
24039 ** routine to lower a locking level.
24040 **
24041 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
24042 ** But we track the other locking levels internally.
24043 */
24044 static int dotlockLock(sqlite3_file *id, int eFileLock) {
24045   unixFile *pFile = (unixFile*)id;
24046   int fd;
24047   char *zLockFile = (char *)pFile->lockingContext;
24048   int rc = SQLITE_OK;
24049
24050
24051   /* If we have any lock, then the lock file already exists.  All we have
24052   ** to do is adjust our internal record of the lock level.
24053   */
24054   if( pFile->eFileLock > NO_LOCK ){
24055     pFile->eFileLock = eFileLock;
24056 #if !OS_VXWORKS
24057     /* Always update the timestamp on the old file */
24058     utimes(zLockFile, NULL);
24059 #endif
24060     return SQLITE_OK;
24061   }
24062   
24063   /* grab an exclusive lock */
24064   fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
24065   if( fd<0 ){
24066     /* failed to open/create the file, someone else may have stolen the lock */
24067     int tErrno = errno;
24068     if( EEXIST == tErrno ){
24069       rc = SQLITE_BUSY;
24070     } else {
24071       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24072       if( IS_LOCK_ERROR(rc) ){
24073         pFile->lastErrno = tErrno;
24074       }
24075     }
24076     return rc;
24077   } 
24078   if( close(fd) ){
24079     pFile->lastErrno = errno;
24080     rc = SQLITE_IOERR_CLOSE;
24081   }
24082   
24083   /* got it, set the type and return ok */
24084   pFile->eFileLock = eFileLock;
24085   return rc;
24086 }
24087
24088 /*
24089 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
24090 ** must be either NO_LOCK or SHARED_LOCK.
24091 **
24092 ** If the locking level of the file descriptor is already at or below
24093 ** the requested locking level, this routine is a no-op.
24094 **
24095 ** When the locking level reaches NO_LOCK, delete the lock file.
24096 */
24097 static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
24098   unixFile *pFile = (unixFile*)id;
24099   char *zLockFile = (char *)pFile->lockingContext;
24100
24101   assert( pFile );
24102   OSTRACE(("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
24103            pFile->eFileLock, getpid()));
24104   assert( eFileLock<=SHARED_LOCK );
24105   
24106   /* no-op if possible */
24107   if( pFile->eFileLock==eFileLock ){
24108     return SQLITE_OK;
24109   }
24110
24111   /* To downgrade to shared, simply update our internal notion of the
24112   ** lock state.  No need to mess with the file on disk.
24113   */
24114   if( eFileLock==SHARED_LOCK ){
24115     pFile->eFileLock = SHARED_LOCK;
24116     return SQLITE_OK;
24117   }
24118   
24119   /* To fully unlock the database, delete the lock file */
24120   assert( eFileLock==NO_LOCK );
24121   if( unlink(zLockFile) ){
24122     int rc = 0;
24123     int tErrno = errno;
24124     if( ENOENT != tErrno ){
24125       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
24126     }
24127     if( IS_LOCK_ERROR(rc) ){
24128       pFile->lastErrno = tErrno;
24129     }
24130     return rc; 
24131   }
24132   pFile->eFileLock = NO_LOCK;
24133   return SQLITE_OK;
24134 }
24135
24136 /*
24137 ** Close a file.  Make sure the lock has been released before closing.
24138 */
24139 static int dotlockClose(sqlite3_file *id) {
24140   int rc;
24141   if( id ){
24142     unixFile *pFile = (unixFile*)id;
24143     dotlockUnlock(id, NO_LOCK);
24144     sqlite3_free(pFile->lockingContext);
24145   }
24146   rc = closeUnixFile(id);
24147   return rc;
24148 }
24149 /****************** End of the dot-file lock implementation *******************
24150 ******************************************************************************/
24151
24152 /******************************************************************************
24153 ************************** Begin flock Locking ********************************
24154 **
24155 ** Use the flock() system call to do file locking.
24156 **
24157 ** flock() locking is like dot-file locking in that the various
24158 ** fine-grain locking levels supported by SQLite are collapsed into
24159 ** a single exclusive lock.  In other words, SHARED, RESERVED, and
24160 ** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
24161 ** still works when you do this, but concurrency is reduced since
24162 ** only a single process can be reading the database at a time.
24163 **
24164 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
24165 ** compiling for VXWORKS.
24166 */
24167 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
24168
24169 /*
24170 ** This routine checks if there is a RESERVED lock held on the specified
24171 ** file by this or any other process. If such a lock is held, set *pResOut
24172 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
24173 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
24174 */
24175 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
24176   int rc = SQLITE_OK;
24177   int reserved = 0;
24178   unixFile *pFile = (unixFile*)id;
24179   
24180   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
24181   
24182   assert( pFile );
24183   
24184   /* Check if a thread in this process holds such a lock */
24185   if( pFile->eFileLock>SHARED_LOCK ){
24186     reserved = 1;
24187   }
24188   
24189   /* Otherwise see if some other process holds it. */
24190   if( !reserved ){
24191     /* attempt to get the lock */
24192     int lrc = flock(pFile->h, LOCK_EX | LOCK_NB);
24193     if( !lrc ){
24194       /* got the lock, unlock it */
24195       lrc = flock(pFile->h, LOCK_UN);
24196       if ( lrc ) {
24197         int tErrno = errno;
24198         /* unlock failed with an error */
24199         lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK); 
24200         if( IS_LOCK_ERROR(lrc) ){
24201           pFile->lastErrno = tErrno;
24202           rc = lrc;
24203         }
24204       }
24205     } else {
24206       int tErrno = errno;
24207       reserved = 1;
24208       /* someone else might have it reserved */
24209       lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); 
24210       if( IS_LOCK_ERROR(lrc) ){
24211         pFile->lastErrno = tErrno;
24212         rc = lrc;
24213       }
24214     }
24215   }
24216   OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
24217
24218 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
24219   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
24220     rc = SQLITE_OK;
24221     reserved=1;
24222   }
24223 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
24224   *pResOut = reserved;
24225   return rc;
24226 }
24227
24228 /*
24229 ** Lock the file with the lock specified by parameter eFileLock - one
24230 ** of the following:
24231 **
24232 **     (1) SHARED_LOCK
24233 **     (2) RESERVED_LOCK
24234 **     (3) PENDING_LOCK
24235 **     (4) EXCLUSIVE_LOCK
24236 **
24237 ** Sometimes when requesting one lock state, additional lock states
24238 ** are inserted in between.  The locking might fail on one of the later
24239 ** transitions leaving the lock state different from what it started but
24240 ** still short of its goal.  The following chart shows the allowed
24241 ** transitions and the inserted intermediate states:
24242 **
24243 **    UNLOCKED -> SHARED
24244 **    SHARED -> RESERVED
24245 **    SHARED -> (PENDING) -> EXCLUSIVE
24246 **    RESERVED -> (PENDING) -> EXCLUSIVE
24247 **    PENDING -> EXCLUSIVE
24248 **
24249 ** flock() only really support EXCLUSIVE locks.  We track intermediate
24250 ** lock states in the sqlite3_file structure, but all locks SHARED or
24251 ** above are really EXCLUSIVE locks and exclude all other processes from
24252 ** access the file.
24253 **
24254 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
24255 ** routine to lower a locking level.
24256 */
24257 static int flockLock(sqlite3_file *id, int eFileLock) {
24258   int rc = SQLITE_OK;
24259   unixFile *pFile = (unixFile*)id;
24260
24261   assert( pFile );
24262
24263   /* if we already have a lock, it is exclusive.  
24264   ** Just adjust level and punt on outta here. */
24265   if (pFile->eFileLock > NO_LOCK) {
24266     pFile->eFileLock = eFileLock;
24267     return SQLITE_OK;
24268   }
24269   
24270   /* grab an exclusive lock */
24271   
24272   if (flock(pFile->h, LOCK_EX | LOCK_NB)) {
24273     int tErrno = errno;
24274     /* didn't get, must be busy */
24275     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24276     if( IS_LOCK_ERROR(rc) ){
24277       pFile->lastErrno = tErrno;
24278     }
24279   } else {
24280     /* got it, set the type and return ok */
24281     pFile->eFileLock = eFileLock;
24282   }
24283   OSTRACE(("LOCK    %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock), 
24284            rc==SQLITE_OK ? "ok" : "failed"));
24285 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
24286   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
24287     rc = SQLITE_BUSY;
24288   }
24289 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
24290   return rc;
24291 }
24292
24293
24294 /*
24295 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
24296 ** must be either NO_LOCK or SHARED_LOCK.
24297 **
24298 ** If the locking level of the file descriptor is already at or below
24299 ** the requested locking level, this routine is a no-op.
24300 */
24301 static int flockUnlock(sqlite3_file *id, int eFileLock) {
24302   unixFile *pFile = (unixFile*)id;
24303   
24304   assert( pFile );
24305   OSTRACE(("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
24306            pFile->eFileLock, getpid()));
24307   assert( eFileLock<=SHARED_LOCK );
24308   
24309   /* no-op if possible */
24310   if( pFile->eFileLock==eFileLock ){
24311     return SQLITE_OK;
24312   }
24313   
24314   /* shared can just be set because we always have an exclusive */
24315   if (eFileLock==SHARED_LOCK) {
24316     pFile->eFileLock = eFileLock;
24317     return SQLITE_OK;
24318   }
24319   
24320   /* no, really, unlock. */
24321   int rc = flock(pFile->h, LOCK_UN);
24322   if (rc) {
24323     int r, tErrno = errno;
24324     r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
24325     if( IS_LOCK_ERROR(r) ){
24326       pFile->lastErrno = tErrno;
24327     }
24328 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
24329     if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
24330       r = SQLITE_BUSY;
24331     }
24332 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
24333     
24334     return r;
24335   } else {
24336     pFile->eFileLock = NO_LOCK;
24337     return SQLITE_OK;
24338   }
24339 }
24340
24341 /*
24342 ** Close a file.
24343 */
24344 static int flockClose(sqlite3_file *id) {
24345   if( id ){
24346     flockUnlock(id, NO_LOCK);
24347   }
24348   return closeUnixFile(id);
24349 }
24350
24351 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
24352
24353 /******************* End of the flock lock implementation *********************
24354 ******************************************************************************/
24355
24356 /******************************************************************************
24357 ************************ Begin Named Semaphore Locking ************************
24358 **
24359 ** Named semaphore locking is only supported on VxWorks.
24360 **
24361 ** Semaphore locking is like dot-lock and flock in that it really only
24362 ** supports EXCLUSIVE locking.  Only a single process can read or write
24363 ** the database file at a time.  This reduces potential concurrency, but
24364 ** makes the lock implementation much easier.
24365 */
24366 #if OS_VXWORKS
24367
24368 /*
24369 ** This routine checks if there is a RESERVED lock held on the specified
24370 ** file by this or any other process. If such a lock is held, set *pResOut
24371 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
24372 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
24373 */
24374 static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
24375   int rc = SQLITE_OK;
24376   int reserved = 0;
24377   unixFile *pFile = (unixFile*)id;
24378
24379   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
24380   
24381   assert( pFile );
24382
24383   /* Check if a thread in this process holds such a lock */
24384   if( pFile->eFileLock>SHARED_LOCK ){
24385     reserved = 1;
24386   }
24387   
24388   /* Otherwise see if some other process holds it. */
24389   if( !reserved ){
24390     sem_t *pSem = pFile->pInode->pSem;
24391     struct stat statBuf;
24392
24393     if( sem_trywait(pSem)==-1 ){
24394       int tErrno = errno;
24395       if( EAGAIN != tErrno ){
24396         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
24397         pFile->lastErrno = tErrno;
24398       } else {
24399         /* someone else has the lock when we are in NO_LOCK */
24400         reserved = (pFile->eFileLock < SHARED_LOCK);
24401       }
24402     }else{
24403       /* we could have it if we want it */
24404       sem_post(pSem);
24405     }
24406   }
24407   OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
24408
24409   *pResOut = reserved;
24410   return rc;
24411 }
24412
24413 /*
24414 ** Lock the file with the lock specified by parameter eFileLock - one
24415 ** of the following:
24416 **
24417 **     (1) SHARED_LOCK
24418 **     (2) RESERVED_LOCK
24419 **     (3) PENDING_LOCK
24420 **     (4) EXCLUSIVE_LOCK
24421 **
24422 ** Sometimes when requesting one lock state, additional lock states
24423 ** are inserted in between.  The locking might fail on one of the later
24424 ** transitions leaving the lock state different from what it started but
24425 ** still short of its goal.  The following chart shows the allowed
24426 ** transitions and the inserted intermediate states:
24427 **
24428 **    UNLOCKED -> SHARED
24429 **    SHARED -> RESERVED
24430 **    SHARED -> (PENDING) -> EXCLUSIVE
24431 **    RESERVED -> (PENDING) -> EXCLUSIVE
24432 **    PENDING -> EXCLUSIVE
24433 **
24434 ** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
24435 ** lock states in the sqlite3_file structure, but all locks SHARED or
24436 ** above are really EXCLUSIVE locks and exclude all other processes from
24437 ** access the file.
24438 **
24439 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
24440 ** routine to lower a locking level.
24441 */
24442 static int semLock(sqlite3_file *id, int eFileLock) {
24443   unixFile *pFile = (unixFile*)id;
24444   int fd;
24445   sem_t *pSem = pFile->pInode->pSem;
24446   int rc = SQLITE_OK;
24447
24448   /* if we already have a lock, it is exclusive.  
24449   ** Just adjust level and punt on outta here. */
24450   if (pFile->eFileLock > NO_LOCK) {
24451     pFile->eFileLock = eFileLock;
24452     rc = SQLITE_OK;
24453     goto sem_end_lock;
24454   }
24455   
24456   /* lock semaphore now but bail out when already locked. */
24457   if( sem_trywait(pSem)==-1 ){
24458     rc = SQLITE_BUSY;
24459     goto sem_end_lock;
24460   }
24461
24462   /* got it, set the type and return ok */
24463   pFile->eFileLock = eFileLock;
24464
24465  sem_end_lock:
24466   return rc;
24467 }
24468
24469 /*
24470 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
24471 ** must be either NO_LOCK or SHARED_LOCK.
24472 **
24473 ** If the locking level of the file descriptor is already at or below
24474 ** the requested locking level, this routine is a no-op.
24475 */
24476 static int semUnlock(sqlite3_file *id, int eFileLock) {
24477   unixFile *pFile = (unixFile*)id;
24478   sem_t *pSem = pFile->pInode->pSem;
24479
24480   assert( pFile );
24481   assert( pSem );
24482   OSTRACE(("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
24483            pFile->eFileLock, getpid()));
24484   assert( eFileLock<=SHARED_LOCK );
24485   
24486   /* no-op if possible */
24487   if( pFile->eFileLock==eFileLock ){
24488     return SQLITE_OK;
24489   }
24490   
24491   /* shared can just be set because we always have an exclusive */
24492   if (eFileLock==SHARED_LOCK) {
24493     pFile->eFileLock = eFileLock;
24494     return SQLITE_OK;
24495   }
24496   
24497   /* no, really unlock. */
24498   if ( sem_post(pSem)==-1 ) {
24499     int rc, tErrno = errno;
24500     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
24501     if( IS_LOCK_ERROR(rc) ){
24502       pFile->lastErrno = tErrno;
24503     }
24504     return rc; 
24505   }
24506   pFile->eFileLock = NO_LOCK;
24507   return SQLITE_OK;
24508 }
24509
24510 /*
24511  ** Close a file.
24512  */
24513 static int semClose(sqlite3_file *id) {
24514   if( id ){
24515     unixFile *pFile = (unixFile*)id;
24516     semUnlock(id, NO_LOCK);
24517     assert( pFile );
24518     unixEnterMutex();
24519     releaseInodeInfo(pFile);
24520     unixLeaveMutex();
24521     closeUnixFile(id);
24522   }
24523   return SQLITE_OK;
24524 }
24525
24526 #endif /* OS_VXWORKS */
24527 /*
24528 ** Named semaphore locking is only available on VxWorks.
24529 **
24530 *************** End of the named semaphore lock implementation ****************
24531 ******************************************************************************/
24532
24533
24534 /******************************************************************************
24535 *************************** Begin AFP Locking *********************************
24536 **
24537 ** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
24538 ** on Apple Macintosh computers - both OS9 and OSX.
24539 **
24540 ** Third-party implementations of AFP are available.  But this code here
24541 ** only works on OSX.
24542 */
24543
24544 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
24545 /*
24546 ** The afpLockingContext structure contains all afp lock specific state
24547 */
24548 typedef struct afpLockingContext afpLockingContext;
24549 struct afpLockingContext {
24550   int reserved;
24551   const char *dbPath;             /* Name of the open file */
24552 };
24553
24554 struct ByteRangeLockPB2
24555 {
24556   unsigned long long offset;        /* offset to first byte to lock */
24557   unsigned long long length;        /* nbr of bytes to lock */
24558   unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
24559   unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
24560   unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
24561   int fd;                           /* file desc to assoc this lock with */
24562 };
24563
24564 #define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
24565
24566 /*
24567 ** This is a utility for setting or clearing a bit-range lock on an
24568 ** AFP filesystem.
24569 ** 
24570 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
24571 */
24572 static int afpSetLock(
24573   const char *path,              /* Name of the file to be locked or unlocked */
24574   unixFile *pFile,               /* Open file descriptor on path */
24575   unsigned long long offset,     /* First byte to be locked */
24576   unsigned long long length,     /* Number of bytes to lock */
24577   int setLockFlag                /* True to set lock.  False to clear lock */
24578 ){
24579   struct ByteRangeLockPB2 pb;
24580   int err;
24581   
24582   pb.unLockFlag = setLockFlag ? 0 : 1;
24583   pb.startEndFlag = 0;
24584   pb.offset = offset;
24585   pb.length = length; 
24586   pb.fd = pFile->h;
24587   
24588   OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n", 
24589     (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
24590     offset, length));
24591   err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
24592   if ( err==-1 ) {
24593     int rc;
24594     int tErrno = errno;
24595     OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
24596              path, tErrno, strerror(tErrno)));
24597 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
24598     rc = SQLITE_BUSY;
24599 #else
24600     rc = sqliteErrorFromPosixError(tErrno,
24601                     setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
24602 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
24603     if( IS_LOCK_ERROR(rc) ){
24604       pFile->lastErrno = tErrno;
24605     }
24606     return rc;
24607   } else {
24608     return SQLITE_OK;
24609   }
24610 }
24611
24612 /*
24613 ** This routine checks if there is a RESERVED lock held on the specified
24614 ** file by this or any other process. If such a lock is held, set *pResOut
24615 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
24616 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
24617 */
24618 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
24619   int rc = SQLITE_OK;
24620   int reserved = 0;
24621   unixFile *pFile = (unixFile*)id;
24622   
24623   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
24624   
24625   assert( pFile );
24626   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
24627   if( context->reserved ){
24628     *pResOut = 1;
24629     return SQLITE_OK;
24630   }
24631   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
24632   
24633   /* Check if a thread in this process holds such a lock */
24634   if( pFile->pInode->eFileLock>SHARED_LOCK ){
24635     reserved = 1;
24636   }
24637   
24638   /* Otherwise see if some other process holds it.
24639    */
24640   if( !reserved ){
24641     /* lock the RESERVED byte */
24642     int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);  
24643     if( SQLITE_OK==lrc ){
24644       /* if we succeeded in taking the reserved lock, unlock it to restore
24645       ** the original state */
24646       lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
24647     } else {
24648       /* if we failed to get the lock then someone else must have it */
24649       reserved = 1;
24650     }
24651     if( IS_LOCK_ERROR(lrc) ){
24652       rc=lrc;
24653     }
24654   }
24655   
24656   unixLeaveMutex();
24657   OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
24658   
24659   *pResOut = reserved;
24660   return rc;
24661 }
24662
24663 /*
24664 ** Lock the file with the lock specified by parameter eFileLock - one
24665 ** of the following:
24666 **
24667 **     (1) SHARED_LOCK
24668 **     (2) RESERVED_LOCK
24669 **     (3) PENDING_LOCK
24670 **     (4) EXCLUSIVE_LOCK
24671 **
24672 ** Sometimes when requesting one lock state, additional lock states
24673 ** are inserted in between.  The locking might fail on one of the later
24674 ** transitions leaving the lock state different from what it started but
24675 ** still short of its goal.  The following chart shows the allowed
24676 ** transitions and the inserted intermediate states:
24677 **
24678 **    UNLOCKED -> SHARED
24679 **    SHARED -> RESERVED
24680 **    SHARED -> (PENDING) -> EXCLUSIVE
24681 **    RESERVED -> (PENDING) -> EXCLUSIVE
24682 **    PENDING -> EXCLUSIVE
24683 **
24684 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
24685 ** routine to lower a locking level.
24686 */
24687 static int afpLock(sqlite3_file *id, int eFileLock){
24688   int rc = SQLITE_OK;
24689   unixFile *pFile = (unixFile*)id;
24690   unixInodeInfo *pInode = pFile->pInode;
24691   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
24692   
24693   assert( pFile );
24694   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
24695            azFileLock(eFileLock), azFileLock(pFile->eFileLock),
24696            azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
24697
24698   /* If there is already a lock of this type or more restrictive on the
24699   ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
24700   ** unixEnterMutex() hasn't been called yet.
24701   */
24702   if( pFile->eFileLock>=eFileLock ){
24703     OSTRACE(("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
24704            azFileLock(eFileLock)));
24705     return SQLITE_OK;
24706   }
24707
24708   /* Make sure the locking sequence is correct
24709   **  (1) We never move from unlocked to anything higher than shared lock.
24710   **  (2) SQLite never explicitly requests a pendig lock.
24711   **  (3) A shared lock is always held when a reserve lock is requested.
24712   */
24713   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
24714   assert( eFileLock!=PENDING_LOCK );
24715   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
24716   
24717   /* This mutex is needed because pFile->pInode is shared across threads
24718   */
24719   unixEnterMutex();
24720   pInode = pFile->pInode;
24721
24722   /* If some thread using this PID has a lock via a different unixFile*
24723   ** handle that precludes the requested lock, return BUSY.
24724   */
24725   if( (pFile->eFileLock!=pInode->eFileLock && 
24726        (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
24727      ){
24728     rc = SQLITE_BUSY;
24729     goto afp_end_lock;
24730   }
24731   
24732   /* If a SHARED lock is requested, and some thread using this PID already
24733   ** has a SHARED or RESERVED lock, then increment reference counts and
24734   ** return SQLITE_OK.
24735   */
24736   if( eFileLock==SHARED_LOCK && 
24737      (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
24738     assert( eFileLock==SHARED_LOCK );
24739     assert( pFile->eFileLock==0 );
24740     assert( pInode->nShared>0 );
24741     pFile->eFileLock = SHARED_LOCK;
24742     pInode->nShared++;
24743     pInode->nLock++;
24744     goto afp_end_lock;
24745   }
24746     
24747   /* A PENDING lock is needed before acquiring a SHARED lock and before
24748   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
24749   ** be released.
24750   */
24751   if( eFileLock==SHARED_LOCK 
24752       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
24753   ){
24754     int failed;
24755     failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
24756     if (failed) {
24757       rc = failed;
24758       goto afp_end_lock;
24759     }
24760   }
24761   
24762   /* If control gets to this point, then actually go ahead and make
24763   ** operating system calls for the specified lock.
24764   */
24765   if( eFileLock==SHARED_LOCK ){
24766     int lrc1, lrc2, lrc1Errno;
24767     long lk, mask;
24768     
24769     assert( pInode->nShared==0 );
24770     assert( pInode->eFileLock==0 );
24771         
24772     mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
24773     /* Now get the read-lock SHARED_LOCK */
24774     /* note that the quality of the randomness doesn't matter that much */
24775     lk = random(); 
24776     pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
24777     lrc1 = afpSetLock(context->dbPath, pFile, 
24778           SHARED_FIRST+pInode->sharedByte, 1, 1);
24779     if( IS_LOCK_ERROR(lrc1) ){
24780       lrc1Errno = pFile->lastErrno;
24781     }
24782     /* Drop the temporary PENDING lock */
24783     lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
24784     
24785     if( IS_LOCK_ERROR(lrc1) ) {
24786       pFile->lastErrno = lrc1Errno;
24787       rc = lrc1;
24788       goto afp_end_lock;
24789     } else if( IS_LOCK_ERROR(lrc2) ){
24790       rc = lrc2;
24791       goto afp_end_lock;
24792     } else if( lrc1 != SQLITE_OK ) {
24793       rc = lrc1;
24794     } else {
24795       pFile->eFileLock = SHARED_LOCK;
24796       pInode->nLock++;
24797       pInode->nShared = 1;
24798     }
24799   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
24800     /* We are trying for an exclusive lock but another thread in this
24801      ** same process is still holding a shared lock. */
24802     rc = SQLITE_BUSY;
24803   }else{
24804     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
24805     ** assumed that there is a SHARED or greater lock on the file
24806     ** already.
24807     */
24808     int failed = 0;
24809     assert( 0!=pFile->eFileLock );
24810     if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
24811         /* Acquire a RESERVED lock */
24812         failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
24813       if( !failed ){
24814         context->reserved = 1;
24815       }
24816     }
24817     if (!failed && eFileLock == EXCLUSIVE_LOCK) {
24818       /* Acquire an EXCLUSIVE lock */
24819         
24820       /* Remove the shared lock before trying the range.  we'll need to 
24821       ** reestablish the shared lock if we can't get the  afpUnlock
24822       */
24823       if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
24824                          pInode->sharedByte, 1, 0)) ){
24825         int failed2 = SQLITE_OK;
24826         /* now attemmpt to get the exclusive lock range */
24827         failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST, 
24828                                SHARED_SIZE, 1);
24829         if( failed && (failed2 = afpSetLock(context->dbPath, pFile, 
24830                        SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
24831           /* Can't reestablish the shared lock.  Sqlite can't deal, this is
24832           ** a critical I/O error
24833           */
24834           rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 : 
24835                SQLITE_IOERR_LOCK;
24836           goto afp_end_lock;
24837         } 
24838       }else{
24839         rc = failed; 
24840       }
24841     }
24842     if( failed ){
24843       rc = failed;
24844     }
24845   }
24846   
24847   if( rc==SQLITE_OK ){
24848     pFile->eFileLock = eFileLock;
24849     pInode->eFileLock = eFileLock;
24850   }else if( eFileLock==EXCLUSIVE_LOCK ){
24851     pFile->eFileLock = PENDING_LOCK;
24852     pInode->eFileLock = PENDING_LOCK;
24853   }
24854   
24855 afp_end_lock:
24856   unixLeaveMutex();
24857   OSTRACE(("LOCK    %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock), 
24858          rc==SQLITE_OK ? "ok" : "failed"));
24859   return rc;
24860 }
24861
24862 /*
24863 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
24864 ** must be either NO_LOCK or SHARED_LOCK.
24865 **
24866 ** If the locking level of the file descriptor is already at or below
24867 ** the requested locking level, this routine is a no-op.
24868 */
24869 static int afpUnlock(sqlite3_file *id, int eFileLock) {
24870   int rc = SQLITE_OK;
24871   unixFile *pFile = (unixFile*)id;
24872   unixInodeInfo *pInode;
24873   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
24874   int skipShared = 0;
24875 #ifdef SQLITE_TEST
24876   int h = pFile->h;
24877 #endif
24878
24879   assert( pFile );
24880   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
24881            pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
24882            getpid()));
24883
24884   assert( eFileLock<=SHARED_LOCK );
24885   if( pFile->eFileLock<=eFileLock ){
24886     return SQLITE_OK;
24887   }
24888   unixEnterMutex();
24889   pInode = pFile->pInode;
24890   assert( pInode->nShared!=0 );
24891   if( pFile->eFileLock>SHARED_LOCK ){
24892     assert( pInode->eFileLock==pFile->eFileLock );
24893     SimulateIOErrorBenign(1);
24894     SimulateIOError( h=(-1) )
24895     SimulateIOErrorBenign(0);
24896     
24897 #ifndef NDEBUG
24898     /* When reducing a lock such that other processes can start
24899     ** reading the database file again, make sure that the
24900     ** transaction counter was updated if any part of the database
24901     ** file changed.  If the transaction counter is not updated,
24902     ** other connections to the same file might not realize that
24903     ** the file has changed and hence might not know to flush their
24904     ** cache.  The use of a stale cache can lead to database corruption.
24905     */
24906     assert( pFile->inNormalWrite==0
24907            || pFile->dbUpdate==0
24908            || pFile->transCntrChng==1 );
24909     pFile->inNormalWrite = 0;
24910 #endif
24911     
24912     if( pFile->eFileLock==EXCLUSIVE_LOCK ){
24913       rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
24914       if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
24915         /* only re-establish the shared lock if necessary */
24916         int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
24917         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
24918       } else {
24919         skipShared = 1;
24920       }
24921     }
24922     if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
24923       rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
24924     } 
24925     if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
24926       rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
24927       if( !rc ){ 
24928         context->reserved = 0; 
24929       }
24930     }
24931     if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
24932       pInode->eFileLock = SHARED_LOCK;
24933     }
24934   }
24935   if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
24936
24937     /* Decrement the shared lock counter.  Release the lock using an
24938     ** OS call only when all threads in this same process have released
24939     ** the lock.
24940     */
24941     unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
24942     pInode->nShared--;
24943     if( pInode->nShared==0 ){
24944       SimulateIOErrorBenign(1);
24945       SimulateIOError( h=(-1) )
24946       SimulateIOErrorBenign(0);
24947       if( !skipShared ){
24948         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
24949       }
24950       if( !rc ){
24951         pInode->eFileLock = NO_LOCK;
24952         pFile->eFileLock = NO_LOCK;
24953       }
24954     }
24955     if( rc==SQLITE_OK ){
24956       pInode->nLock--;
24957       assert( pInode->nLock>=0 );
24958       if( pInode->nLock==0 ){
24959         rc = closePendingFds(pFile);
24960       }
24961     }
24962   }
24963   
24964   unixLeaveMutex();
24965   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
24966   return rc;
24967 }
24968
24969 /*
24970 ** Close a file & cleanup AFP specific locking context 
24971 */
24972 static int afpClose(sqlite3_file *id) {
24973   int rc = SQLITE_OK;
24974   if( id ){
24975     unixFile *pFile = (unixFile*)id;
24976     afpUnlock(id, NO_LOCK);
24977     unixEnterMutex();
24978     if( pFile->pInode && pFile->pInode->nLock ){
24979       /* If there are outstanding locks, do not actually close the file just
24980       ** yet because that would clear those locks.  Instead, add the file
24981       ** descriptor to pInode->aPending.  It will be automatically closed when
24982       ** the last lock is cleared.
24983       */
24984       setPendingFd(pFile);
24985     }
24986     releaseInodeInfo(pFile);
24987     sqlite3_free(pFile->lockingContext);
24988     rc = closeUnixFile(id);
24989     unixLeaveMutex();
24990   }
24991   return rc;
24992 }
24993
24994 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
24995 /*
24996 ** The code above is the AFP lock implementation.  The code is specific
24997 ** to MacOSX and does not work on other unix platforms.  No alternative
24998 ** is available.  If you don't compile for a mac, then the "unix-afp"
24999 ** VFS is not available.
25000 **
25001 ********************* End of the AFP lock implementation **********************
25002 ******************************************************************************/
25003
25004 /******************************************************************************
25005 *************************** Begin NFS Locking ********************************/
25006
25007 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
25008 /*
25009  ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
25010  ** must be either NO_LOCK or SHARED_LOCK.
25011  **
25012  ** If the locking level of the file descriptor is already at or below
25013  ** the requested locking level, this routine is a no-op.
25014  */
25015 static int nfsUnlock(sqlite3_file *id, int eFileLock){
25016   return _posixUnlock(id, eFileLock, 1);
25017 }
25018
25019 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
25020 /*
25021 ** The code above is the NFS lock implementation.  The code is specific
25022 ** to MacOSX and does not work on other unix platforms.  No alternative
25023 ** is available.  
25024 **
25025 ********************* End of the NFS lock implementation **********************
25026 ******************************************************************************/
25027
25028 /******************************************************************************
25029 **************** Non-locking sqlite3_file methods *****************************
25030 **
25031 ** The next division contains implementations for all methods of the 
25032 ** sqlite3_file object other than the locking methods.  The locking
25033 ** methods were defined in divisions above (one locking method per
25034 ** division).  Those methods that are common to all locking modes
25035 ** are gather together into this division.
25036 */
25037
25038 /*
25039 ** Seek to the offset passed as the second argument, then read cnt 
25040 ** bytes into pBuf. Return the number of bytes actually read.
25041 **
25042 ** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
25043 ** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
25044 ** one system to another.  Since SQLite does not define USE_PREAD
25045 ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
25046 ** See tickets #2741 and #2681.
25047 **
25048 ** To avoid stomping the errno value on a failed read the lastErrno value
25049 ** is set before returning.
25050 */
25051 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
25052   int got;
25053 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
25054   i64 newOffset;
25055 #endif
25056   TIMER_START;
25057 #if defined(USE_PREAD)
25058   got = pread(id->h, pBuf, cnt, offset);
25059   SimulateIOError( got = -1 );
25060 #elif defined(USE_PREAD64)
25061   got = pread64(id->h, pBuf, cnt, offset);
25062   SimulateIOError( got = -1 );
25063 #else
25064   newOffset = lseek(id->h, offset, SEEK_SET);
25065   SimulateIOError( newOffset-- );
25066   if( newOffset!=offset ){
25067     if( newOffset == -1 ){
25068       ((unixFile*)id)->lastErrno = errno;
25069     }else{
25070       ((unixFile*)id)->lastErrno = 0;                   
25071     }
25072     return -1;
25073   }
25074   got = read(id->h, pBuf, cnt);
25075 #endif
25076   TIMER_END;
25077   if( got<0 ){
25078     ((unixFile*)id)->lastErrno = errno;
25079   }
25080   OSTRACE(("READ    %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
25081   return got;
25082 }
25083
25084 /*
25085 ** Read data from a file into a buffer.  Return SQLITE_OK if all
25086 ** bytes were read successfully and SQLITE_IOERR if anything goes
25087 ** wrong.
25088 */
25089 static int unixRead(
25090   sqlite3_file *id, 
25091   void *pBuf, 
25092   int amt,
25093   sqlite3_int64 offset
25094 ){
25095   unixFile *pFile = (unixFile *)id;
25096   int got;
25097   assert( id );
25098
25099   /* If this is a database file (not a journal, master-journal or temp
25100   ** file), the bytes in the locking range should never be read or written. */
25101 #if 0
25102   assert( pFile->pUnused==0
25103        || offset>=PENDING_BYTE+512
25104        || offset+amt<=PENDING_BYTE 
25105   );
25106 #endif
25107
25108   got = seekAndRead(pFile, offset, pBuf, amt);
25109   if( got==amt ){
25110     return SQLITE_OK;
25111   }else if( got<0 ){
25112     /* lastErrno set by seekAndRead */
25113     return SQLITE_IOERR_READ;
25114   }else{
25115     pFile->lastErrno = 0; /* not a system error */
25116     /* Unread parts of the buffer must be zero-filled */
25117     memset(&((char*)pBuf)[got], 0, amt-got);
25118     return SQLITE_IOERR_SHORT_READ;
25119   }
25120 }
25121
25122 /*
25123 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
25124 ** Return the number of bytes actually read.  Update the offset.
25125 **
25126 ** To avoid stomping the errno value on a failed write the lastErrno value
25127 ** is set before returning.
25128 */
25129 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
25130   int got;
25131 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
25132   i64 newOffset;
25133 #endif
25134   TIMER_START;
25135 #if defined(USE_PREAD)
25136   got = pwrite(id->h, pBuf, cnt, offset);
25137 #elif defined(USE_PREAD64)
25138   got = pwrite64(id->h, pBuf, cnt, offset);
25139 #else
25140   newOffset = lseek(id->h, offset, SEEK_SET);
25141   if( newOffset!=offset ){
25142     if( newOffset == -1 ){
25143       ((unixFile*)id)->lastErrno = errno;
25144     }else{
25145       ((unixFile*)id)->lastErrno = 0;                   
25146     }
25147     return -1;
25148   }
25149   got = write(id->h, pBuf, cnt);
25150 #endif
25151   TIMER_END;
25152   if( got<0 ){
25153     ((unixFile*)id)->lastErrno = errno;
25154   }
25155
25156   OSTRACE(("WRITE   %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
25157   return got;
25158 }
25159
25160
25161 /*
25162 ** Write data from a buffer into a file.  Return SQLITE_OK on success
25163 ** or some other error code on failure.
25164 */
25165 static int unixWrite(
25166   sqlite3_file *id, 
25167   const void *pBuf, 
25168   int amt,
25169   sqlite3_int64 offset 
25170 ){
25171   unixFile *pFile = (unixFile*)id;
25172   int wrote = 0;
25173   assert( id );
25174   assert( amt>0 );
25175
25176   /* If this is a database file (not a journal, master-journal or temp
25177   ** file), the bytes in the locking range should never be read or written. */
25178 #if 0
25179   assert( pFile->pUnused==0
25180        || offset>=PENDING_BYTE+512
25181        || offset+amt<=PENDING_BYTE 
25182   );
25183 #endif
25184
25185 #ifndef NDEBUG
25186   /* If we are doing a normal write to a database file (as opposed to
25187   ** doing a hot-journal rollback or a write to some file other than a
25188   ** normal database file) then record the fact that the database
25189   ** has changed.  If the transaction counter is modified, record that
25190   ** fact too.
25191   */
25192   if( pFile->inNormalWrite ){
25193     pFile->dbUpdate = 1;  /* The database has been modified */
25194     if( offset<=24 && offset+amt>=27 ){
25195       int rc;
25196       char oldCntr[4];
25197       SimulateIOErrorBenign(1);
25198       rc = seekAndRead(pFile, 24, oldCntr, 4);
25199       SimulateIOErrorBenign(0);
25200       if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
25201         pFile->transCntrChng = 1;  /* The transaction counter has changed */
25202       }
25203     }
25204   }
25205 #endif
25206
25207   while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
25208     amt -= wrote;
25209     offset += wrote;
25210     pBuf = &((char*)pBuf)[wrote];
25211   }
25212   SimulateIOError(( wrote=(-1), amt=1 ));
25213   SimulateDiskfullError(( wrote=0, amt=1 ));
25214   if( amt>0 ){
25215     if( wrote<0 ){
25216       /* lastErrno set by seekAndWrite */
25217       return SQLITE_IOERR_WRITE;
25218     }else{
25219       pFile->lastErrno = 0; /* not a system error */
25220       return SQLITE_FULL;
25221     }
25222   }
25223   return SQLITE_OK;
25224 }
25225
25226 #ifdef SQLITE_TEST
25227 /*
25228 ** Count the number of fullsyncs and normal syncs.  This is used to test
25229 ** that syncs and fullsyncs are occurring at the right times.
25230 */
25231 SQLITE_API int sqlite3_sync_count = 0;
25232 SQLITE_API int sqlite3_fullsync_count = 0;
25233 #endif
25234
25235 /*
25236 ** We do not trust systems to provide a working fdatasync().  Some do.
25237 ** Others do no.  To be safe, we will stick with the (slower) fsync().
25238 ** If you know that your system does support fdatasync() correctly,
25239 ** then simply compile with -Dfdatasync=fdatasync
25240 */
25241 #if !defined(fdatasync) && !defined(__linux__)
25242 # define fdatasync fsync
25243 #endif
25244
25245 /*
25246 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
25247 ** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
25248 ** only available on Mac OS X.  But that could change.
25249 */
25250 #ifdef F_FULLFSYNC
25251 # define HAVE_FULLFSYNC 1
25252 #else
25253 # define HAVE_FULLFSYNC 0
25254 #endif
25255
25256
25257 /*
25258 ** The fsync() system call does not work as advertised on many
25259 ** unix systems.  The following procedure is an attempt to make
25260 ** it work better.
25261 **
25262 ** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
25263 ** for testing when we want to run through the test suite quickly.
25264 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
25265 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
25266 ** or power failure will likely corrupt the database file.
25267 **
25268 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
25269 ** The idea behind dataOnly is that it should only write the file content
25270 ** to disk, not the inode.  We only set dataOnly if the file size is 
25271 ** unchanged since the file size is part of the inode.  However, 
25272 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
25273 ** file size has changed.  The only real difference between fdatasync()
25274 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
25275 ** inode if the mtime or owner or other inode attributes have changed.
25276 ** We only care about the file size, not the other file attributes, so
25277 ** as far as SQLite is concerned, an fdatasync() is always adequate.
25278 ** So, we always use fdatasync() if it is available, regardless of
25279 ** the value of the dataOnly flag.
25280 */
25281 static int full_fsync(int fd, int fullSync, int dataOnly){
25282   int rc;
25283
25284   /* The following "ifdef/elif/else/" block has the same structure as
25285   ** the one below. It is replicated here solely to avoid cluttering 
25286   ** up the real code with the UNUSED_PARAMETER() macros.
25287   */
25288 #ifdef SQLITE_NO_SYNC
25289   UNUSED_PARAMETER(fd);
25290   UNUSED_PARAMETER(fullSync);
25291   UNUSED_PARAMETER(dataOnly);
25292 #elif HAVE_FULLFSYNC
25293   UNUSED_PARAMETER(dataOnly);
25294 #else
25295   UNUSED_PARAMETER(fullSync);
25296   UNUSED_PARAMETER(dataOnly);
25297 #endif
25298
25299   /* Record the number of times that we do a normal fsync() and 
25300   ** FULLSYNC.  This is used during testing to verify that this procedure
25301   ** gets called with the correct arguments.
25302   */
25303 #ifdef SQLITE_TEST
25304   if( fullSync ) sqlite3_fullsync_count++;
25305   sqlite3_sync_count++;
25306 #endif
25307
25308   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
25309   ** no-op
25310   */
25311 #ifdef SQLITE_NO_SYNC
25312   rc = SQLITE_OK;
25313 #elif HAVE_FULLFSYNC
25314   if( fullSync ){
25315     rc = fcntl(fd, F_FULLFSYNC, 0);
25316   }else{
25317     rc = 1;
25318   }
25319   /* If the FULLFSYNC failed, fall back to attempting an fsync().
25320   ** It shouldn't be possible for fullfsync to fail on the local 
25321   ** file system (on OSX), so failure indicates that FULLFSYNC
25322   ** isn't supported for this file system. So, attempt an fsync 
25323   ** and (for now) ignore the overhead of a superfluous fcntl call.  
25324   ** It'd be better to detect fullfsync support once and avoid 
25325   ** the fcntl call every time sync is called.
25326   */
25327   if( rc ) rc = fsync(fd);
25328
25329 #elif defined(__APPLE__)
25330   /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
25331   ** so currently we default to the macro that redefines fdatasync to fsync
25332   */
25333   rc = fsync(fd);
25334 #else 
25335   rc = fdatasync(fd);
25336 #if OS_VXWORKS
25337   if( rc==-1 && errno==ENOTSUP ){
25338     rc = fsync(fd);
25339   }
25340 #endif /* OS_VXWORKS */
25341 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
25342
25343   if( OS_VXWORKS && rc!= -1 ){
25344     rc = 0;
25345   }
25346   return rc;
25347 }
25348
25349 /*
25350 ** Make sure all writes to a particular file are committed to disk.
25351 **
25352 ** If dataOnly==0 then both the file itself and its metadata (file
25353 ** size, access time, etc) are synced.  If dataOnly!=0 then only the
25354 ** file data is synced.
25355 **
25356 ** Under Unix, also make sure that the directory entry for the file
25357 ** has been created by fsync-ing the directory that contains the file.
25358 ** If we do not do this and we encounter a power failure, the directory
25359 ** entry for the journal might not exist after we reboot.  The next
25360 ** SQLite to access the file will not know that the journal exists (because
25361 ** the directory entry for the journal was never created) and the transaction
25362 ** will not roll back - possibly leading to database corruption.
25363 */
25364 static int unixSync(sqlite3_file *id, int flags){
25365   int rc;
25366   unixFile *pFile = (unixFile*)id;
25367
25368   int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
25369   int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
25370
25371   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
25372   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
25373       || (flags&0x0F)==SQLITE_SYNC_FULL
25374   );
25375
25376   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
25377   ** line is to test that doing so does not cause any problems.
25378   */
25379   SimulateDiskfullError( return SQLITE_FULL );
25380
25381   assert( pFile );
25382   OSTRACE(("SYNC    %-3d\n", pFile->h));
25383   rc = full_fsync(pFile->h, isFullsync, isDataOnly);
25384   SimulateIOError( rc=1 );
25385   if( rc ){
25386     pFile->lastErrno = errno;
25387     return SQLITE_IOERR_FSYNC;
25388   }
25389   if( pFile->dirfd>=0 ){
25390     int err;
25391     OSTRACE(("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
25392             HAVE_FULLFSYNC, isFullsync));
25393 #ifndef SQLITE_DISABLE_DIRSYNC
25394     /* The directory sync is only attempted if full_fsync is
25395     ** turned off or unavailable.  If a full_fsync occurred above,
25396     ** then the directory sync is superfluous.
25397     */
25398     if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
25399        /*
25400        ** We have received multiple reports of fsync() returning
25401        ** errors when applied to directories on certain file systems.
25402        ** A failed directory sync is not a big deal.  So it seems
25403        ** better to ignore the error.  Ticket #1657
25404        */
25405        /* pFile->lastErrno = errno; */
25406        /* return SQLITE_IOERR; */
25407     }
25408 #endif
25409     err = close(pFile->dirfd); /* Only need to sync once, so close the */
25410     if( err==0 ){              /* directory when we are done */
25411       pFile->dirfd = -1;
25412     }else{
25413       pFile->lastErrno = errno;
25414       rc = SQLITE_IOERR_DIR_CLOSE;
25415     }
25416   }
25417   return rc;
25418 }
25419
25420 /*
25421 ** Truncate an open file to a specified size
25422 */
25423 static int unixTruncate(sqlite3_file *id, i64 nByte){
25424   int rc;
25425   assert( id );
25426   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
25427   rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
25428   if( rc ){
25429     ((unixFile*)id)->lastErrno = errno;
25430     return SQLITE_IOERR_TRUNCATE;
25431   }else{
25432 #ifndef NDEBUG
25433     /* If we are doing a normal write to a database file (as opposed to
25434     ** doing a hot-journal rollback or a write to some file other than a
25435     ** normal database file) and we truncate the file to zero length,
25436     ** that effectively updates the change counter.  This might happen
25437     ** when restoring a database using the backup API from a zero-length
25438     ** source.
25439     */
25440     if( ((unixFile*)id)->inNormalWrite && nByte==0 ){
25441       ((unixFile*)id)->transCntrChng = 1;
25442     }
25443 #endif
25444
25445     return SQLITE_OK;
25446   }
25447 }
25448
25449 /*
25450 ** Determine the current size of a file in bytes
25451 */
25452 static int unixFileSize(sqlite3_file *id, i64 *pSize){
25453   int rc;
25454   struct stat buf;
25455   assert( id );
25456   rc = fstat(((unixFile*)id)->h, &buf);
25457   SimulateIOError( rc=1 );
25458   if( rc!=0 ){
25459     ((unixFile*)id)->lastErrno = errno;
25460     return SQLITE_IOERR_FSTAT;
25461   }
25462   *pSize = buf.st_size;
25463
25464   /* When opening a zero-size database, the findInodeInfo() procedure
25465   ** writes a single byte into that file in order to work around a bug
25466   ** in the OS-X msdos filesystem.  In order to avoid problems with upper
25467   ** layers, we need to report this file size as zero even though it is
25468   ** really 1.   Ticket #3260.
25469   */
25470   if( *pSize==1 ) *pSize = 0;
25471
25472
25473   return SQLITE_OK;
25474 }
25475
25476 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
25477 /*
25478 ** Handler for proxy-locking file-control verbs.  Defined below in the
25479 ** proxying locking division.
25480 */
25481 static int proxyFileControl(sqlite3_file*,int,void*);
25482 #endif
25483
25484
25485 /*
25486 ** Information and control of an open file handle.
25487 */
25488 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
25489   switch( op ){
25490     case SQLITE_FCNTL_LOCKSTATE: {
25491       *(int*)pArg = ((unixFile*)id)->eFileLock;
25492       return SQLITE_OK;
25493     }
25494     case SQLITE_LAST_ERRNO: {
25495       *(int*)pArg = ((unixFile*)id)->lastErrno;
25496       return SQLITE_OK;
25497     }
25498     case SQLITE_FCNTL_SIZE_HINT: {
25499 #if 0 /* No performance advantage seen on Linux */
25500       sqlite3_int64 szFile = *(sqlite3_int64*)pArg;
25501       unixFile *pFile = (unixFile*)id;
25502       ftruncate(pFile->h, szFile);
25503 #endif
25504       return SQLITE_OK;
25505     }
25506 #ifndef NDEBUG
25507     /* The pager calls this method to signal that it has done
25508     ** a rollback and that the database is therefore unchanged and
25509     ** it hence it is OK for the transaction change counter to be
25510     ** unchanged.
25511     */
25512     case SQLITE_FCNTL_DB_UNCHANGED: {
25513       ((unixFile*)id)->dbUpdate = 0;
25514       return SQLITE_OK;
25515     }
25516 #endif
25517 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
25518     case SQLITE_SET_LOCKPROXYFILE:
25519     case SQLITE_GET_LOCKPROXYFILE: {
25520       return proxyFileControl(id,op,pArg);
25521     }
25522 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
25523   }
25524   return SQLITE_ERROR;
25525 }
25526
25527 /*
25528 ** Return the sector size in bytes of the underlying block device for
25529 ** the specified file. This is almost always 512 bytes, but may be
25530 ** larger for some devices.
25531 **
25532 ** SQLite code assumes this function cannot fail. It also assumes that
25533 ** if two files are created in the same file-system directory (i.e.
25534 ** a database and its journal file) that the sector size will be the
25535 ** same for both.
25536 */
25537 static int unixSectorSize(sqlite3_file *NotUsed){
25538   UNUSED_PARAMETER(NotUsed);
25539   return SQLITE_DEFAULT_SECTOR_SIZE;
25540 }
25541
25542 /*
25543 ** Return the device characteristics for the file. This is always 0 for unix.
25544 */
25545 static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
25546   UNUSED_PARAMETER(NotUsed);
25547   return 0;
25548 }
25549
25550 #ifndef SQLITE_OMIT_WAL
25551
25552
25553 /*
25554 ** Object used to represent an shared memory buffer.  
25555 **
25556 ** When multiple threads all reference the same wal-index, each thread
25557 ** has its own unixShm object, but they all point to a single instance
25558 ** of this unixShmNode object.  In other words, each wal-index is opened
25559 ** only once per process.
25560 **
25561 ** Each unixShmNode object is connected to a single unixInodeInfo object.
25562 ** We could coalesce this object into unixInodeInfo, but that would mean
25563 ** every open file that does not use shared memory (in other words, most
25564 ** open files) would have to carry around this extra information.  So
25565 ** the unixInodeInfo object contains a pointer to this unixShmNode object
25566 ** and the unixShmNode object is created only when needed.
25567 **
25568 ** unixMutexHeld() must be true when creating or destroying
25569 ** this object or while reading or writing the following fields:
25570 **
25571 **      nRef
25572 **
25573 ** The following fields are read-only after the object is created:
25574 ** 
25575 **      fid
25576 **      zFilename
25577 **
25578 ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
25579 ** unixMutexHeld() is true when reading or writing any other field
25580 ** in this structure.
25581 */
25582 struct unixShmNode {
25583   unixInodeInfo *pInode;     /* unixInodeInfo that owns this SHM node */
25584   sqlite3_mutex *mutex;      /* Mutex to access this object */
25585   char *zFilename;           /* Name of the mmapped file */
25586   int h;                     /* Open file descriptor */
25587   int szRegion;              /* Size of shared-memory regions */
25588   int nRegion;               /* Size of array apRegion */
25589   char **apRegion;           /* Array of mapped shared-memory regions */
25590   int nRef;                  /* Number of unixShm objects pointing to this */
25591   unixShm *pFirst;           /* All unixShm objects pointing to this */
25592 #ifdef SQLITE_DEBUG
25593   u8 exclMask;               /* Mask of exclusive locks held */
25594   u8 sharedMask;             /* Mask of shared locks held */
25595   u8 nextShmId;              /* Next available unixShm.id value */
25596 #endif
25597 };
25598
25599 /*
25600 ** Structure used internally by this VFS to record the state of an
25601 ** open shared memory connection.
25602 **
25603 ** The following fields are initialized when this object is created and
25604 ** are read-only thereafter:
25605 **
25606 **    unixShm.pFile
25607 **    unixShm.id
25608 **
25609 ** All other fields are read/write.  The unixShm.pFile->mutex must be held
25610 ** while accessing any read/write fields.
25611 */
25612 struct unixShm {
25613   unixShmNode *pShmNode;     /* The underlying unixShmNode object */
25614   unixShm *pNext;            /* Next unixShm with the same unixShmNode */
25615   u8 hasMutex;               /* True if holding the unixShmNode mutex */
25616   u16 sharedMask;            /* Mask of shared locks held */
25617   u16 exclMask;              /* Mask of exclusive locks held */
25618 #ifdef SQLITE_DEBUG
25619   u8 id;                     /* Id of this connection within its unixShmNode */
25620 #endif
25621 };
25622
25623 /*
25624 ** Constants used for locking
25625 */
25626 #define UNIX_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)         /* first lock byte */
25627 #define UNIX_SHM_DMS    (UNIX_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
25628
25629 /*
25630 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
25631 **
25632 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
25633 ** otherwise.
25634 */
25635 static int unixShmSystemLock(
25636   unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
25637   int lockType,          /* F_UNLCK, F_RDLCK, or F_WRLCK */
25638   int ofst,              /* First byte of the locking range */
25639   int n                  /* Number of bytes to lock */
25640 ){
25641   struct flock f;       /* The posix advisory locking structure */
25642   int rc = SQLITE_OK;   /* Result code form fcntl() */
25643
25644   /* Access to the unixShmNode object is serialized by the caller */
25645   assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
25646
25647   /* Shared locks never span more than one byte */
25648   assert( n==1 || lockType!=F_RDLCK );
25649
25650   /* Locks are within range */
25651   assert( n>=1 && n<SQLITE_SHM_NLOCK );
25652
25653   /* Initialize the locking parameters */
25654   memset(&f, 0, sizeof(f));
25655   f.l_type = lockType;
25656   f.l_whence = SEEK_SET;
25657   f.l_start = ofst;
25658   f.l_len = n;
25659
25660   rc = fcntl(pShmNode->h, F_SETLK, &f);
25661   rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
25662
25663   /* Update the global lock state and do debug tracing */
25664 #ifdef SQLITE_DEBUG
25665   { u16 mask;
25666   OSTRACE(("SHM-LOCK "));
25667   mask = (1<<(ofst+n)) - (1<<ofst);
25668   if( rc==SQLITE_OK ){
25669     if( lockType==F_UNLCK ){
25670       OSTRACE(("unlock %d ok", ofst));
25671       pShmNode->exclMask &= ~mask;
25672       pShmNode->sharedMask &= ~mask;
25673     }else if( lockType==F_RDLCK ){
25674       OSTRACE(("read-lock %d ok", ofst));
25675       pShmNode->exclMask &= ~mask;
25676       pShmNode->sharedMask |= mask;
25677     }else{
25678       assert( lockType==F_WRLCK );
25679       OSTRACE(("write-lock %d ok", ofst));
25680       pShmNode->exclMask |= mask;
25681       pShmNode->sharedMask &= ~mask;
25682     }
25683   }else{
25684     if( lockType==F_UNLCK ){
25685       OSTRACE(("unlock %d failed", ofst));
25686     }else if( lockType==F_RDLCK ){
25687       OSTRACE(("read-lock failed"));
25688     }else{
25689       assert( lockType==F_WRLCK );
25690       OSTRACE(("write-lock %d failed", ofst));
25691     }
25692   }
25693   OSTRACE((" - afterwards %03x,%03x\n",
25694            pShmNode->sharedMask, pShmNode->exclMask));
25695   }
25696 #endif
25697
25698   return rc;        
25699 }
25700
25701
25702 /*
25703 ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
25704 **
25705 ** This is not a VFS shared-memory method; it is a utility function called
25706 ** by VFS shared-memory methods.
25707 */
25708 static void unixShmPurge(unixFile *pFd){
25709   unixShmNode *p = pFd->pInode->pShmNode;
25710   assert( unixMutexHeld() );
25711   if( p && p->nRef==0 ){
25712     int i;
25713     assert( p->pInode==pFd->pInode );
25714     if( p->mutex ) sqlite3_mutex_free(p->mutex);
25715     for(i=0; i<p->nRegion; i++){
25716       munmap(p->apRegion[i], p->szRegion);
25717     }
25718     sqlite3_free(p->apRegion);
25719     if( p->h>=0 ) close(p->h);
25720     p->pInode->pShmNode = 0;
25721     sqlite3_free(p);
25722   }
25723 }
25724
25725 /*
25726 ** Open a shared-memory area associated with open database file pDbFd.  
25727 ** This particular implementation uses mmapped files.
25728 **
25729 ** The file used to implement shared-memory is in the same directory
25730 ** as the open database file and has the same name as the open database
25731 ** file with the "-shm" suffix added.  For example, if the database file
25732 ** is "/home/user1/config.db" then the file that is created and mmapped
25733 ** for shared memory will be called "/home/user1/config.db-shm".  
25734 **
25735 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
25736 ** some other tmpfs mount. But if a file in a different directory
25737 ** from the database file is used, then differing access permissions
25738 ** or a chroot() might cause two different processes on the same
25739 ** database to end up using different files for shared memory - 
25740 ** meaning that their memory would not really be shared - resulting
25741 ** in database corruption.  Nevertheless, this tmpfs file usage
25742 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
25743 ** or the equivalent.  The use of the SQLITE_SHM_DIRECTORY compile-time
25744 ** option results in an incompatible build of SQLite;  builds of SQLite
25745 ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
25746 ** same database file at the same time, database corruption will likely
25747 ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
25748 ** "unsupported" and may go away in a future SQLite release.
25749 **
25750 ** When opening a new shared-memory file, if no other instances of that
25751 ** file are currently open, in this process or in other processes, then
25752 ** the file must be truncated to zero length or have its header cleared.
25753 */
25754 static int unixOpenSharedMemory(unixFile *pDbFd){
25755   struct unixShm *p = 0;          /* The connection to be opened */
25756   struct unixShmNode *pShmNode;   /* The underlying mmapped file */
25757   int rc;                         /* Result code */
25758   unixInodeInfo *pInode;          /* The inode of fd */
25759   char *zShmFilename;             /* Name of the file used for SHM */
25760   int nShmFilename;               /* Size of the SHM filename in bytes */
25761
25762   /* Allocate space for the new unixShm object. */
25763   p = sqlite3_malloc( sizeof(*p) );
25764   if( p==0 ) return SQLITE_NOMEM;
25765   memset(p, 0, sizeof(*p));
25766   assert( pDbFd->pShm==0 );
25767
25768   /* Check to see if a unixShmNode object already exists. Reuse an existing
25769   ** one if present. Create a new one if necessary.
25770   */
25771   unixEnterMutex();
25772   pInode = pDbFd->pInode;
25773   pShmNode = pInode->pShmNode;
25774   if( pShmNode==0 ){
25775     struct stat sStat;                 /* fstat() info for database file */
25776
25777     /* Call fstat() to figure out the permissions on the database file. If
25778     ** a new *-shm file is created, an attempt will be made to create it
25779     ** with the same permissions. The actual permissions the file is created
25780     ** with are subject to the current umask setting.
25781     */
25782     if( fstat(pDbFd->h, &sStat) ){
25783       rc = SQLITE_IOERR_FSTAT;
25784       goto shm_open_err;
25785     }
25786
25787 #ifdef SQLITE_SHM_DIRECTORY
25788     nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 30;
25789 #else
25790     nShmFilename = 5 + (int)strlen(pDbFd->zPath);
25791 #endif
25792     pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
25793     if( pShmNode==0 ){
25794       rc = SQLITE_NOMEM;
25795       goto shm_open_err;
25796     }
25797     memset(pShmNode, 0, sizeof(*pShmNode));
25798     zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
25799 #ifdef SQLITE_SHM_DIRECTORY
25800     sqlite3_snprintf(nShmFilename, zShmFilename, 
25801                      SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
25802                      (u32)sStat.st_ino, (u32)sStat.st_dev);
25803 #else
25804     sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
25805 #endif
25806     pShmNode->h = -1;
25807     pDbFd->pInode->pShmNode = pShmNode;
25808     pShmNode->pInode = pDbFd->pInode;
25809     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
25810     if( pShmNode->mutex==0 ){
25811       rc = SQLITE_NOMEM;
25812       goto shm_open_err;
25813     }
25814
25815     pShmNode->h = open(zShmFilename, O_RDWR|O_CREAT, (sStat.st_mode & 0777));
25816     if( pShmNode->h<0 ){
25817       rc = SQLITE_CANTOPEN_BKPT;
25818       goto shm_open_err;
25819     }
25820
25821     /* Check to see if another process is holding the dead-man switch.
25822     ** If not, truncate the file to zero length. 
25823     */
25824     rc = SQLITE_OK;
25825     if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
25826       if( ftruncate(pShmNode->h, 0) ){
25827         rc = SQLITE_IOERR_SHMOPEN;
25828       }
25829     }
25830     if( rc==SQLITE_OK ){
25831       rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
25832     }
25833     if( rc ) goto shm_open_err;
25834   }
25835
25836   /* Make the new connection a child of the unixShmNode */
25837   p->pShmNode = pShmNode;
25838 #ifdef SQLITE_DEBUG
25839   p->id = pShmNode->nextShmId++;
25840 #endif
25841   pShmNode->nRef++;
25842   pDbFd->pShm = p;
25843   unixLeaveMutex();
25844
25845   /* The reference count on pShmNode has already been incremented under
25846   ** the cover of the unixEnterMutex() mutex and the pointer from the
25847   ** new (struct unixShm) object to the pShmNode has been set. All that is
25848   ** left to do is to link the new object into the linked list starting
25849   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex 
25850   ** mutex.
25851   */
25852   sqlite3_mutex_enter(pShmNode->mutex);
25853   p->pNext = pShmNode->pFirst;
25854   pShmNode->pFirst = p;
25855   sqlite3_mutex_leave(pShmNode->mutex);
25856   return SQLITE_OK;
25857
25858   /* Jump here on any error */
25859 shm_open_err:
25860   unixShmPurge(pDbFd);       /* This call frees pShmNode if required */
25861   sqlite3_free(p);
25862   unixLeaveMutex();
25863   return rc;
25864 }
25865
25866 /*
25867 ** This function is called to obtain a pointer to region iRegion of the 
25868 ** shared-memory associated with the database file fd. Shared-memory regions 
25869 ** are numbered starting from zero. Each shared-memory region is szRegion 
25870 ** bytes in size.
25871 **
25872 ** If an error occurs, an error code is returned and *pp is set to NULL.
25873 **
25874 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
25875 ** region has not been allocated (by any client, including one running in a
25876 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If 
25877 ** bExtend is non-zero and the requested shared-memory region has not yet 
25878 ** been allocated, it is allocated by this function.
25879 **
25880 ** If the shared-memory region has already been allocated or is allocated by
25881 ** this call as described above, then it is mapped into this processes 
25882 ** address space (if it is not already), *pp is set to point to the mapped 
25883 ** memory and SQLITE_OK returned.
25884 */
25885 static int unixShmMap(
25886   sqlite3_file *fd,               /* Handle open on database file */
25887   int iRegion,                    /* Region to retrieve */
25888   int szRegion,                   /* Size of regions */
25889   int bExtend,                    /* True to extend file if necessary */
25890   void volatile **pp              /* OUT: Mapped memory */
25891 ){
25892   unixFile *pDbFd = (unixFile*)fd;
25893   unixShm *p;
25894   unixShmNode *pShmNode;
25895   int rc = SQLITE_OK;
25896
25897   /* If the shared-memory file has not yet been opened, open it now. */
25898   if( pDbFd->pShm==0 ){
25899     rc = unixOpenSharedMemory(pDbFd);
25900     if( rc!=SQLITE_OK ) return rc;
25901   }
25902
25903   p = pDbFd->pShm;
25904   pShmNode = p->pShmNode;
25905   sqlite3_mutex_enter(pShmNode->mutex);
25906   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
25907
25908   if( pShmNode->nRegion<=iRegion ){
25909     char **apNew;                      /* New apRegion[] array */
25910     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
25911     struct stat sStat;                 /* Used by fstat() */
25912
25913     pShmNode->szRegion = szRegion;
25914
25915     /* The requested region is not mapped into this processes address space.
25916     ** Check to see if it has been allocated (i.e. if the wal-index file is
25917     ** large enough to contain the requested region).
25918     */
25919     if( fstat(pShmNode->h, &sStat) ){
25920       rc = SQLITE_IOERR_SHMSIZE;
25921       goto shmpage_out;
25922     }
25923
25924     if( sStat.st_size<nByte ){
25925       /* The requested memory region does not exist. If bExtend is set to
25926       ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
25927       **
25928       ** Alternatively, if bExtend is true, use ftruncate() to allocate
25929       ** the requested memory region.
25930       */
25931       if( !bExtend ) goto shmpage_out;
25932       if( ftruncate(pShmNode->h, nByte) ){
25933         rc = SQLITE_IOERR_SHMSIZE;
25934         goto shmpage_out;
25935       }
25936     }
25937
25938     /* Map the requested memory region into this processes address space. */
25939     apNew = (char **)sqlite3_realloc(
25940         pShmNode->apRegion, (iRegion+1)*sizeof(char *)
25941     );
25942     if( !apNew ){
25943       rc = SQLITE_IOERR_NOMEM;
25944       goto shmpage_out;
25945     }
25946     pShmNode->apRegion = apNew;
25947     while(pShmNode->nRegion<=iRegion){
25948       void *pMem = mmap(0, szRegion, PROT_READ|PROT_WRITE, 
25949           MAP_SHARED, pShmNode->h, iRegion*szRegion
25950       );
25951       if( pMem==MAP_FAILED ){
25952         rc = SQLITE_IOERR;
25953         goto shmpage_out;
25954       }
25955       pShmNode->apRegion[pShmNode->nRegion] = pMem;
25956       pShmNode->nRegion++;
25957     }
25958   }
25959
25960 shmpage_out:
25961   if( pShmNode->nRegion>iRegion ){
25962     *pp = pShmNode->apRegion[iRegion];
25963   }else{
25964     *pp = 0;
25965   }
25966   sqlite3_mutex_leave(pShmNode->mutex);
25967   return rc;
25968 }
25969
25970 /*
25971 ** Change the lock state for a shared-memory segment.
25972 **
25973 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
25974 ** different here than in posix.  In xShmLock(), one can go from unlocked
25975 ** to shared and back or from unlocked to exclusive and back.  But one may
25976 ** not go from shared to exclusive or from exclusive to shared.
25977 */
25978 static int unixShmLock(
25979   sqlite3_file *fd,          /* Database file holding the shared memory */
25980   int ofst,                  /* First lock to acquire or release */
25981   int n,                     /* Number of locks to acquire or release */
25982   int flags                  /* What to do with the lock */
25983 ){
25984   unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */
25985   unixShm *p = pDbFd->pShm;             /* The shared memory being locked */
25986   unixShm *pX;                          /* For looping over all siblings */
25987   unixShmNode *pShmNode = p->pShmNode;  /* The underlying file iNode */
25988   int rc = SQLITE_OK;                   /* Result code */
25989   u16 mask;                             /* Mask of locks to take or release */
25990
25991   assert( pShmNode==pDbFd->pInode->pShmNode );
25992   assert( pShmNode->pInode==pDbFd->pInode );
25993   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
25994   assert( n>=1 );
25995   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
25996        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
25997        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
25998        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
25999   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
26000
26001   mask = (1<<(ofst+n)) - (1<<ofst);
26002   assert( n>1 || mask==(1<<ofst) );
26003   sqlite3_mutex_enter(pShmNode->mutex);
26004   if( flags & SQLITE_SHM_UNLOCK ){
26005     u16 allMask = 0; /* Mask of locks held by siblings */
26006
26007     /* See if any siblings hold this same lock */
26008     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
26009       if( pX==p ) continue;
26010       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
26011       allMask |= pX->sharedMask;
26012     }
26013
26014     /* Unlock the system-level locks */
26015     if( (mask & allMask)==0 ){
26016       rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
26017     }else{
26018       rc = SQLITE_OK;
26019     }
26020
26021     /* Undo the local locks */
26022     if( rc==SQLITE_OK ){
26023       p->exclMask &= ~mask;
26024       p->sharedMask &= ~mask;
26025     } 
26026   }else if( flags & SQLITE_SHM_SHARED ){
26027     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
26028
26029     /* Find out which shared locks are already held by sibling connections.
26030     ** If any sibling already holds an exclusive lock, go ahead and return
26031     ** SQLITE_BUSY.
26032     */
26033     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
26034       if( (pX->exclMask & mask)!=0 ){
26035         rc = SQLITE_BUSY;
26036         break;
26037       }
26038       allShared |= pX->sharedMask;
26039     }
26040
26041     /* Get shared locks at the system level, if necessary */
26042     if( rc==SQLITE_OK ){
26043       if( (allShared & mask)==0 ){
26044         rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
26045       }else{
26046         rc = SQLITE_OK;
26047       }
26048     }
26049
26050     /* Get the local shared locks */
26051     if( rc==SQLITE_OK ){
26052       p->sharedMask |= mask;
26053     }
26054   }else{
26055     /* Make sure no sibling connections hold locks that will block this
26056     ** lock.  If any do, return SQLITE_BUSY right away.
26057     */
26058     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
26059       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
26060         rc = SQLITE_BUSY;
26061         break;
26062       }
26063     }
26064   
26065     /* Get the exclusive locks at the system level.  Then if successful
26066     ** also mark the local connection as being locked.
26067     */
26068     if( rc==SQLITE_OK ){
26069       rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
26070       if( rc==SQLITE_OK ){
26071         assert( (p->sharedMask & mask)==0 );
26072         p->exclMask |= mask;
26073       }
26074     }
26075   }
26076   sqlite3_mutex_leave(pShmNode->mutex);
26077   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
26078            p->id, getpid(), p->sharedMask, p->exclMask));
26079   return rc;
26080 }
26081
26082 /*
26083 ** Implement a memory barrier or memory fence on shared memory.  
26084 **
26085 ** All loads and stores begun before the barrier must complete before
26086 ** any load or store begun after the barrier.
26087 */
26088 static void unixShmBarrier(
26089   sqlite3_file *fd                /* Database file holding the shared memory */
26090 ){
26091   UNUSED_PARAMETER(fd);
26092   unixEnterMutex();
26093   unixLeaveMutex();
26094 }
26095
26096 /*
26097 ** Close a connection to shared-memory.  Delete the underlying 
26098 ** storage if deleteFlag is true.
26099 **
26100 ** If there is no shared memory associated with the connection then this
26101 ** routine is a harmless no-op.
26102 */
26103 static int unixShmUnmap(
26104   sqlite3_file *fd,               /* The underlying database file */
26105   int deleteFlag                  /* Delete shared-memory if true */
26106 ){
26107   unixShm *p;                     /* The connection to be closed */
26108   unixShmNode *pShmNode;          /* The underlying shared-memory file */
26109   unixShm **pp;                   /* For looping over sibling connections */
26110   unixFile *pDbFd;                /* The underlying database file */
26111
26112   pDbFd = (unixFile*)fd;
26113   p = pDbFd->pShm;
26114   if( p==0 ) return SQLITE_OK;
26115   pShmNode = p->pShmNode;
26116
26117   assert( pShmNode==pDbFd->pInode->pShmNode );
26118   assert( pShmNode->pInode==pDbFd->pInode );
26119
26120   /* Remove connection p from the set of connections associated
26121   ** with pShmNode */
26122   sqlite3_mutex_enter(pShmNode->mutex);
26123   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
26124   *pp = p->pNext;
26125
26126   /* Free the connection p */
26127   sqlite3_free(p);
26128   pDbFd->pShm = 0;
26129   sqlite3_mutex_leave(pShmNode->mutex);
26130
26131   /* If pShmNode->nRef has reached 0, then close the underlying
26132   ** shared-memory file, too */
26133   unixEnterMutex();
26134   assert( pShmNode->nRef>0 );
26135   pShmNode->nRef--;
26136   if( pShmNode->nRef==0 ){
26137     if( deleteFlag ) unlink(pShmNode->zFilename);
26138     unixShmPurge(pDbFd);
26139   }
26140   unixLeaveMutex();
26141
26142   return SQLITE_OK;
26143 }
26144
26145
26146 #else
26147 # define unixShmMap     0
26148 # define unixShmLock    0
26149 # define unixShmBarrier 0
26150 # define unixShmUnmap   0
26151 #endif /* #ifndef SQLITE_OMIT_WAL */
26152
26153 /*
26154 ** Here ends the implementation of all sqlite3_file methods.
26155 **
26156 ********************** End sqlite3_file Methods *******************************
26157 ******************************************************************************/
26158
26159 /*
26160 ** This division contains definitions of sqlite3_io_methods objects that
26161 ** implement various file locking strategies.  It also contains definitions
26162 ** of "finder" functions.  A finder-function is used to locate the appropriate
26163 ** sqlite3_io_methods object for a particular database file.  The pAppData
26164 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
26165 ** the correct finder-function for that VFS.
26166 **
26167 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
26168 ** object.  The only interesting finder-function is autolockIoFinder, which
26169 ** looks at the filesystem type and tries to guess the best locking
26170 ** strategy from that.
26171 **
26172 ** For finder-funtion F, two objects are created:
26173 **
26174 **    (1) The real finder-function named "FImpt()".
26175 **
26176 **    (2) A constant pointer to this function named just "F".
26177 **
26178 **
26179 ** A pointer to the F pointer is used as the pAppData value for VFS
26180 ** objects.  We have to do this instead of letting pAppData point
26181 ** directly at the finder-function since C90 rules prevent a void*
26182 ** from be cast into a function pointer.
26183 **
26184 **
26185 ** Each instance of this macro generates two objects:
26186 **
26187 **   *  A constant sqlite3_io_methods object call METHOD that has locking
26188 **      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
26189 **
26190 **   *  An I/O method finder function called FINDER that returns a pointer
26191 **      to the METHOD object in the previous bullet.
26192 */
26193 #define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK)      \
26194 static const sqlite3_io_methods METHOD = {                                   \
26195    VERSION,                    /* iVersion */                                \
26196    CLOSE,                      /* xClose */                                  \
26197    unixRead,                   /* xRead */                                   \
26198    unixWrite,                  /* xWrite */                                  \
26199    unixTruncate,               /* xTruncate */                               \
26200    unixSync,                   /* xSync */                                   \
26201    unixFileSize,               /* xFileSize */                               \
26202    LOCK,                       /* xLock */                                   \
26203    UNLOCK,                     /* xUnlock */                                 \
26204    CKLOCK,                     /* xCheckReservedLock */                      \
26205    unixFileControl,            /* xFileControl */                            \
26206    unixSectorSize,             /* xSectorSize */                             \
26207    unixDeviceCharacteristics,  /* xDeviceCapabilities */                     \
26208    unixShmMap,                 /* xShmMap */                                 \
26209    unixShmLock,                /* xShmLock */                                \
26210    unixShmBarrier,             /* xShmBarrier */                             \
26211    unixShmUnmap                /* xShmUnmap */                               \
26212 };                                                                           \
26213 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
26214   UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
26215   return &METHOD;                                                            \
26216 }                                                                            \
26217 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
26218     = FINDER##Impl;
26219
26220 /*
26221 ** Here are all of the sqlite3_io_methods objects for each of the
26222 ** locking strategies.  Functions that return pointers to these methods
26223 ** are also created.
26224 */
26225 IOMETHODS(
26226   posixIoFinder,            /* Finder function name */
26227   posixIoMethods,           /* sqlite3_io_methods object name */
26228   2,                        /* shared memory is enabled */
26229   unixClose,                /* xClose method */
26230   unixLock,                 /* xLock method */
26231   unixUnlock,               /* xUnlock method */
26232   unixCheckReservedLock     /* xCheckReservedLock method */
26233 )
26234 IOMETHODS(
26235   nolockIoFinder,           /* Finder function name */
26236   nolockIoMethods,          /* sqlite3_io_methods object name */
26237   1,                        /* shared memory is disabled */
26238   nolockClose,              /* xClose method */
26239   nolockLock,               /* xLock method */
26240   nolockUnlock,             /* xUnlock method */
26241   nolockCheckReservedLock   /* xCheckReservedLock method */
26242 )
26243 IOMETHODS(
26244   dotlockIoFinder,          /* Finder function name */
26245   dotlockIoMethods,         /* sqlite3_io_methods object name */
26246   1,                        /* shared memory is disabled */
26247   dotlockClose,             /* xClose method */
26248   dotlockLock,              /* xLock method */
26249   dotlockUnlock,            /* xUnlock method */
26250   dotlockCheckReservedLock  /* xCheckReservedLock method */
26251 )
26252
26253 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
26254 IOMETHODS(
26255   flockIoFinder,            /* Finder function name */
26256   flockIoMethods,           /* sqlite3_io_methods object name */
26257   1,                        /* shared memory is disabled */
26258   flockClose,               /* xClose method */
26259   flockLock,                /* xLock method */
26260   flockUnlock,              /* xUnlock method */
26261   flockCheckReservedLock    /* xCheckReservedLock method */
26262 )
26263 #endif
26264
26265 #if OS_VXWORKS
26266 IOMETHODS(
26267   semIoFinder,              /* Finder function name */
26268   semIoMethods,             /* sqlite3_io_methods object name */
26269   1,                        /* shared memory is disabled */
26270   semClose,                 /* xClose method */
26271   semLock,                  /* xLock method */
26272   semUnlock,                /* xUnlock method */
26273   semCheckReservedLock      /* xCheckReservedLock method */
26274 )
26275 #endif
26276
26277 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26278 IOMETHODS(
26279   afpIoFinder,              /* Finder function name */
26280   afpIoMethods,             /* sqlite3_io_methods object name */
26281   1,                        /* shared memory is disabled */
26282   afpClose,                 /* xClose method */
26283   afpLock,                  /* xLock method */
26284   afpUnlock,                /* xUnlock method */
26285   afpCheckReservedLock      /* xCheckReservedLock method */
26286 )
26287 #endif
26288
26289 /*
26290 ** The proxy locking method is a "super-method" in the sense that it
26291 ** opens secondary file descriptors for the conch and lock files and
26292 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
26293 ** secondary files.  For this reason, the division that implements
26294 ** proxy locking is located much further down in the file.  But we need
26295 ** to go ahead and define the sqlite3_io_methods and finder function
26296 ** for proxy locking here.  So we forward declare the I/O methods.
26297 */
26298 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26299 static int proxyClose(sqlite3_file*);
26300 static int proxyLock(sqlite3_file*, int);
26301 static int proxyUnlock(sqlite3_file*, int);
26302 static int proxyCheckReservedLock(sqlite3_file*, int*);
26303 IOMETHODS(
26304   proxyIoFinder,            /* Finder function name */
26305   proxyIoMethods,           /* sqlite3_io_methods object name */
26306   1,                        /* shared memory is disabled */
26307   proxyClose,               /* xClose method */
26308   proxyLock,                /* xLock method */
26309   proxyUnlock,              /* xUnlock method */
26310   proxyCheckReservedLock    /* xCheckReservedLock method */
26311 )
26312 #endif
26313
26314 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
26315 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26316 IOMETHODS(
26317   nfsIoFinder,               /* Finder function name */
26318   nfsIoMethods,              /* sqlite3_io_methods object name */
26319   1,                         /* shared memory is disabled */
26320   unixClose,                 /* xClose method */
26321   unixLock,                  /* xLock method */
26322   nfsUnlock,                 /* xUnlock method */
26323   unixCheckReservedLock      /* xCheckReservedLock method */
26324 )
26325 #endif
26326
26327 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26328 /* 
26329 ** This "finder" function attempts to determine the best locking strategy 
26330 ** for the database file "filePath".  It then returns the sqlite3_io_methods
26331 ** object that implements that strategy.
26332 **
26333 ** This is for MacOSX only.
26334 */
26335 static const sqlite3_io_methods *autolockIoFinderImpl(
26336   const char *filePath,    /* name of the database file */
26337   unixFile *pNew           /* open file object for the database file */
26338 ){
26339   static const struct Mapping {
26340     const char *zFilesystem;              /* Filesystem type name */
26341     const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
26342   } aMap[] = {
26343     { "hfs",    &posixIoMethods },
26344     { "ufs",    &posixIoMethods },
26345     { "afpfs",  &afpIoMethods },
26346     { "smbfs",  &afpIoMethods },
26347     { "webdav", &nolockIoMethods },
26348     { 0, 0 }
26349   };
26350   int i;
26351   struct statfs fsInfo;
26352   struct flock lockInfo;
26353
26354   if( !filePath ){
26355     /* If filePath==NULL that means we are dealing with a transient file
26356     ** that does not need to be locked. */
26357     return &nolockIoMethods;
26358   }
26359   if( statfs(filePath, &fsInfo) != -1 ){
26360     if( fsInfo.f_flags & MNT_RDONLY ){
26361       return &nolockIoMethods;
26362     }
26363     for(i=0; aMap[i].zFilesystem; i++){
26364       if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
26365         return aMap[i].pMethods;
26366       }
26367     }
26368   }
26369
26370   /* Default case. Handles, amongst others, "nfs".
26371   ** Test byte-range lock using fcntl(). If the call succeeds, 
26372   ** assume that the file-system supports POSIX style locks. 
26373   */
26374   lockInfo.l_len = 1;
26375   lockInfo.l_start = 0;
26376   lockInfo.l_whence = SEEK_SET;
26377   lockInfo.l_type = F_RDLCK;
26378   if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
26379     if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
26380       return &nfsIoMethods;
26381     } else {
26382       return &posixIoMethods;
26383     }
26384   }else{
26385     return &dotlockIoMethods;
26386   }
26387 }
26388 static const sqlite3_io_methods 
26389   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
26390
26391 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
26392
26393 #if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
26394 /* 
26395 ** This "finder" function attempts to determine the best locking strategy 
26396 ** for the database file "filePath".  It then returns the sqlite3_io_methods
26397 ** object that implements that strategy.
26398 **
26399 ** This is for VXWorks only.
26400 */
26401 static const sqlite3_io_methods *autolockIoFinderImpl(
26402   const char *filePath,    /* name of the database file */
26403   unixFile *pNew           /* the open file object */
26404 ){
26405   struct flock lockInfo;
26406
26407   if( !filePath ){
26408     /* If filePath==NULL that means we are dealing with a transient file
26409     ** that does not need to be locked. */
26410     return &nolockIoMethods;
26411   }
26412
26413   /* Test if fcntl() is supported and use POSIX style locks.
26414   ** Otherwise fall back to the named semaphore method.
26415   */
26416   lockInfo.l_len = 1;
26417   lockInfo.l_start = 0;
26418   lockInfo.l_whence = SEEK_SET;
26419   lockInfo.l_type = F_RDLCK;
26420   if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
26421     return &posixIoMethods;
26422   }else{
26423     return &semIoMethods;
26424   }
26425 }
26426 static const sqlite3_io_methods 
26427   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
26428
26429 #endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
26430
26431 /*
26432 ** An abstract type for a pointer to a IO method finder function:
26433 */
26434 typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
26435
26436
26437 /****************************************************************************
26438 **************************** sqlite3_vfs methods ****************************
26439 **
26440 ** This division contains the implementation of methods on the
26441 ** sqlite3_vfs object.
26442 */
26443
26444 /*
26445 ** Initialize the contents of the unixFile structure pointed to by pId.
26446 */
26447 static int fillInUnixFile(
26448   sqlite3_vfs *pVfs,      /* Pointer to vfs object */
26449   int h,                  /* Open file descriptor of file being opened */
26450   int dirfd,              /* Directory file descriptor */
26451   sqlite3_file *pId,      /* Write to the unixFile structure here */
26452   const char *zFilename,  /* Name of the file being opened */
26453   int noLock,             /* Omit locking if true */
26454   int isDelete            /* Delete on close if true */
26455 ){
26456   const sqlite3_io_methods *pLockingStyle;
26457   unixFile *pNew = (unixFile *)pId;
26458   int rc = SQLITE_OK;
26459
26460   assert( pNew->pInode==NULL );
26461
26462   /* Parameter isDelete is only used on vxworks. Express this explicitly 
26463   ** here to prevent compiler warnings about unused parameters.
26464   */
26465   UNUSED_PARAMETER(isDelete);
26466
26467   OSTRACE(("OPEN    %-3d %s\n", h, zFilename));
26468   pNew->h = h;
26469   pNew->dirfd = dirfd;
26470   pNew->fileFlags = 0;
26471   assert( zFilename==0 || zFilename[0]=='/' );  /* Never a relative pathname */
26472   pNew->zPath = zFilename;
26473
26474 #if OS_VXWORKS
26475   pNew->pId = vxworksFindFileId(zFilename);
26476   if( pNew->pId==0 ){
26477     noLock = 1;
26478     rc = SQLITE_NOMEM;
26479   }
26480 #endif
26481
26482   if( noLock ){
26483     pLockingStyle = &nolockIoMethods;
26484   }else{
26485     pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
26486 #if SQLITE_ENABLE_LOCKING_STYLE
26487     /* Cache zFilename in the locking context (AFP and dotlock override) for
26488     ** proxyLock activation is possible (remote proxy is based on db name)
26489     ** zFilename remains valid until file is closed, to support */
26490     pNew->lockingContext = (void*)zFilename;
26491 #endif
26492   }
26493
26494   if( pLockingStyle == &posixIoMethods
26495 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26496     || pLockingStyle == &nfsIoMethods
26497 #endif
26498   ){
26499     unixEnterMutex();
26500     rc = findInodeInfo(pNew, &pNew->pInode);
26501     if( rc!=SQLITE_OK ){
26502       /* If an error occured in findInodeInfo(), close the file descriptor
26503       ** immediately, before releasing the mutex. findInodeInfo() may fail
26504       ** in two scenarios:
26505       **
26506       **   (a) A call to fstat() failed.
26507       **   (b) A malloc failed.
26508       **
26509       ** Scenario (b) may only occur if the process is holding no other
26510       ** file descriptors open on the same file. If there were other file
26511       ** descriptors on this file, then no malloc would be required by
26512       ** findInodeInfo(). If this is the case, it is quite safe to close
26513       ** handle h - as it is guaranteed that no posix locks will be released
26514       ** by doing so.
26515       **
26516       ** If scenario (a) caused the error then things are not so safe. The
26517       ** implicit assumption here is that if fstat() fails, things are in
26518       ** such bad shape that dropping a lock or two doesn't matter much.
26519       */
26520       close(h);
26521       h = -1;
26522     }
26523     unixLeaveMutex();
26524   }
26525
26526 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
26527   else if( pLockingStyle == &afpIoMethods ){
26528     /* AFP locking uses the file path so it needs to be included in
26529     ** the afpLockingContext.
26530     */
26531     afpLockingContext *pCtx;
26532     pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
26533     if( pCtx==0 ){
26534       rc = SQLITE_NOMEM;
26535     }else{
26536       /* NB: zFilename exists and remains valid until the file is closed
26537       ** according to requirement F11141.  So we do not need to make a
26538       ** copy of the filename. */
26539       pCtx->dbPath = zFilename;
26540       pCtx->reserved = 0;
26541       srandomdev();
26542       unixEnterMutex();
26543       rc = findInodeInfo(pNew, &pNew->pInode);
26544       if( rc!=SQLITE_OK ){
26545         sqlite3_free(pNew->lockingContext);
26546         close(h);
26547         h = -1;
26548       }
26549       unixLeaveMutex();        
26550     }
26551   }
26552 #endif
26553
26554   else if( pLockingStyle == &dotlockIoMethods ){
26555     /* Dotfile locking uses the file path so it needs to be included in
26556     ** the dotlockLockingContext 
26557     */
26558     char *zLockFile;
26559     int nFilename;
26560     nFilename = (int)strlen(zFilename) + 6;
26561     zLockFile = (char *)sqlite3_malloc(nFilename);
26562     if( zLockFile==0 ){
26563       rc = SQLITE_NOMEM;
26564     }else{
26565       sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
26566     }
26567     pNew->lockingContext = zLockFile;
26568   }
26569
26570 #if OS_VXWORKS
26571   else if( pLockingStyle == &semIoMethods ){
26572     /* Named semaphore locking uses the file path so it needs to be
26573     ** included in the semLockingContext
26574     */
26575     unixEnterMutex();
26576     rc = findInodeInfo(pNew, &pNew->pInode);
26577     if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
26578       char *zSemName = pNew->pInode->aSemName;
26579       int n;
26580       sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
26581                        pNew->pId->zCanonicalName);
26582       for( n=1; zSemName[n]; n++ )
26583         if( zSemName[n]=='/' ) zSemName[n] = '_';
26584       pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
26585       if( pNew->pInode->pSem == SEM_FAILED ){
26586         rc = SQLITE_NOMEM;
26587         pNew->pInode->aSemName[0] = '\0';
26588       }
26589     }
26590     unixLeaveMutex();
26591   }
26592 #endif
26593   
26594   pNew->lastErrno = 0;
26595 #if OS_VXWORKS
26596   if( rc!=SQLITE_OK ){
26597     if( h>=0 ) close(h);
26598     h = -1;
26599     unlink(zFilename);
26600     isDelete = 0;
26601   }
26602   pNew->isDelete = isDelete;
26603 #endif
26604   if( rc!=SQLITE_OK ){
26605     if( dirfd>=0 ) close(dirfd); /* silent leak if fail, already in error */
26606     if( h>=0 ) close(h);
26607   }else{
26608     pNew->pMethod = pLockingStyle;
26609     OpenCounter(+1);
26610   }
26611   return rc;
26612 }
26613
26614 /*
26615 ** Open a file descriptor to the directory containing file zFilename.
26616 ** If successful, *pFd is set to the opened file descriptor and
26617 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
26618 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
26619 ** value.
26620 **
26621 ** If SQLITE_OK is returned, the caller is responsible for closing
26622 ** the file descriptor *pFd using close().
26623 */
26624 static int openDirectory(const char *zFilename, int *pFd){
26625   int ii;
26626   int fd = -1;
26627   char zDirname[MAX_PATHNAME+1];
26628
26629   sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
26630   for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
26631   if( ii>0 ){
26632     zDirname[ii] = '\0';
26633     fd = open(zDirname, O_RDONLY|O_BINARY, 0);
26634     if( fd>=0 ){
26635 #ifdef FD_CLOEXEC
26636       fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
26637 #endif
26638       OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
26639     }
26640   }
26641   *pFd = fd;
26642   return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN_BKPT);
26643 }
26644
26645 /*
26646 ** Return the name of a directory in which to put temporary files.
26647 ** If no suitable temporary file directory can be found, return NULL.
26648 */
26649 static const char *unixTempFileDir(void){
26650   static const char *azDirs[] = {
26651      0,
26652      0,
26653      "/var/tmp",
26654      "/usr/tmp",
26655      "/tmp",
26656      0        /* List terminator */
26657   };
26658   unsigned int i;
26659   struct stat buf;
26660   const char *zDir = 0;
26661
26662   azDirs[0] = sqlite3_temp_directory;
26663   if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
26664   for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
26665     if( zDir==0 ) continue;
26666     if( stat(zDir, &buf) ) continue;
26667     if( !S_ISDIR(buf.st_mode) ) continue;
26668     if( access(zDir, 07) ) continue;
26669     break;
26670   }
26671   return zDir;
26672 }
26673
26674 /*
26675 ** Create a temporary file name in zBuf.  zBuf must be allocated
26676 ** by the calling process and must be big enough to hold at least
26677 ** pVfs->mxPathname bytes.
26678 */
26679 static int unixGetTempname(int nBuf, char *zBuf){
26680   static const unsigned char zChars[] =
26681     "abcdefghijklmnopqrstuvwxyz"
26682     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
26683     "0123456789";
26684   unsigned int i, j;
26685   const char *zDir;
26686
26687   /* It's odd to simulate an io-error here, but really this is just
26688   ** using the io-error infrastructure to test that SQLite handles this
26689   ** function failing. 
26690   */
26691   SimulateIOError( return SQLITE_IOERR );
26692
26693   zDir = unixTempFileDir();
26694   if( zDir==0 ) zDir = ".";
26695
26696   /* Check that the output buffer is large enough for the temporary file 
26697   ** name. If it is not, return SQLITE_ERROR.
26698   */
26699   if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
26700     return SQLITE_ERROR;
26701   }
26702
26703   do{
26704     sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
26705     j = (int)strlen(zBuf);
26706     sqlite3_randomness(15, &zBuf[j]);
26707     for(i=0; i<15; i++, j++){
26708       zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
26709     }
26710     zBuf[j] = 0;
26711   }while( access(zBuf,0)==0 );
26712   return SQLITE_OK;
26713 }
26714
26715 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
26716 /*
26717 ** Routine to transform a unixFile into a proxy-locking unixFile.
26718 ** Implementation in the proxy-lock division, but used by unixOpen()
26719 ** if SQLITE_PREFER_PROXY_LOCKING is defined.
26720 */
26721 static int proxyTransformUnixFile(unixFile*, const char*);
26722 #endif
26723
26724 /*
26725 ** Search for an unused file descriptor that was opened on the database 
26726 ** file (not a journal or master-journal file) identified by pathname
26727 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
26728 ** argument to this function.
26729 **
26730 ** Such a file descriptor may exist if a database connection was closed
26731 ** but the associated file descriptor could not be closed because some
26732 ** other file descriptor open on the same file is holding a file-lock.
26733 ** Refer to comments in the unixClose() function and the lengthy comment
26734 ** describing "Posix Advisory Locking" at the start of this file for 
26735 ** further details. Also, ticket #4018.
26736 **
26737 ** If a suitable file descriptor is found, then it is returned. If no
26738 ** such file descriptor is located, -1 is returned.
26739 */
26740 static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
26741   UnixUnusedFd *pUnused = 0;
26742
26743   /* Do not search for an unused file descriptor on vxworks. Not because
26744   ** vxworks would not benefit from the change (it might, we're not sure),
26745   ** but because no way to test it is currently available. It is better 
26746   ** not to risk breaking vxworks support for the sake of such an obscure 
26747   ** feature.  */
26748 #if !OS_VXWORKS
26749   struct stat sStat;                   /* Results of stat() call */
26750
26751   /* A stat() call may fail for various reasons. If this happens, it is
26752   ** almost certain that an open() call on the same path will also fail.
26753   ** For this reason, if an error occurs in the stat() call here, it is
26754   ** ignored and -1 is returned. The caller will try to open a new file
26755   ** descriptor on the same path, fail, and return an error to SQLite.
26756   **
26757   ** Even if a subsequent open() call does succeed, the consequences of
26758   ** not searching for a resusable file descriptor are not dire.  */
26759   if( 0==stat(zPath, &sStat) ){
26760     unixInodeInfo *pInode;
26761
26762     unixEnterMutex();
26763     pInode = inodeList;
26764     while( pInode && (pInode->fileId.dev!=sStat.st_dev
26765                      || pInode->fileId.ino!=sStat.st_ino) ){
26766        pInode = pInode->pNext;
26767     }
26768     if( pInode ){
26769       UnixUnusedFd **pp;
26770       for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
26771       pUnused = *pp;
26772       if( pUnused ){
26773         *pp = pUnused->pNext;
26774       }
26775     }
26776     unixLeaveMutex();
26777   }
26778 #endif    /* if !OS_VXWORKS */
26779   return pUnused;
26780 }
26781
26782 /*
26783 ** This function is called by unixOpen() to determine the unix permissions
26784 ** to create new files with. If no error occurs, then SQLITE_OK is returned
26785 ** and a value suitable for passing as the third argument to open(2) is
26786 ** written to *pMode. If an IO error occurs, an SQLite error code is 
26787 ** returned and the value of *pMode is not modified.
26788 **
26789 ** If the file being opened is a temporary file, it is always created with
26790 ** the octal permissions 0600 (read/writable by owner only). If the file
26791 ** is a database or master journal file, it is created with the permissions 
26792 ** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
26793 **
26794 ** Finally, if the file being opened is a WAL or regular journal file, then 
26795 ** this function queries the file-system for the permissions on the 
26796 ** corresponding database file and sets *pMode to this value. Whenever 
26797 ** possible, WAL and journal files are created using the same permissions 
26798 ** as the associated database file.
26799 */
26800 static int findCreateFileMode(
26801   const char *zPath,              /* Path of file (possibly) being created */
26802   int flags,                      /* Flags passed as 4th argument to xOpen() */
26803   mode_t *pMode                   /* OUT: Permissions to open file with */
26804 ){
26805   int rc = SQLITE_OK;             /* Return Code */
26806   if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
26807     char zDb[MAX_PATHNAME+1];     /* Database file path */
26808     int nDb;                      /* Number of valid bytes in zDb */
26809     struct stat sStat;            /* Output of stat() on database file */
26810
26811     nDb = sqlite3Strlen30(zPath) - ((flags & SQLITE_OPEN_WAL) ? 4 : 8);
26812     memcpy(zDb, zPath, nDb);
26813     zDb[nDb] = '\0';
26814     if( 0==stat(zDb, &sStat) ){
26815       *pMode = sStat.st_mode & 0777;
26816     }else{
26817       rc = SQLITE_IOERR_FSTAT;
26818     }
26819   }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
26820     *pMode = 0600;
26821   }else{
26822     *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
26823   }
26824   return rc;
26825 }
26826
26827 /*
26828 ** Open the file zPath.
26829 ** 
26830 ** Previously, the SQLite OS layer used three functions in place of this
26831 ** one:
26832 **
26833 **     sqlite3OsOpenReadWrite();
26834 **     sqlite3OsOpenReadOnly();
26835 **     sqlite3OsOpenExclusive();
26836 **
26837 ** These calls correspond to the following combinations of flags:
26838 **
26839 **     ReadWrite() ->     (READWRITE | CREATE)
26840 **     ReadOnly()  ->     (READONLY) 
26841 **     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
26842 **
26843 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
26844 ** true, the file was configured to be automatically deleted when the
26845 ** file handle closed. To achieve the same effect using this new 
26846 ** interface, add the DELETEONCLOSE flag to those specified above for 
26847 ** OpenExclusive().
26848 */
26849 static int unixOpen(
26850   sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
26851   const char *zPath,           /* Pathname of file to be opened */
26852   sqlite3_file *pFile,         /* The file descriptor to be filled in */
26853   int flags,                   /* Input flags to control the opening */
26854   int *pOutFlags               /* Output flags returned to SQLite core */
26855 ){
26856   unixFile *p = (unixFile *)pFile;
26857   int fd = -1;                   /* File descriptor returned by open() */
26858   int dirfd = -1;                /* Directory file descriptor */
26859   int openFlags = 0;             /* Flags to pass to open() */
26860   int eType = flags&0xFFFFFF00;  /* Type of file to open */
26861   int noLock;                    /* True to omit locking primitives */
26862   int rc = SQLITE_OK;            /* Function Return Code */
26863
26864   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
26865   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
26866   int isCreate     = (flags & SQLITE_OPEN_CREATE);
26867   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
26868   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
26869 #if SQLITE_ENABLE_LOCKING_STYLE
26870   int isAutoProxy  = (flags & SQLITE_OPEN_AUTOPROXY);
26871 #endif
26872
26873   /* If creating a master or main-file journal, this function will open
26874   ** a file-descriptor on the directory too. The first time unixSync()
26875   ** is called the directory file descriptor will be fsync()ed and close()d.
26876   */
26877   int isOpenDirectory = (isCreate && (
26878         eType==SQLITE_OPEN_MASTER_JOURNAL 
26879      || eType==SQLITE_OPEN_MAIN_JOURNAL 
26880      || eType==SQLITE_OPEN_WAL
26881   ));
26882
26883   /* If argument zPath is a NULL pointer, this function is required to open
26884   ** a temporary file. Use this buffer to store the file name in.
26885   */
26886   char zTmpname[MAX_PATHNAME+1];
26887   const char *zName = zPath;
26888
26889   /* Check the following statements are true: 
26890   **
26891   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
26892   **   (b) if CREATE is set, then READWRITE must also be set, and
26893   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
26894   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
26895   */
26896   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
26897   assert(isCreate==0 || isReadWrite);
26898   assert(isExclusive==0 || isCreate);
26899   assert(isDelete==0 || isCreate);
26900
26901   /* The main DB, main journal, WAL file and master journal are never 
26902   ** automatically deleted. Nor are they ever temporary files.  */
26903   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
26904   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
26905   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
26906   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
26907
26908   /* Assert that the upper layer has set one of the "file-type" flags. */
26909   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
26910        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
26911        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
26912        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
26913   );
26914
26915   memset(p, 0, sizeof(unixFile));
26916
26917   if( eType==SQLITE_OPEN_MAIN_DB ){
26918     UnixUnusedFd *pUnused;
26919     pUnused = findReusableFd(zName, flags);
26920     if( pUnused ){
26921       fd = pUnused->fd;
26922     }else{
26923       pUnused = sqlite3_malloc(sizeof(*pUnused));
26924       if( !pUnused ){
26925         return SQLITE_NOMEM;
26926       }
26927     }
26928     p->pUnused = pUnused;
26929   }else if( !zName ){
26930     /* If zName is NULL, the upper layer is requesting a temp file. */
26931     assert(isDelete && !isOpenDirectory);
26932     rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
26933     if( rc!=SQLITE_OK ){
26934       return rc;
26935     }
26936     zName = zTmpname;
26937   }
26938
26939   /* Determine the value of the flags parameter passed to POSIX function
26940   ** open(). These must be calculated even if open() is not called, as
26941   ** they may be stored as part of the file handle and used by the 
26942   ** 'conch file' locking functions later on.  */
26943   if( isReadonly )  openFlags |= O_RDONLY;
26944   if( isReadWrite ) openFlags |= O_RDWR;
26945   if( isCreate )    openFlags |= O_CREAT;
26946   if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
26947   openFlags |= (O_LARGEFILE|O_BINARY);
26948
26949   if( fd<0 ){
26950     mode_t openMode;              /* Permissions to create file with */
26951     rc = findCreateFileMode(zName, flags, &openMode);
26952     if( rc!=SQLITE_OK ){
26953       assert( !p->pUnused );
26954       assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
26955       return rc;
26956     }
26957     fd = open(zName, openFlags, openMode);
26958     OSTRACE(("OPENX   %-3d %s 0%o\n", fd, zName, openFlags));
26959     if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
26960       /* Failed to open the file for read/write access. Try read-only. */
26961       flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
26962       openFlags &= ~(O_RDWR|O_CREAT);
26963       flags |= SQLITE_OPEN_READONLY;
26964       openFlags |= O_RDONLY;
26965       fd = open(zName, openFlags, openMode);
26966     }
26967     if( fd<0 ){
26968       rc = SQLITE_CANTOPEN_BKPT;
26969       goto open_finished;
26970     }
26971   }
26972   assert( fd>=0 );
26973   if( pOutFlags ){
26974     *pOutFlags = flags;
26975   }
26976
26977   if( p->pUnused ){
26978     p->pUnused->fd = fd;
26979     p->pUnused->flags = flags;
26980   }
26981
26982   if( isDelete ){
26983 #if OS_VXWORKS
26984     zPath = zName;
26985 #else
26986     unlink(zName);
26987 #endif
26988   }
26989 #if SQLITE_ENABLE_LOCKING_STYLE
26990   else{
26991     p->openFlags = openFlags;
26992   }
26993 #endif
26994
26995   if( isOpenDirectory ){
26996     rc = openDirectory(zPath, &dirfd);
26997     if( rc!=SQLITE_OK ){
26998       /* It is safe to close fd at this point, because it is guaranteed not
26999       ** to be open on a database file. If it were open on a database file,
27000       ** it would not be safe to close as this would release any locks held
27001       ** on the file by this process.  */
27002       assert( eType!=SQLITE_OPEN_MAIN_DB );
27003       close(fd);             /* silently leak if fail, already in error */
27004       goto open_finished;
27005     }
27006   }
27007
27008 #ifdef FD_CLOEXEC
27009   fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
27010 #endif
27011
27012   noLock = eType!=SQLITE_OPEN_MAIN_DB;
27013
27014   
27015 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
27016   struct statfs fsInfo;
27017   if( fstatfs(fd, &fsInfo) == -1 ){
27018     ((unixFile*)pFile)->lastErrno = errno;
27019     if( dirfd>=0 ) close(dirfd); /* silently leak if fail, in error */
27020     close(fd); /* silently leak if fail, in error */
27021     return SQLITE_IOERR_ACCESS;
27022   }
27023   if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
27024     ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
27025   }
27026 #endif
27027   
27028 #if SQLITE_ENABLE_LOCKING_STYLE
27029 #if SQLITE_PREFER_PROXY_LOCKING
27030   isAutoProxy = 1;
27031 #endif
27032   if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
27033     char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
27034     int useProxy = 0;
27035
27036     /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means 
27037     ** never use proxy, NULL means use proxy for non-local files only.  */
27038     if( envforce!=NULL ){
27039       useProxy = atoi(envforce)>0;
27040     }else{
27041       struct statfs fsInfo;
27042       if( statfs(zPath, &fsInfo) == -1 ){
27043         /* In theory, the close(fd) call is sub-optimal. If the file opened
27044         ** with fd is a database file, and there are other connections open
27045         ** on that file that are currently holding advisory locks on it,
27046         ** then the call to close() will cancel those locks. In practice,
27047         ** we're assuming that statfs() doesn't fail very often. At least
27048         ** not while other file descriptors opened by the same process on
27049         ** the same file are working.  */
27050         p->lastErrno = errno;
27051         if( dirfd>=0 ){
27052           close(dirfd); /* silently leak if fail, in error */
27053         }
27054         close(fd); /* silently leak if fail, in error */
27055         rc = SQLITE_IOERR_ACCESS;
27056         goto open_finished;
27057       }
27058       useProxy = !(fsInfo.f_flags&MNT_LOCAL);
27059     }
27060     if( useProxy ){
27061       rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
27062       if( rc==SQLITE_OK ){
27063         rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
27064         if( rc!=SQLITE_OK ){
27065           /* Use unixClose to clean up the resources added in fillInUnixFile 
27066           ** and clear all the structure's references.  Specifically, 
27067           ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op 
27068           */
27069           unixClose(pFile);
27070           return rc;
27071         }
27072       }
27073       goto open_finished;
27074     }
27075   }
27076 #endif
27077   
27078   rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
27079 open_finished:
27080   if( rc!=SQLITE_OK ){
27081     sqlite3_free(p->pUnused);
27082   }
27083   return rc;
27084 }
27085
27086
27087 /*
27088 ** Delete the file at zPath. If the dirSync argument is true, fsync()
27089 ** the directory after deleting the file.
27090 */
27091 static int unixDelete(
27092   sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
27093   const char *zPath,        /* Name of file to be deleted */
27094   int dirSync               /* If true, fsync() directory after deleting file */
27095 ){
27096   int rc = SQLITE_OK;
27097   UNUSED_PARAMETER(NotUsed);
27098   SimulateIOError(return SQLITE_IOERR_DELETE);
27099   if( unlink(zPath)==(-1) && errno!=ENOENT ){
27100     return SQLITE_IOERR_DELETE;
27101   }
27102 #ifndef SQLITE_DISABLE_DIRSYNC
27103   if( dirSync ){
27104     int fd;
27105     rc = openDirectory(zPath, &fd);
27106     if( rc==SQLITE_OK ){
27107 #if OS_VXWORKS
27108       if( fsync(fd)==-1 )
27109 #else
27110       if( fsync(fd) )
27111 #endif
27112       {
27113         rc = SQLITE_IOERR_DIR_FSYNC;
27114       }
27115       if( close(fd)&&!rc ){
27116         rc = SQLITE_IOERR_DIR_CLOSE;
27117       }
27118     }
27119   }
27120 #endif
27121   return rc;
27122 }
27123
27124 /*
27125 ** Test the existance of or access permissions of file zPath. The
27126 ** test performed depends on the value of flags:
27127 **
27128 **     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
27129 **     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
27130 **     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
27131 **
27132 ** Otherwise return 0.
27133 */
27134 static int unixAccess(
27135   sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
27136   const char *zPath,      /* Path of the file to examine */
27137   int flags,              /* What do we want to learn about the zPath file? */
27138   int *pResOut            /* Write result boolean here */
27139 ){
27140   int amode = 0;
27141   UNUSED_PARAMETER(NotUsed);
27142   SimulateIOError( return SQLITE_IOERR_ACCESS; );
27143   switch( flags ){
27144     case SQLITE_ACCESS_EXISTS:
27145       amode = F_OK;
27146       break;
27147     case SQLITE_ACCESS_READWRITE:
27148       amode = W_OK|R_OK;
27149       break;
27150     case SQLITE_ACCESS_READ:
27151       amode = R_OK;
27152       break;
27153
27154     default:
27155       assert(!"Invalid flags argument");
27156   }
27157   *pResOut = (access(zPath, amode)==0);
27158   if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
27159     struct stat buf;
27160     if( 0==stat(zPath, &buf) && buf.st_size==0 ){
27161       *pResOut = 0;
27162     }
27163   }
27164   return SQLITE_OK;
27165 }
27166
27167
27168 /*
27169 ** Turn a relative pathname into a full pathname. The relative path
27170 ** is stored as a nul-terminated string in the buffer pointed to by
27171 ** zPath. 
27172 **
27173 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes 
27174 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
27175 ** this buffer before returning.
27176 */
27177 static int unixFullPathname(
27178   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
27179   const char *zPath,            /* Possibly relative input path */
27180   int nOut,                     /* Size of output buffer in bytes */
27181   char *zOut                    /* Output buffer */
27182 ){
27183
27184   /* It's odd to simulate an io-error here, but really this is just
27185   ** using the io-error infrastructure to test that SQLite handles this
27186   ** function failing. This function could fail if, for example, the
27187   ** current working directory has been unlinked.
27188   */
27189   SimulateIOError( return SQLITE_ERROR );
27190
27191   assert( pVfs->mxPathname==MAX_PATHNAME );
27192   UNUSED_PARAMETER(pVfs);
27193
27194   zOut[nOut-1] = '\0';
27195   if( zPath[0]=='/' ){
27196     sqlite3_snprintf(nOut, zOut, "%s", zPath);
27197   }else{
27198     int nCwd;
27199     if( getcwd(zOut, nOut-1)==0 ){
27200       return SQLITE_CANTOPEN_BKPT;
27201     }
27202     nCwd = (int)strlen(zOut);
27203     sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
27204   }
27205   return SQLITE_OK;
27206 }
27207
27208
27209 #ifndef SQLITE_OMIT_LOAD_EXTENSION
27210 /*
27211 ** Interfaces for opening a shared library, finding entry points
27212 ** within the shared library, and closing the shared library.
27213 */
27214 #include <dlfcn.h>
27215 static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
27216   UNUSED_PARAMETER(NotUsed);
27217   return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
27218 }
27219
27220 /*
27221 ** SQLite calls this function immediately after a call to unixDlSym() or
27222 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
27223 ** message is available, it is written to zBufOut. If no error message
27224 ** is available, zBufOut is left unmodified and SQLite uses a default
27225 ** error message.
27226 */
27227 static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
27228   char *zErr;
27229   UNUSED_PARAMETER(NotUsed);
27230   unixEnterMutex();
27231   zErr = dlerror();
27232   if( zErr ){
27233     sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
27234   }
27235   unixLeaveMutex();
27236 }
27237 static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
27238   /* 
27239   ** GCC with -pedantic-errors says that C90 does not allow a void* to be
27240   ** cast into a pointer to a function.  And yet the library dlsym() routine
27241   ** returns a void* which is really a pointer to a function.  So how do we
27242   ** use dlsym() with -pedantic-errors?
27243   **
27244   ** Variable x below is defined to be a pointer to a function taking
27245   ** parameters void* and const char* and returning a pointer to a function.
27246   ** We initialize x by assigning it a pointer to the dlsym() function.
27247   ** (That assignment requires a cast.)  Then we call the function that
27248   ** x points to.  
27249   **
27250   ** This work-around is unlikely to work correctly on any system where
27251   ** you really cannot cast a function pointer into void*.  But then, on the
27252   ** other hand, dlsym() will not work on such a system either, so we have
27253   ** not really lost anything.
27254   */
27255   void (*(*x)(void*,const char*))(void);
27256   UNUSED_PARAMETER(NotUsed);
27257   x = (void(*(*)(void*,const char*))(void))dlsym;
27258   return (*x)(p, zSym);
27259 }
27260 static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
27261   UNUSED_PARAMETER(NotUsed);
27262   dlclose(pHandle);
27263 }
27264 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
27265   #define unixDlOpen  0
27266   #define unixDlError 0
27267   #define unixDlSym   0
27268   #define unixDlClose 0
27269 #endif
27270
27271 /*
27272 ** Write nBuf bytes of random data to the supplied buffer zBuf.
27273 */
27274 static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
27275   UNUSED_PARAMETER(NotUsed);
27276   assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
27277
27278   /* We have to initialize zBuf to prevent valgrind from reporting
27279   ** errors.  The reports issued by valgrind are incorrect - we would
27280   ** prefer that the randomness be increased by making use of the
27281   ** uninitialized space in zBuf - but valgrind errors tend to worry
27282   ** some users.  Rather than argue, it seems easier just to initialize
27283   ** the whole array and silence valgrind, even if that means less randomness
27284   ** in the random seed.
27285   **
27286   ** When testing, initializing zBuf[] to zero is all we do.  That means
27287   ** that we always use the same random number sequence.  This makes the
27288   ** tests repeatable.
27289   */
27290   memset(zBuf, 0, nBuf);
27291 #if !defined(SQLITE_TEST)
27292   {
27293     int pid, fd;
27294     fd = open("/dev/urandom", O_RDONLY);
27295     if( fd<0 ){
27296       time_t t;
27297       time(&t);
27298       memcpy(zBuf, &t, sizeof(t));
27299       pid = getpid();
27300       memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
27301       assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
27302       nBuf = sizeof(t) + sizeof(pid);
27303     }else{
27304       nBuf = read(fd, zBuf, nBuf);
27305       close(fd);
27306     }
27307   }
27308 #endif
27309   return nBuf;
27310 }
27311
27312
27313 /*
27314 ** Sleep for a little while.  Return the amount of time slept.
27315 ** The argument is the number of microseconds we want to sleep.
27316 ** The return value is the number of microseconds of sleep actually
27317 ** requested from the underlying operating system, a number which
27318 ** might be greater than or equal to the argument, but not less
27319 ** than the argument.
27320 */
27321 static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
27322 #if OS_VXWORKS
27323   struct timespec sp;
27324
27325   sp.tv_sec = microseconds / 1000000;
27326   sp.tv_nsec = (microseconds % 1000000) * 1000;
27327   nanosleep(&sp, NULL);
27328   UNUSED_PARAMETER(NotUsed);
27329   return microseconds;
27330 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
27331   usleep(microseconds);
27332   UNUSED_PARAMETER(NotUsed);
27333   return microseconds;
27334 #else
27335   int seconds = (microseconds+999999)/1000000;
27336   sleep(seconds);
27337   UNUSED_PARAMETER(NotUsed);
27338   return seconds*1000000;
27339 #endif
27340 }
27341
27342 /*
27343 ** The following variable, if set to a non-zero value, is interpreted as
27344 ** the number of seconds since 1970 and is used to set the result of
27345 ** sqlite3OsCurrentTime() during testing.
27346 */
27347 #ifdef SQLITE_TEST
27348 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
27349 #endif
27350
27351 /*
27352 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
27353 ** the current time and date as a Julian Day number times 86_400_000.  In
27354 ** other words, write into *piNow the number of milliseconds since the Julian
27355 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
27356 ** proleptic Gregorian calendar.
27357 **
27358 ** On success, return 0.  Return 1 if the time and date cannot be found.
27359 */
27360 static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
27361   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
27362 #if defined(NO_GETTOD)
27363   time_t t;
27364   time(&t);
27365   *piNow = ((sqlite3_int64)i)*1000 + unixEpoch;
27366 #elif OS_VXWORKS
27367   struct timespec sNow;
27368   clock_gettime(CLOCK_REALTIME, &sNow);
27369   *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
27370 #else
27371   struct timeval sNow;
27372   gettimeofday(&sNow, 0);
27373   *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
27374 #endif
27375
27376 #ifdef SQLITE_TEST
27377   if( sqlite3_current_time ){
27378     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
27379   }
27380 #endif
27381   UNUSED_PARAMETER(NotUsed);
27382   return 0;
27383 }
27384
27385 /*
27386 ** Find the current time (in Universal Coordinated Time).  Write the
27387 ** current time and date as a Julian Day number into *prNow and
27388 ** return 0.  Return 1 if the time and date cannot be found.
27389 */
27390 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
27391   sqlite3_int64 i;
27392   UNUSED_PARAMETER(NotUsed);
27393   unixCurrentTimeInt64(0, &i);
27394   *prNow = i/86400000.0;
27395   return 0;
27396 }
27397
27398 /*
27399 ** We added the xGetLastError() method with the intention of providing
27400 ** better low-level error messages when operating-system problems come up
27401 ** during SQLite operation.  But so far, none of that has been implemented
27402 ** in the core.  So this routine is never called.  For now, it is merely
27403 ** a place-holder.
27404 */
27405 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
27406   UNUSED_PARAMETER(NotUsed);
27407   UNUSED_PARAMETER(NotUsed2);
27408   UNUSED_PARAMETER(NotUsed3);
27409   return 0;
27410 }
27411
27412
27413 /*
27414 ************************ End of sqlite3_vfs methods ***************************
27415 ******************************************************************************/
27416
27417 /******************************************************************************
27418 ************************** Begin Proxy Locking ********************************
27419 **
27420 ** Proxy locking is a "uber-locking-method" in this sense:  It uses the
27421 ** other locking methods on secondary lock files.  Proxy locking is a
27422 ** meta-layer over top of the primitive locking implemented above.  For
27423 ** this reason, the division that implements of proxy locking is deferred
27424 ** until late in the file (here) after all of the other I/O methods have
27425 ** been defined - so that the primitive locking methods are available
27426 ** as services to help with the implementation of proxy locking.
27427 **
27428 ****
27429 **
27430 ** The default locking schemes in SQLite use byte-range locks on the
27431 ** database file to coordinate safe, concurrent access by multiple readers
27432 ** and writers [http://sqlite.org/lockingv3.html].  The five file locking
27433 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
27434 ** as POSIX read & write locks over fixed set of locations (via fsctl),
27435 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
27436 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
27437 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
27438 ** address in the shared range is taken for a SHARED lock, the entire
27439 ** shared range is taken for an EXCLUSIVE lock):
27440 **
27441 **      PENDING_BYTE        0x40000000                  
27442 **      RESERVED_BYTE       0x40000001
27443 **      SHARED_RANGE        0x40000002 -> 0x40000200
27444 **
27445 ** This works well on the local file system, but shows a nearly 100x
27446 ** slowdown in read performance on AFP because the AFP client disables
27447 ** the read cache when byte-range locks are present.  Enabling the read
27448 ** cache exposes a cache coherency problem that is present on all OS X
27449 ** supported network file systems.  NFS and AFP both observe the
27450 ** close-to-open semantics for ensuring cache coherency
27451 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
27452 ** address the requirements for concurrent database access by multiple
27453 ** readers and writers
27454 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
27455 **
27456 ** To address the performance and cache coherency issues, proxy file locking
27457 ** changes the way database access is controlled by limiting access to a
27458 ** single host at a time and moving file locks off of the database file
27459 ** and onto a proxy file on the local file system.  
27460 **
27461 **
27462 ** Using proxy locks
27463 ** -----------------
27464 **
27465 ** C APIs
27466 **
27467 **  sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
27468 **                       <proxy_path> | ":auto:");
27469 **  sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
27470 **
27471 **
27472 ** SQL pragmas
27473 **
27474 **  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
27475 **  PRAGMA [database.]lock_proxy_file
27476 **
27477 ** Specifying ":auto:" means that if there is a conch file with a matching
27478 ** host ID in it, the proxy path in the conch file will be used, otherwise
27479 ** a proxy path based on the user's temp dir
27480 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
27481 ** actual proxy file name is generated from the name and path of the
27482 ** database file.  For example:
27483 **
27484 **       For database path "/Users/me/foo.db" 
27485 **       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
27486 **
27487 ** Once a lock proxy is configured for a database connection, it can not
27488 ** be removed, however it may be switched to a different proxy path via
27489 ** the above APIs (assuming the conch file is not being held by another
27490 ** connection or process). 
27491 **
27492 **
27493 ** How proxy locking works
27494 ** -----------------------
27495 **
27496 ** Proxy file locking relies primarily on two new supporting files: 
27497 **
27498 **   *  conch file to limit access to the database file to a single host
27499 **      at a time
27500 **
27501 **   *  proxy file to act as a proxy for the advisory locks normally
27502 **      taken on the database
27503 **
27504 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
27505 ** by taking an sqlite-style shared lock on the conch file, reading the
27506 ** contents and comparing the host's unique host ID (see below) and lock
27507 ** proxy path against the values stored in the conch.  The conch file is
27508 ** stored in the same directory as the database file and the file name
27509 ** is patterned after the database file name as ".<databasename>-conch".
27510 ** If the conch file does not exist, or it's contents do not match the
27511 ** host ID and/or proxy path, then the lock is escalated to an exclusive
27512 ** lock and the conch file contents is updated with the host ID and proxy
27513 ** path and the lock is downgraded to a shared lock again.  If the conch
27514 ** is held by another process (with a shared lock), the exclusive lock
27515 ** will fail and SQLITE_BUSY is returned.
27516 **
27517 ** The proxy file - a single-byte file used for all advisory file locks
27518 ** normally taken on the database file.   This allows for safe sharing
27519 ** of the database file for multiple readers and writers on the same
27520 ** host (the conch ensures that they all use the same local lock file).
27521 **
27522 ** Requesting the lock proxy does not immediately take the conch, it is
27523 ** only taken when the first request to lock database file is made.  
27524 ** This matches the semantics of the traditional locking behavior, where
27525 ** opening a connection to a database file does not take a lock on it.
27526 ** The shared lock and an open file descriptor are maintained until 
27527 ** the connection to the database is closed. 
27528 **
27529 ** The proxy file and the lock file are never deleted so they only need
27530 ** to be created the first time they are used.
27531 **
27532 ** Configuration options
27533 ** ---------------------
27534 **
27535 **  SQLITE_PREFER_PROXY_LOCKING
27536 **
27537 **       Database files accessed on non-local file systems are
27538 **       automatically configured for proxy locking, lock files are
27539 **       named automatically using the same logic as
27540 **       PRAGMA lock_proxy_file=":auto:"
27541 **    
27542 **  SQLITE_PROXY_DEBUG
27543 **
27544 **       Enables the logging of error messages during host id file
27545 **       retrieval and creation
27546 **
27547 **  LOCKPROXYDIR
27548 **
27549 **       Overrides the default directory used for lock proxy files that
27550 **       are named automatically via the ":auto:" setting
27551 **
27552 **  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
27553 **
27554 **       Permissions to use when creating a directory for storing the
27555 **       lock proxy files, only used when LOCKPROXYDIR is not set.
27556 **    
27557 **    
27558 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
27559 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
27560 ** force proxy locking to be used for every database file opened, and 0
27561 ** will force automatic proxy locking to be disabled for all database
27562 ** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
27563 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
27564 */
27565
27566 /*
27567 ** Proxy locking is only available on MacOSX 
27568 */
27569 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27570
27571 /*
27572 ** The proxyLockingContext has the path and file structures for the remote 
27573 ** and local proxy files in it
27574 */
27575 typedef struct proxyLockingContext proxyLockingContext;
27576 struct proxyLockingContext {
27577   unixFile *conchFile;         /* Open conch file */
27578   char *conchFilePath;         /* Name of the conch file */
27579   unixFile *lockProxy;         /* Open proxy lock file */
27580   char *lockProxyPath;         /* Name of the proxy lock file */
27581   char *dbPath;                /* Name of the open file */
27582   int conchHeld;               /* 1 if the conch is held, -1 if lockless */
27583   void *oldLockingContext;     /* Original lockingcontext to restore on close */
27584   sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
27585 };
27586
27587 /* 
27588 ** The proxy lock file path for the database at dbPath is written into lPath, 
27589 ** which must point to valid, writable memory large enough for a maxLen length
27590 ** file path. 
27591 */
27592 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
27593   int len;
27594   int dbLen;
27595   int i;
27596
27597 #ifdef LOCKPROXYDIR
27598   len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
27599 #else
27600 # ifdef _CS_DARWIN_USER_TEMP_DIR
27601   {
27602     if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
27603       OSTRACE(("GETLOCKPATH  failed %s errno=%d pid=%d\n",
27604                lPath, errno, getpid()));
27605       return SQLITE_IOERR_LOCK;
27606     }
27607     len = strlcat(lPath, "sqliteplocks", maxLen);    
27608   }
27609 # else
27610   len = strlcpy(lPath, "/tmp/", maxLen);
27611 # endif
27612 #endif
27613
27614   if( lPath[len-1]!='/' ){
27615     len = strlcat(lPath, "/", maxLen);
27616   }
27617   
27618   /* transform the db path to a unique cache name */
27619   dbLen = (int)strlen(dbPath);
27620   for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
27621     char c = dbPath[i];
27622     lPath[i+len] = (c=='/')?'_':c;
27623   }
27624   lPath[i+len]='\0';
27625   strlcat(lPath, ":auto:", maxLen);
27626   OSTRACE(("GETLOCKPATH  proxy lock path=%s pid=%d\n", lPath, getpid()));
27627   return SQLITE_OK;
27628 }
27629
27630 /* 
27631  ** Creates the lock file and any missing directories in lockPath
27632  */
27633 static int proxyCreateLockPath(const char *lockPath){
27634   int i, len;
27635   char buf[MAXPATHLEN];
27636   int start = 0;
27637   
27638   assert(lockPath!=NULL);
27639   /* try to create all the intermediate directories */
27640   len = (int)strlen(lockPath);
27641   buf[0] = lockPath[0];
27642   for( i=1; i<len; i++ ){
27643     if( lockPath[i] == '/' && (i - start > 0) ){
27644       /* only mkdir if leaf dir != "." or "/" or ".." */
27645       if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/') 
27646          || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
27647         buf[i]='\0';
27648         if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
27649           int err=errno;
27650           if( err!=EEXIST ) {
27651             OSTRACE(("CREATELOCKPATH  FAILED creating %s, "
27652                      "'%s' proxy lock path=%s pid=%d\n",
27653                      buf, strerror(err), lockPath, getpid()));
27654             return err;
27655           }
27656         }
27657       }
27658       start=i+1;
27659     }
27660     buf[i] = lockPath[i];
27661   }
27662   OSTRACE(("CREATELOCKPATH  proxy lock path=%s pid=%d\n", lockPath, getpid()));
27663   return 0;
27664 }
27665
27666 /*
27667 ** Create a new VFS file descriptor (stored in memory obtained from
27668 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
27669 **
27670 ** The caller is responsible not only for closing the file descriptor
27671 ** but also for freeing the memory associated with the file descriptor.
27672 */
27673 static int proxyCreateUnixFile(
27674     const char *path,        /* path for the new unixFile */
27675     unixFile **ppFile,       /* unixFile created and returned by ref */
27676     int islockfile           /* if non zero missing dirs will be created */
27677 ) {
27678   int fd = -1;
27679   int dirfd = -1;
27680   unixFile *pNew;
27681   int rc = SQLITE_OK;
27682   int openFlags = O_RDWR | O_CREAT;
27683   sqlite3_vfs dummyVfs;
27684   int terrno = 0;
27685   UnixUnusedFd *pUnused = NULL;
27686
27687   /* 1. first try to open/create the file
27688   ** 2. if that fails, and this is a lock file (not-conch), try creating
27689   ** the parent directories and then try again.
27690   ** 3. if that fails, try to open the file read-only
27691   ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
27692   */
27693   pUnused = findReusableFd(path, openFlags);
27694   if( pUnused ){
27695     fd = pUnused->fd;
27696   }else{
27697     pUnused = sqlite3_malloc(sizeof(*pUnused));
27698     if( !pUnused ){
27699       return SQLITE_NOMEM;
27700     }
27701   }
27702   if( fd<0 ){
27703     fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
27704     terrno = errno;
27705     if( fd<0 && errno==ENOENT && islockfile ){
27706       if( proxyCreateLockPath(path) == SQLITE_OK ){
27707         fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
27708       }
27709     }
27710   }
27711   if( fd<0 ){
27712     openFlags = O_RDONLY;
27713     fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
27714     terrno = errno;
27715   }
27716   if( fd<0 ){
27717     if( islockfile ){
27718       return SQLITE_BUSY;
27719     }
27720     switch (terrno) {
27721       case EACCES:
27722         return SQLITE_PERM;
27723       case EIO: 
27724         return SQLITE_IOERR_LOCK; /* even though it is the conch */
27725       default:
27726         return SQLITE_CANTOPEN_BKPT;
27727     }
27728   }
27729   
27730   pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
27731   if( pNew==NULL ){
27732     rc = SQLITE_NOMEM;
27733     goto end_create_proxy;
27734   }
27735   memset(pNew, 0, sizeof(unixFile));
27736   pNew->openFlags = openFlags;
27737   dummyVfs.pAppData = (void*)&autolockIoFinder;
27738   pUnused->fd = fd;
27739   pUnused->flags = openFlags;
27740   pNew->pUnused = pUnused;
27741   
27742   rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0);
27743   if( rc==SQLITE_OK ){
27744     *ppFile = pNew;
27745     return SQLITE_OK;
27746   }
27747 end_create_proxy:    
27748   close(fd); /* silently leak fd if error, we're already in error */
27749   sqlite3_free(pNew);
27750   sqlite3_free(pUnused);
27751   return rc;
27752 }
27753
27754 #ifdef SQLITE_TEST
27755 /* simulate multiple hosts by creating unique hostid file paths */
27756 SQLITE_API int sqlite3_hostid_num = 0;
27757 #endif
27758
27759 #define PROXY_HOSTIDLEN    16  /* conch file host id length */
27760
27761 /* Not always defined in the headers as it ought to be */
27762 extern int gethostuuid(uuid_t id, const struct timespec *wait);
27763
27764 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN 
27765 ** bytes of writable memory.
27766 */
27767 static int proxyGetHostID(unsigned char *pHostID, int *pError){
27768   struct timespec timeout = {1, 0}; /* 1 sec timeout */
27769   
27770   assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
27771   memset(pHostID, 0, PROXY_HOSTIDLEN);
27772   if( gethostuuid(pHostID, &timeout) ){
27773     int err = errno;
27774     if( pError ){
27775       *pError = err;
27776     }
27777     return SQLITE_IOERR;
27778   }
27779 #ifdef SQLITE_TEST
27780   /* simulate multiple hosts by creating unique hostid file paths */
27781   if( sqlite3_hostid_num != 0){
27782     pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
27783   }
27784 #endif
27785   
27786   return SQLITE_OK;
27787 }
27788
27789 /* The conch file contains the header, host id and lock file path
27790  */
27791 #define PROXY_CONCHVERSION 2   /* 1-byte header, 16-byte host id, path */
27792 #define PROXY_HEADERLEN    1   /* conch file header length */
27793 #define PROXY_PATHINDEX    (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
27794 #define PROXY_MAXCONCHLEN  (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
27795
27796 /* 
27797 ** Takes an open conch file, copies the contents to a new path and then moves 
27798 ** it back.  The newly created file's file descriptor is assigned to the
27799 ** conch file structure and finally the original conch file descriptor is 
27800 ** closed.  Returns zero if successful.
27801 */
27802 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
27803   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
27804   unixFile *conchFile = pCtx->conchFile;
27805   char tPath[MAXPATHLEN];
27806   char buf[PROXY_MAXCONCHLEN];
27807   char *cPath = pCtx->conchFilePath;
27808   size_t readLen = 0;
27809   size_t pathLen = 0;
27810   char errmsg[64] = "";
27811   int fd = -1;
27812   int rc = -1;
27813   UNUSED_PARAMETER(myHostID);
27814
27815   /* create a new path by replace the trailing '-conch' with '-break' */
27816   pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
27817   if( pathLen>MAXPATHLEN || pathLen<6 || 
27818      (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
27819     sprintf(errmsg, "path error (len %d)", (int)pathLen);
27820     goto end_breaklock;
27821   }
27822   /* read the conch content */
27823   readLen = pread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
27824   if( readLen<PROXY_PATHINDEX ){
27825     sprintf(errmsg, "read error (len %d)", (int)readLen);
27826     goto end_breaklock;
27827   }
27828   /* write it out to the temporary break file */
27829   fd = open(tPath, (O_RDWR|O_CREAT|O_EXCL), SQLITE_DEFAULT_FILE_PERMISSIONS);
27830   if( fd<0 ){
27831     sprintf(errmsg, "create failed (%d)", errno);
27832     goto end_breaklock;
27833   }
27834   if( pwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
27835     sprintf(errmsg, "write failed (%d)", errno);
27836     goto end_breaklock;
27837   }
27838   if( rename(tPath, cPath) ){
27839     sprintf(errmsg, "rename failed (%d)", errno);
27840     goto end_breaklock;
27841   }
27842   rc = 0;
27843   fprintf(stderr, "broke stale lock on %s\n", cPath);
27844   close(conchFile->h);
27845   conchFile->h = fd;
27846   conchFile->openFlags = O_RDWR | O_CREAT;
27847
27848 end_breaklock:
27849   if( rc ){
27850     if( fd>=0 ){
27851       unlink(tPath);
27852       close(fd);
27853     }
27854     fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
27855   }
27856   return rc;
27857 }
27858
27859 /* Take the requested lock on the conch file and break a stale lock if the 
27860 ** host id matches.
27861 */
27862 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
27863   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
27864   unixFile *conchFile = pCtx->conchFile;
27865   int rc = SQLITE_OK;
27866   int nTries = 0;
27867   struct timespec conchModTime;
27868   
27869   do {
27870     rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
27871     nTries ++;
27872     if( rc==SQLITE_BUSY ){
27873       /* If the lock failed (busy):
27874        * 1st try: get the mod time of the conch, wait 0.5s and try again. 
27875        * 2nd try: fail if the mod time changed or host id is different, wait 
27876        *           10 sec and try again
27877        * 3rd try: break the lock unless the mod time has changed.
27878        */
27879       struct stat buf;
27880       if( fstat(conchFile->h, &buf) ){
27881         pFile->lastErrno = errno;
27882         return SQLITE_IOERR_LOCK;
27883       }
27884       
27885       if( nTries==1 ){
27886         conchModTime = buf.st_mtimespec;
27887         usleep(500000); /* wait 0.5 sec and try the lock again*/
27888         continue;  
27889       }
27890
27891       assert( nTries>1 );
27892       if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec || 
27893          conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
27894         return SQLITE_BUSY;
27895       }
27896       
27897       if( nTries==2 ){  
27898         char tBuf[PROXY_MAXCONCHLEN];
27899         int len = pread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
27900         if( len<0 ){
27901           pFile->lastErrno = errno;
27902           return SQLITE_IOERR_LOCK;
27903         }
27904         if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
27905           /* don't break the lock if the host id doesn't match */
27906           if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
27907             return SQLITE_BUSY;
27908           }
27909         }else{
27910           /* don't break the lock on short read or a version mismatch */
27911           return SQLITE_BUSY;
27912         }
27913         usleep(10000000); /* wait 10 sec and try the lock again */
27914         continue; 
27915       }
27916       
27917       assert( nTries==3 );
27918       if( 0==proxyBreakConchLock(pFile, myHostID) ){
27919         rc = SQLITE_OK;
27920         if( lockType==EXCLUSIVE_LOCK ){
27921           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);          
27922         }
27923         if( !rc ){
27924           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
27925         }
27926       }
27927     }
27928   } while( rc==SQLITE_BUSY && nTries<3 );
27929   
27930   return rc;
27931 }
27932
27933 /* Takes the conch by taking a shared lock and read the contents conch, if 
27934 ** lockPath is non-NULL, the host ID and lock file path must match.  A NULL 
27935 ** lockPath means that the lockPath in the conch file will be used if the 
27936 ** host IDs match, or a new lock path will be generated automatically 
27937 ** and written to the conch file.
27938 */
27939 static int proxyTakeConch(unixFile *pFile){
27940   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
27941   
27942   if( pCtx->conchHeld!=0 ){
27943     return SQLITE_OK;
27944   }else{
27945     unixFile *conchFile = pCtx->conchFile;
27946     uuid_t myHostID;
27947     int pError = 0;
27948     char readBuf[PROXY_MAXCONCHLEN];
27949     char lockPath[MAXPATHLEN];
27950     char *tempLockPath = NULL;
27951     int rc = SQLITE_OK;
27952     int createConch = 0;
27953     int hostIdMatch = 0;
27954     int readLen = 0;
27955     int tryOldLockPath = 0;
27956     int forceNewLockPath = 0;
27957     
27958     OSTRACE(("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
27959              (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
27960
27961     rc = proxyGetHostID(myHostID, &pError);
27962     if( (rc&0xff)==SQLITE_IOERR ){
27963       pFile->lastErrno = pError;
27964       goto end_takeconch;
27965     }
27966     rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
27967     if( rc!=SQLITE_OK ){
27968       goto end_takeconch;
27969     }
27970     /* read the existing conch file */
27971     readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
27972     if( readLen<0 ){
27973       /* I/O error: lastErrno set by seekAndRead */
27974       pFile->lastErrno = conchFile->lastErrno;
27975       rc = SQLITE_IOERR_READ;
27976       goto end_takeconch;
27977     }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) || 
27978              readBuf[0]!=(char)PROXY_CONCHVERSION ){
27979       /* a short read or version format mismatch means we need to create a new 
27980       ** conch file. 
27981       */
27982       createConch = 1;
27983     }
27984     /* if the host id matches and the lock path already exists in the conch
27985     ** we'll try to use the path there, if we can't open that path, we'll 
27986     ** retry with a new auto-generated path 
27987     */
27988     do { /* in case we need to try again for an :auto: named lock file */
27989
27990       if( !createConch && !forceNewLockPath ){
27991         hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID, 
27992                                   PROXY_HOSTIDLEN);
27993         /* if the conch has data compare the contents */
27994         if( !pCtx->lockProxyPath ){
27995           /* for auto-named local lock file, just check the host ID and we'll
27996            ** use the local lock file path that's already in there
27997            */
27998           if( hostIdMatch ){
27999             size_t pathLen = (readLen - PROXY_PATHINDEX);
28000             
28001             if( pathLen>=MAXPATHLEN ){
28002               pathLen=MAXPATHLEN-1;
28003             }
28004             memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
28005             lockPath[pathLen] = 0;
28006             tempLockPath = lockPath;
28007             tryOldLockPath = 1;
28008             /* create a copy of the lock path if the conch is taken */
28009             goto end_takeconch;
28010           }
28011         }else if( hostIdMatch
28012                && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
28013                            readLen-PROXY_PATHINDEX)
28014         ){
28015           /* conch host and lock path match */
28016           goto end_takeconch; 
28017         }
28018       }
28019       
28020       /* if the conch isn't writable and doesn't match, we can't take it */
28021       if( (conchFile->openFlags&O_RDWR) == 0 ){
28022         rc = SQLITE_BUSY;
28023         goto end_takeconch;
28024       }
28025       
28026       /* either the conch didn't match or we need to create a new one */
28027       if( !pCtx->lockProxyPath ){
28028         proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
28029         tempLockPath = lockPath;
28030         /* create a copy of the lock path _only_ if the conch is taken */
28031       }
28032       
28033       /* update conch with host and path (this will fail if other process
28034       ** has a shared lock already), if the host id matches, use the big
28035       ** stick.
28036       */
28037       futimes(conchFile->h, NULL);
28038       if( hostIdMatch && !createConch ){
28039         if( conchFile->pInode && conchFile->pInode->nShared>1 ){
28040           /* We are trying for an exclusive lock but another thread in this
28041            ** same process is still holding a shared lock. */
28042           rc = SQLITE_BUSY;
28043         } else {          
28044           rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
28045         }
28046       }else{
28047         rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
28048       }
28049       if( rc==SQLITE_OK ){
28050         char writeBuffer[PROXY_MAXCONCHLEN];
28051         int writeSize = 0;
28052         
28053         writeBuffer[0] = (char)PROXY_CONCHVERSION;
28054         memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
28055         if( pCtx->lockProxyPath!=NULL ){
28056           strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
28057         }else{
28058           strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
28059         }
28060         writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
28061         ftruncate(conchFile->h, writeSize);
28062         rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
28063         fsync(conchFile->h);
28064         /* If we created a new conch file (not just updated the contents of a 
28065          ** valid conch file), try to match the permissions of the database 
28066          */
28067         if( rc==SQLITE_OK && createConch ){
28068           struct stat buf;
28069           int err = fstat(pFile->h, &buf);
28070           if( err==0 ){
28071             mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
28072                                         S_IROTH|S_IWOTH);
28073             /* try to match the database file R/W permissions, ignore failure */
28074 #ifndef SQLITE_PROXY_DEBUG
28075             fchmod(conchFile->h, cmode);
28076 #else
28077             if( fchmod(conchFile->h, cmode)!=0 ){
28078               int code = errno;
28079               fprintf(stderr, "fchmod %o FAILED with %d %s\n",
28080                       cmode, code, strerror(code));
28081             } else {
28082               fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
28083             }
28084           }else{
28085             int code = errno;
28086             fprintf(stderr, "STAT FAILED[%d] with %d %s\n", 
28087                     err, code, strerror(code));
28088 #endif
28089           }
28090         }
28091       }
28092       conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
28093       
28094     end_takeconch:
28095       OSTRACE(("TRANSPROXY: CLOSE  %d\n", pFile->h));
28096       if( rc==SQLITE_OK && pFile->openFlags ){
28097         if( pFile->h>=0 ){
28098 #ifdef STRICT_CLOSE_ERROR
28099           if( close(pFile->h) ){
28100             pFile->lastErrno = errno;
28101             return SQLITE_IOERR_CLOSE;
28102           }
28103 #else
28104           close(pFile->h); /* silently leak fd if fail */
28105 #endif
28106         }
28107         pFile->h = -1;
28108         int fd = open(pCtx->dbPath, pFile->openFlags,
28109                       SQLITE_DEFAULT_FILE_PERMISSIONS);
28110         OSTRACE(("TRANSPROXY: OPEN  %d\n", fd));
28111         if( fd>=0 ){
28112           pFile->h = fd;
28113         }else{
28114           rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
28115            during locking */
28116         }
28117       }
28118       if( rc==SQLITE_OK && !pCtx->lockProxy ){
28119         char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
28120         rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
28121         if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
28122           /* we couldn't create the proxy lock file with the old lock file path
28123            ** so try again via auto-naming 
28124            */
28125           forceNewLockPath = 1;
28126           tryOldLockPath = 0;
28127           continue; /* go back to the do {} while start point, try again */
28128         }
28129       }
28130       if( rc==SQLITE_OK ){
28131         /* Need to make a copy of path if we extracted the value
28132          ** from the conch file or the path was allocated on the stack
28133          */
28134         if( tempLockPath ){
28135           pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
28136           if( !pCtx->lockProxyPath ){
28137             rc = SQLITE_NOMEM;
28138           }
28139         }
28140       }
28141       if( rc==SQLITE_OK ){
28142         pCtx->conchHeld = 1;
28143         
28144         if( pCtx->lockProxy->pMethod == &afpIoMethods ){
28145           afpLockingContext *afpCtx;
28146           afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
28147           afpCtx->dbPath = pCtx->lockProxyPath;
28148         }
28149       } else {
28150         conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
28151       }
28152       OSTRACE(("TAKECONCH  %d %s\n", conchFile->h,
28153                rc==SQLITE_OK?"ok":"failed"));
28154       return rc;
28155     } while (1); /* in case we need to retry the :auto: lock file - 
28156                  ** we should never get here except via the 'continue' call. */
28157   }
28158 }
28159
28160 /*
28161 ** If pFile holds a lock on a conch file, then release that lock.
28162 */
28163 static int proxyReleaseConch(unixFile *pFile){
28164   int rc = SQLITE_OK;         /* Subroutine return code */
28165   proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
28166   unixFile *conchFile;        /* Name of the conch file */
28167
28168   pCtx = (proxyLockingContext *)pFile->lockingContext;
28169   conchFile = pCtx->conchFile;
28170   OSTRACE(("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
28171            (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), 
28172            getpid()));
28173   if( pCtx->conchHeld>0 ){
28174     rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
28175   }
28176   pCtx->conchHeld = 0;
28177   OSTRACE(("RELEASECONCH  %d %s\n", conchFile->h,
28178            (rc==SQLITE_OK ? "ok" : "failed")));
28179   return rc;
28180 }
28181
28182 /*
28183 ** Given the name of a database file, compute the name of its conch file.
28184 ** Store the conch filename in memory obtained from sqlite3_malloc().
28185 ** Make *pConchPath point to the new name.  Return SQLITE_OK on success
28186 ** or SQLITE_NOMEM if unable to obtain memory.
28187 **
28188 ** The caller is responsible for ensuring that the allocated memory
28189 ** space is eventually freed.
28190 **
28191 ** *pConchPath is set to NULL if a memory allocation error occurs.
28192 */
28193 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
28194   int i;                        /* Loop counter */
28195   int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
28196   char *conchPath;              /* buffer in which to construct conch name */
28197
28198   /* Allocate space for the conch filename and initialize the name to
28199   ** the name of the original database file. */  
28200   *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
28201   if( conchPath==0 ){
28202     return SQLITE_NOMEM;
28203   }
28204   memcpy(conchPath, dbPath, len+1);
28205   
28206   /* now insert a "." before the last / character */
28207   for( i=(len-1); i>=0; i-- ){
28208     if( conchPath[i]=='/' ){
28209       i++;
28210       break;
28211     }
28212   }
28213   conchPath[i]='.';
28214   while ( i<len ){
28215     conchPath[i+1]=dbPath[i];
28216     i++;
28217   }
28218
28219   /* append the "-conch" suffix to the file */
28220   memcpy(&conchPath[i+1], "-conch", 7);
28221   assert( (int)strlen(conchPath) == len+7 );
28222
28223   return SQLITE_OK;
28224 }
28225
28226
28227 /* Takes a fully configured proxy locking-style unix file and switches
28228 ** the local lock file path 
28229 */
28230 static int switchLockProxyPath(unixFile *pFile, const char *path) {
28231   proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
28232   char *oldPath = pCtx->lockProxyPath;
28233   int rc = SQLITE_OK;
28234
28235   if( pFile->eFileLock!=NO_LOCK ){
28236     return SQLITE_BUSY;
28237   }  
28238
28239   /* nothing to do if the path is NULL, :auto: or matches the existing path */
28240   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
28241     (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
28242     return SQLITE_OK;
28243   }else{
28244     unixFile *lockProxy = pCtx->lockProxy;
28245     pCtx->lockProxy=NULL;
28246     pCtx->conchHeld = 0;
28247     if( lockProxy!=NULL ){
28248       rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
28249       if( rc ) return rc;
28250       sqlite3_free(lockProxy);
28251     }
28252     sqlite3_free(oldPath);
28253     pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
28254   }
28255   
28256   return rc;
28257 }
28258
28259 /*
28260 ** pFile is a file that has been opened by a prior xOpen call.  dbPath
28261 ** is a string buffer at least MAXPATHLEN+1 characters in size.
28262 **
28263 ** This routine find the filename associated with pFile and writes it
28264 ** int dbPath.
28265 */
28266 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
28267 #if defined(__APPLE__)
28268   if( pFile->pMethod == &afpIoMethods ){
28269     /* afp style keeps a reference to the db path in the filePath field 
28270     ** of the struct */
28271     assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
28272     strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
28273   } else
28274 #endif
28275   if( pFile->pMethod == &dotlockIoMethods ){
28276     /* dot lock style uses the locking context to store the dot lock
28277     ** file path */
28278     int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
28279     memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
28280   }else{
28281     /* all other styles use the locking context to store the db file path */
28282     assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
28283     strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
28284   }
28285   return SQLITE_OK;
28286 }
28287
28288 /*
28289 ** Takes an already filled in unix file and alters it so all file locking 
28290 ** will be performed on the local proxy lock file.  The following fields
28291 ** are preserved in the locking context so that they can be restored and 
28292 ** the unix structure properly cleaned up at close time:
28293 **  ->lockingContext
28294 **  ->pMethod
28295 */
28296 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
28297   proxyLockingContext *pCtx;
28298   char dbPath[MAXPATHLEN+1];       /* Name of the database file */
28299   char *lockPath=NULL;
28300   int rc = SQLITE_OK;
28301   
28302   if( pFile->eFileLock!=NO_LOCK ){
28303     return SQLITE_BUSY;
28304   }
28305   proxyGetDbPathForUnixFile(pFile, dbPath);
28306   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
28307     lockPath=NULL;
28308   }else{
28309     lockPath=(char *)path;
28310   }
28311   
28312   OSTRACE(("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
28313            (lockPath ? lockPath : ":auto:"), getpid()));
28314
28315   pCtx = sqlite3_malloc( sizeof(*pCtx) );
28316   if( pCtx==0 ){
28317     return SQLITE_NOMEM;
28318   }
28319   memset(pCtx, 0, sizeof(*pCtx));
28320
28321   rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
28322   if( rc==SQLITE_OK ){
28323     rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
28324     if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
28325       /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
28326       ** (c) the file system is read-only, then enable no-locking access.
28327       ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
28328       ** that openFlags will have only one of O_RDONLY or O_RDWR.
28329       */
28330       struct statfs fsInfo;
28331       struct stat conchInfo;
28332       int goLockless = 0;
28333
28334       if( stat(pCtx->conchFilePath, &conchInfo) == -1 ) {
28335         int err = errno;
28336         if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
28337           goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
28338         }
28339       }
28340       if( goLockless ){
28341         pCtx->conchHeld = -1; /* read only FS/ lockless */
28342         rc = SQLITE_OK;
28343       }
28344     }
28345   }  
28346   if( rc==SQLITE_OK && lockPath ){
28347     pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
28348   }
28349
28350   if( rc==SQLITE_OK ){
28351     pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
28352     if( pCtx->dbPath==NULL ){
28353       rc = SQLITE_NOMEM;
28354     }
28355   }
28356   if( rc==SQLITE_OK ){
28357     /* all memory is allocated, proxys are created and assigned, 
28358     ** switch the locking context and pMethod then return.
28359     */
28360     pCtx->oldLockingContext = pFile->lockingContext;
28361     pFile->lockingContext = pCtx;
28362     pCtx->pOldMethod = pFile->pMethod;
28363     pFile->pMethod = &proxyIoMethods;
28364   }else{
28365     if( pCtx->conchFile ){ 
28366       pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
28367       sqlite3_free(pCtx->conchFile);
28368     }
28369     sqlite3_free(pCtx->lockProxyPath);
28370     sqlite3_free(pCtx->conchFilePath); 
28371     sqlite3_free(pCtx);
28372   }
28373   OSTRACE(("TRANSPROXY  %d %s\n", pFile->h,
28374            (rc==SQLITE_OK ? "ok" : "failed")));
28375   return rc;
28376 }
28377
28378
28379 /*
28380 ** This routine handles sqlite3_file_control() calls that are specific
28381 ** to proxy locking.
28382 */
28383 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
28384   switch( op ){
28385     case SQLITE_GET_LOCKPROXYFILE: {
28386       unixFile *pFile = (unixFile*)id;
28387       if( pFile->pMethod == &proxyIoMethods ){
28388         proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
28389         proxyTakeConch(pFile);
28390         if( pCtx->lockProxyPath ){
28391           *(const char **)pArg = pCtx->lockProxyPath;
28392         }else{
28393           *(const char **)pArg = ":auto: (not held)";
28394         }
28395       } else {
28396         *(const char **)pArg = NULL;
28397       }
28398       return SQLITE_OK;
28399     }
28400     case SQLITE_SET_LOCKPROXYFILE: {
28401       unixFile *pFile = (unixFile*)id;
28402       int rc = SQLITE_OK;
28403       int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
28404       if( pArg==NULL || (const char *)pArg==0 ){
28405         if( isProxyStyle ){
28406           /* turn off proxy locking - not supported */
28407           rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
28408         }else{
28409           /* turn off proxy locking - already off - NOOP */
28410           rc = SQLITE_OK;
28411         }
28412       }else{
28413         const char *proxyPath = (const char *)pArg;
28414         if( isProxyStyle ){
28415           proxyLockingContext *pCtx = 
28416             (proxyLockingContext*)pFile->lockingContext;
28417           if( !strcmp(pArg, ":auto:") 
28418            || (pCtx->lockProxyPath &&
28419                !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
28420           ){
28421             rc = SQLITE_OK;
28422           }else{
28423             rc = switchLockProxyPath(pFile, proxyPath);
28424           }
28425         }else{
28426           /* turn on proxy file locking */
28427           rc = proxyTransformUnixFile(pFile, proxyPath);
28428         }
28429       }
28430       return rc;
28431     }
28432     default: {
28433       assert( 0 );  /* The call assures that only valid opcodes are sent */
28434     }
28435   }
28436   /*NOTREACHED*/
28437   return SQLITE_ERROR;
28438 }
28439
28440 /*
28441 ** Within this division (the proxying locking implementation) the procedures
28442 ** above this point are all utilities.  The lock-related methods of the
28443 ** proxy-locking sqlite3_io_method object follow.
28444 */
28445
28446
28447 /*
28448 ** This routine checks if there is a RESERVED lock held on the specified
28449 ** file by this or any other process. If such a lock is held, set *pResOut
28450 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
28451 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
28452 */
28453 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
28454   unixFile *pFile = (unixFile*)id;
28455   int rc = proxyTakeConch(pFile);
28456   if( rc==SQLITE_OK ){
28457     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
28458     if( pCtx->conchHeld>0 ){
28459       unixFile *proxy = pCtx->lockProxy;
28460       return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
28461     }else{ /* conchHeld < 0 is lockless */
28462       pResOut=0;
28463     }
28464   }
28465   return rc;
28466 }
28467
28468 /*
28469 ** Lock the file with the lock specified by parameter eFileLock - one
28470 ** of the following:
28471 **
28472 **     (1) SHARED_LOCK
28473 **     (2) RESERVED_LOCK
28474 **     (3) PENDING_LOCK
28475 **     (4) EXCLUSIVE_LOCK
28476 **
28477 ** Sometimes when requesting one lock state, additional lock states
28478 ** are inserted in between.  The locking might fail on one of the later
28479 ** transitions leaving the lock state different from what it started but
28480 ** still short of its goal.  The following chart shows the allowed
28481 ** transitions and the inserted intermediate states:
28482 **
28483 **    UNLOCKED -> SHARED
28484 **    SHARED -> RESERVED
28485 **    SHARED -> (PENDING) -> EXCLUSIVE
28486 **    RESERVED -> (PENDING) -> EXCLUSIVE
28487 **    PENDING -> EXCLUSIVE
28488 **
28489 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
28490 ** routine to lower a locking level.
28491 */
28492 static int proxyLock(sqlite3_file *id, int eFileLock) {
28493   unixFile *pFile = (unixFile*)id;
28494   int rc = proxyTakeConch(pFile);
28495   if( rc==SQLITE_OK ){
28496     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
28497     if( pCtx->conchHeld>0 ){
28498       unixFile *proxy = pCtx->lockProxy;
28499       rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
28500       pFile->eFileLock = proxy->eFileLock;
28501     }else{
28502       /* conchHeld < 0 is lockless */
28503     }
28504   }
28505   return rc;
28506 }
28507
28508
28509 /*
28510 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
28511 ** must be either NO_LOCK or SHARED_LOCK.
28512 **
28513 ** If the locking level of the file descriptor is already at or below
28514 ** the requested locking level, this routine is a no-op.
28515 */
28516 static int proxyUnlock(sqlite3_file *id, int eFileLock) {
28517   unixFile *pFile = (unixFile*)id;
28518   int rc = proxyTakeConch(pFile);
28519   if( rc==SQLITE_OK ){
28520     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
28521     if( pCtx->conchHeld>0 ){
28522       unixFile *proxy = pCtx->lockProxy;
28523       rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
28524       pFile->eFileLock = proxy->eFileLock;
28525     }else{
28526       /* conchHeld < 0 is lockless */
28527     }
28528   }
28529   return rc;
28530 }
28531
28532 /*
28533 ** Close a file that uses proxy locks.
28534 */
28535 static int proxyClose(sqlite3_file *id) {
28536   if( id ){
28537     unixFile *pFile = (unixFile*)id;
28538     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
28539     unixFile *lockProxy = pCtx->lockProxy;
28540     unixFile *conchFile = pCtx->conchFile;
28541     int rc = SQLITE_OK;
28542     
28543     if( lockProxy ){
28544       rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
28545       if( rc ) return rc;
28546       rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
28547       if( rc ) return rc;
28548       sqlite3_free(lockProxy);
28549       pCtx->lockProxy = 0;
28550     }
28551     if( conchFile ){
28552       if( pCtx->conchHeld ){
28553         rc = proxyReleaseConch(pFile);
28554         if( rc ) return rc;
28555       }
28556       rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
28557       if( rc ) return rc;
28558       sqlite3_free(conchFile);
28559     }
28560     sqlite3_free(pCtx->lockProxyPath);
28561     sqlite3_free(pCtx->conchFilePath);
28562     sqlite3_free(pCtx->dbPath);
28563     /* restore the original locking context and pMethod then close it */
28564     pFile->lockingContext = pCtx->oldLockingContext;
28565     pFile->pMethod = pCtx->pOldMethod;
28566     sqlite3_free(pCtx);
28567     return pFile->pMethod->xClose(id);
28568   }
28569   return SQLITE_OK;
28570 }
28571
28572
28573
28574 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
28575 /*
28576 ** The proxy locking style is intended for use with AFP filesystems.
28577 ** And since AFP is only supported on MacOSX, the proxy locking is also
28578 ** restricted to MacOSX.
28579 ** 
28580 **
28581 ******************* End of the proxy lock implementation **********************
28582 ******************************************************************************/
28583
28584 /*
28585 ** Initialize the operating system interface.
28586 **
28587 ** This routine registers all VFS implementations for unix-like operating
28588 ** systems.  This routine, and the sqlite3_os_end() routine that follows,
28589 ** should be the only routines in this file that are visible from other
28590 ** files.
28591 **
28592 ** This routine is called once during SQLite initialization and by a
28593 ** single thread.  The memory allocation and mutex subsystems have not
28594 ** necessarily been initialized when this routine is called, and so they
28595 ** should not be used.
28596 */
28597 SQLITE_API int sqlite3_os_init(void){ 
28598   /* 
28599   ** The following macro defines an initializer for an sqlite3_vfs object.
28600   ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
28601   ** to the "finder" function.  (pAppData is a pointer to a pointer because
28602   ** silly C90 rules prohibit a void* from being cast to a function pointer
28603   ** and so we have to go through the intermediate pointer to avoid problems
28604   ** when compiling with -pedantic-errors on GCC.)
28605   **
28606   ** The FINDER parameter to this macro is the name of the pointer to the
28607   ** finder-function.  The finder-function returns a pointer to the
28608   ** sqlite_io_methods object that implements the desired locking
28609   ** behaviors.  See the division above that contains the IOMETHODS
28610   ** macro for addition information on finder-functions.
28611   **
28612   ** Most finders simply return a pointer to a fixed sqlite3_io_methods
28613   ** object.  But the "autolockIoFinder" available on MacOSX does a little
28614   ** more than that; it looks at the filesystem type that hosts the 
28615   ** database file and tries to choose an locking method appropriate for
28616   ** that filesystem time.
28617   */
28618   #define UNIXVFS(VFSNAME, FINDER) {                        \
28619     2,                    /* iVersion */                    \
28620     sizeof(unixFile),     /* szOsFile */                    \
28621     MAX_PATHNAME,         /* mxPathname */                  \
28622     0,                    /* pNext */                       \
28623     VFSNAME,              /* zName */                       \
28624     (void*)&FINDER,       /* pAppData */                    \
28625     unixOpen,             /* xOpen */                       \
28626     unixDelete,           /* xDelete */                     \
28627     unixAccess,           /* xAccess */                     \
28628     unixFullPathname,     /* xFullPathname */               \
28629     unixDlOpen,           /* xDlOpen */                     \
28630     unixDlError,          /* xDlError */                    \
28631     unixDlSym,            /* xDlSym */                      \
28632     unixDlClose,          /* xDlClose */                    \
28633     unixRandomness,       /* xRandomness */                 \
28634     unixSleep,            /* xSleep */                      \
28635     unixCurrentTime,      /* xCurrentTime */                \
28636     unixGetLastError,     /* xGetLastError */               \
28637     unixCurrentTimeInt64, /* xCurrentTimeInt64 */           \
28638   }
28639
28640   /*
28641   ** All default VFSes for unix are contained in the following array.
28642   **
28643   ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
28644   ** by the SQLite core when the VFS is registered.  So the following
28645   ** array cannot be const.
28646   */
28647   static sqlite3_vfs aVfs[] = {
28648 #if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
28649     UNIXVFS("unix",          autolockIoFinder ),
28650 #else
28651     UNIXVFS("unix",          posixIoFinder ),
28652 #endif
28653     UNIXVFS("unix-none",     nolockIoFinder ),
28654     UNIXVFS("unix-dotfile",  dotlockIoFinder ),
28655 #if OS_VXWORKS
28656     UNIXVFS("unix-namedsem", semIoFinder ),
28657 #endif
28658 #if SQLITE_ENABLE_LOCKING_STYLE
28659     UNIXVFS("unix-posix",    posixIoFinder ),
28660 #if !OS_VXWORKS
28661     UNIXVFS("unix-flock",    flockIoFinder ),
28662 #endif
28663 #endif
28664 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
28665     UNIXVFS("unix-afp",      afpIoFinder ),
28666     UNIXVFS("unix-nfs",      nfsIoFinder ),
28667     UNIXVFS("unix-proxy",    proxyIoFinder ),
28668 #endif
28669   };
28670   unsigned int i;          /* Loop counter */
28671
28672   /* Register all VFSes defined in the aVfs[] array */
28673   for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
28674     sqlite3_vfs_register(&aVfs[i], i==0);
28675   }
28676   return SQLITE_OK; 
28677 }
28678
28679 /*
28680 ** Shutdown the operating system interface.
28681 **
28682 ** Some operating systems might need to do some cleanup in this routine,
28683 ** to release dynamically allocated objects.  But not on unix.
28684 ** This routine is a no-op for unix.
28685 */
28686 SQLITE_API int sqlite3_os_end(void){ 
28687   return SQLITE_OK; 
28688 }
28689  
28690 #endif /* SQLITE_OS_UNIX */
28691
28692 /************** End of os_unix.c *********************************************/
28693 /************** Begin file os_win.c ******************************************/
28694 /*
28695 ** 2004 May 22
28696 **
28697 ** The author disclaims copyright to this source code.  In place of
28698 ** a legal notice, here is a blessing:
28699 **
28700 **    May you do good and not evil.
28701 **    May you find forgiveness for yourself and forgive others.
28702 **    May you share freely, never taking more than you give.
28703 **
28704 ******************************************************************************
28705 **
28706 ** This file contains code that is specific to windows.
28707 */
28708 #if SQLITE_OS_WIN               /* This file is used for windows only */
28709
28710
28711 /*
28712 ** A Note About Memory Allocation:
28713 **
28714 ** This driver uses malloc()/free() directly rather than going through
28715 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
28716 ** are designed for use on embedded systems where memory is scarce and
28717 ** malloc failures happen frequently.  Win32 does not typically run on
28718 ** embedded systems, and when it does the developers normally have bigger
28719 ** problems to worry about than running out of memory.  So there is not
28720 ** a compelling need to use the wrappers.
28721 **
28722 ** But there is a good reason to not use the wrappers.  If we use the
28723 ** wrappers then we will get simulated malloc() failures within this
28724 ** driver.  And that causes all kinds of problems for our tests.  We
28725 ** could enhance SQLite to deal with simulated malloc failures within
28726 ** the OS driver, but the code to deal with those failure would not
28727 ** be exercised on Linux (which does not need to malloc() in the driver)
28728 ** and so we would have difficulty writing coverage tests for that
28729 ** code.  Better to leave the code out, we think.
28730 **
28731 ** The point of this discussion is as follows:  When creating a new
28732 ** OS layer for an embedded system, if you use this file as an example,
28733 ** avoid the use of malloc()/free().  Those routines work ok on windows
28734 ** desktops but not so well in embedded systems.
28735 */
28736
28737 #include <winbase.h>
28738
28739 #ifdef __CYGWIN__
28740 # include <sys/cygwin.h>
28741 #endif
28742
28743 /*
28744 ** Macros used to determine whether or not to use threads.
28745 */
28746 #if defined(THREADSAFE) && THREADSAFE
28747 # define SQLITE_W32_THREADS 1
28748 #endif
28749
28750 /*
28751 ** Include code that is common to all os_*.c files
28752 */
28753 /************** Include os_common.h in the middle of os_win.c ****************/
28754 /************** Begin file os_common.h ***************************************/
28755 /*
28756 ** 2004 May 22
28757 **
28758 ** The author disclaims copyright to this source code.  In place of
28759 ** a legal notice, here is a blessing:
28760 **
28761 **    May you do good and not evil.
28762 **    May you find forgiveness for yourself and forgive others.
28763 **    May you share freely, never taking more than you give.
28764 **
28765 ******************************************************************************
28766 **
28767 ** This file contains macros and a little bit of code that is common to
28768 ** all of the platform-specific files (os_*.c) and is #included into those
28769 ** files.
28770 **
28771 ** This file should be #included by the os_*.c files only.  It is not a
28772 ** general purpose header file.
28773 */
28774 #ifndef _OS_COMMON_H_
28775 #define _OS_COMMON_H_
28776
28777 /*
28778 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
28779 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
28780 ** switch.  The following code should catch this problem at compile-time.
28781 */
28782 #ifdef MEMORY_DEBUG
28783 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
28784 #endif
28785
28786 #ifdef SQLITE_DEBUG
28787 SQLITE_PRIVATE int sqlite3OSTrace = 0;
28788 #define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
28789 #else
28790 #define OSTRACE(X)
28791 #endif
28792
28793 /*
28794 ** Macros for performance tracing.  Normally turned off.  Only works
28795 ** on i486 hardware.
28796 */
28797 #ifdef SQLITE_PERFORMANCE_TRACE
28798
28799 /* 
28800 ** hwtime.h contains inline assembler code for implementing 
28801 ** high-performance timing routines.
28802 */
28803 /************** Include hwtime.h in the middle of os_common.h ****************/
28804 /************** Begin file hwtime.h ******************************************/
28805 /*
28806 ** 2008 May 27
28807 **
28808 ** The author disclaims copyright to this source code.  In place of
28809 ** a legal notice, here is a blessing:
28810 **
28811 **    May you do good and not evil.
28812 **    May you find forgiveness for yourself and forgive others.
28813 **    May you share freely, never taking more than you give.
28814 **
28815 ******************************************************************************
28816 **
28817 ** This file contains inline asm code for retrieving "high-performance"
28818 ** counters for x86 class CPUs.
28819 */
28820 #ifndef _HWTIME_H_
28821 #define _HWTIME_H_
28822
28823 /*
28824 ** The following routine only works on pentium-class (or newer) processors.
28825 ** It uses the RDTSC opcode to read the cycle count value out of the
28826 ** processor and returns that value.  This can be used for high-res
28827 ** profiling.
28828 */
28829 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
28830       (defined(i386) || defined(__i386__) || defined(_M_IX86))
28831
28832   #if defined(__GNUC__)
28833
28834   __inline__ sqlite_uint64 sqlite3Hwtime(void){
28835      unsigned int lo, hi;
28836      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
28837      return (sqlite_uint64)hi << 32 | lo;
28838   }
28839
28840   #elif defined(_MSC_VER)
28841
28842   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
28843      __asm {
28844         rdtsc
28845         ret       ; return value at EDX:EAX
28846      }
28847   }
28848
28849   #endif
28850
28851 #elif (defined(__GNUC__) && defined(__x86_64__))
28852
28853   __inline__ sqlite_uint64 sqlite3Hwtime(void){
28854       unsigned long val;
28855       __asm__ __volatile__ ("rdtsc" : "=A" (val));
28856       return val;
28857   }
28858  
28859 #elif (defined(__GNUC__) && defined(__ppc__))
28860
28861   __inline__ sqlite_uint64 sqlite3Hwtime(void){
28862       unsigned long long retval;
28863       unsigned long junk;
28864       __asm__ __volatile__ ("\n\
28865           1:      mftbu   %1\n\
28866                   mftb    %L0\n\
28867                   mftbu   %0\n\
28868                   cmpw    %0,%1\n\
28869                   bne     1b"
28870                   : "=r" (retval), "=r" (junk));
28871       return retval;
28872   }
28873
28874 #else
28875
28876   #error Need implementation of sqlite3Hwtime() for your platform.
28877
28878   /*
28879   ** To compile without implementing sqlite3Hwtime() for your platform,
28880   ** you can remove the above #error and use the following
28881   ** stub function.  You will lose timing support for many
28882   ** of the debugging and testing utilities, but it should at
28883   ** least compile and run.
28884   */
28885 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
28886
28887 #endif
28888
28889 #endif /* !defined(_HWTIME_H_) */
28890
28891 /************** End of hwtime.h **********************************************/
28892 /************** Continuing where we left off in os_common.h ******************/
28893
28894 static sqlite_uint64 g_start;
28895 static sqlite_uint64 g_elapsed;
28896 #define TIMER_START       g_start=sqlite3Hwtime()
28897 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
28898 #define TIMER_ELAPSED     g_elapsed
28899 #else
28900 #define TIMER_START
28901 #define TIMER_END
28902 #define TIMER_ELAPSED     ((sqlite_uint64)0)
28903 #endif
28904
28905 /*
28906 ** If we compile with the SQLITE_TEST macro set, then the following block
28907 ** of code will give us the ability to simulate a disk I/O error.  This
28908 ** is used for testing the I/O recovery logic.
28909 */
28910 #ifdef SQLITE_TEST
28911 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
28912 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
28913 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
28914 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
28915 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
28916 SQLITE_API int sqlite3_diskfull_pending = 0;
28917 SQLITE_API int sqlite3_diskfull = 0;
28918 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
28919 #define SimulateIOError(CODE)  \
28920   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
28921        || sqlite3_io_error_pending-- == 1 )  \
28922               { local_ioerr(); CODE; }
28923 static void local_ioerr(){
28924   IOTRACE(("IOERR\n"));
28925   sqlite3_io_error_hit++;
28926   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
28927 }
28928 #define SimulateDiskfullError(CODE) \
28929    if( sqlite3_diskfull_pending ){ \
28930      if( sqlite3_diskfull_pending == 1 ){ \
28931        local_ioerr(); \
28932        sqlite3_diskfull = 1; \
28933        sqlite3_io_error_hit = 1; \
28934        CODE; \
28935      }else{ \
28936        sqlite3_diskfull_pending--; \
28937      } \
28938    }
28939 #else
28940 #define SimulateIOErrorBenign(X)
28941 #define SimulateIOError(A)
28942 #define SimulateDiskfullError(A)
28943 #endif
28944
28945 /*
28946 ** When testing, keep a count of the number of open files.
28947 */
28948 #ifdef SQLITE_TEST
28949 SQLITE_API int sqlite3_open_file_count = 0;
28950 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
28951 #else
28952 #define OpenCounter(X)
28953 #endif
28954
28955 #endif /* !defined(_OS_COMMON_H_) */
28956
28957 /************** End of os_common.h *******************************************/
28958 /************** Continuing where we left off in os_win.c *********************/
28959
28960 /*
28961 ** Some microsoft compilers lack this definition.
28962 */
28963 #ifndef INVALID_FILE_ATTRIBUTES
28964 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1) 
28965 #endif
28966
28967 /*
28968 ** Determine if we are dealing with WindowsCE - which has a much
28969 ** reduced API.
28970 */
28971 #if SQLITE_OS_WINCE
28972 # define AreFileApisANSI() 1
28973 # define FormatMessageW(a,b,c,d,e,f,g) 0
28974 #endif
28975
28976 /* Forward references */
28977 typedef struct winShm winShm;           /* A connection to shared-memory */
28978 typedef struct winShmNode winShmNode;   /* A region of shared-memory */
28979
28980 /*
28981 ** WinCE lacks native support for file locking so we have to fake it
28982 ** with some code of our own.
28983 */
28984 #if SQLITE_OS_WINCE
28985 typedef struct winceLock {
28986   int nReaders;       /* Number of reader locks obtained */
28987   BOOL bPending;      /* Indicates a pending lock has been obtained */
28988   BOOL bReserved;     /* Indicates a reserved lock has been obtained */
28989   BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
28990 } winceLock;
28991 #endif
28992
28993 /*
28994 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
28995 ** portability layer.
28996 */
28997 typedef struct winFile winFile;
28998 struct winFile {
28999   const sqlite3_io_methods *pMethod; /*** Must be first ***/
29000   sqlite3_vfs *pVfs;      /* The VFS used to open this file */
29001   HANDLE h;               /* Handle for accessing the file */
29002   unsigned char locktype; /* Type of lock currently held on this file */
29003   short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
29004   DWORD lastErrno;        /* The Windows errno from the last I/O error */
29005   DWORD sectorSize;       /* Sector size of the device file is on */
29006   winShm *pShm;           /* Instance of shared memory on this file */
29007   const char *zPath;      /* Full pathname of this file */
29008 #if SQLITE_OS_WINCE
29009   WCHAR *zDeleteOnClose;  /* Name of file to delete when closing */
29010   HANDLE hMutex;          /* Mutex used to control access to shared lock */  
29011   HANDLE hShared;         /* Shared memory segment used for locking */
29012   winceLock local;        /* Locks obtained by this instance of winFile */
29013   winceLock *shared;      /* Global shared lock memory for the file  */
29014 #endif
29015 };
29016
29017 /*
29018 ** Forward prototypes.
29019 */
29020 static int getSectorSize(
29021     sqlite3_vfs *pVfs,
29022     const char *zRelative     /* UTF-8 file name */
29023 );
29024
29025 /*
29026 ** The following variable is (normally) set once and never changes
29027 ** thereafter.  It records whether the operating system is Win95
29028 ** or WinNT.
29029 **
29030 ** 0:   Operating system unknown.
29031 ** 1:   Operating system is Win95.
29032 ** 2:   Operating system is WinNT.
29033 **
29034 ** In order to facilitate testing on a WinNT system, the test fixture
29035 ** can manually set this value to 1 to emulate Win98 behavior.
29036 */
29037 #ifdef SQLITE_TEST
29038 SQLITE_API int sqlite3_os_type = 0;
29039 #else
29040 static int sqlite3_os_type = 0;
29041 #endif
29042
29043 /*
29044 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
29045 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
29046 **
29047 ** Here is an interesting observation:  Win95, Win98, and WinME lack
29048 ** the LockFileEx() API.  But we can still statically link against that
29049 ** API as long as we don't call it when running Win95/98/ME.  A call to
29050 ** this routine is used to determine if the host is Win95/98/ME or
29051 ** WinNT/2K/XP so that we will know whether or not we can safely call
29052 ** the LockFileEx() API.
29053 */
29054 #if SQLITE_OS_WINCE
29055 # define isNT()  (1)
29056 #else
29057   static int isNT(void){
29058     if( sqlite3_os_type==0 ){
29059       OSVERSIONINFO sInfo;
29060       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
29061       GetVersionEx(&sInfo);
29062       sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
29063     }
29064     return sqlite3_os_type==2;
29065   }
29066 #endif /* SQLITE_OS_WINCE */
29067
29068 /*
29069 ** Convert a UTF-8 string to microsoft unicode (UTF-16?). 
29070 **
29071 ** Space to hold the returned string is obtained from malloc.
29072 */
29073 static WCHAR *utf8ToUnicode(const char *zFilename){
29074   int nChar;
29075   WCHAR *zWideFilename;
29076
29077   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
29078   zWideFilename = malloc( nChar*sizeof(zWideFilename[0]) );
29079   if( zWideFilename==0 ){
29080     return 0;
29081   }
29082   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar);
29083   if( nChar==0 ){
29084     free(zWideFilename);
29085     zWideFilename = 0;
29086   }
29087   return zWideFilename;
29088 }
29089
29090 /*
29091 ** Convert microsoft unicode to UTF-8.  Space to hold the returned string is
29092 ** obtained from malloc().
29093 */
29094 static char *unicodeToUtf8(const WCHAR *zWideFilename){
29095   int nByte;
29096   char *zFilename;
29097
29098   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
29099   zFilename = malloc( nByte );
29100   if( zFilename==0 ){
29101     return 0;
29102   }
29103   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
29104                               0, 0);
29105   if( nByte == 0 ){
29106     free(zFilename);
29107     zFilename = 0;
29108   }
29109   return zFilename;
29110 }
29111
29112 /*
29113 ** Convert an ansi string to microsoft unicode, based on the
29114 ** current codepage settings for file apis.
29115 ** 
29116 ** Space to hold the returned string is obtained
29117 ** from malloc.
29118 */
29119 static WCHAR *mbcsToUnicode(const char *zFilename){
29120   int nByte;
29121   WCHAR *zMbcsFilename;
29122   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
29123
29124   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*sizeof(WCHAR);
29125   zMbcsFilename = malloc( nByte*sizeof(zMbcsFilename[0]) );
29126   if( zMbcsFilename==0 ){
29127     return 0;
29128   }
29129   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte);
29130   if( nByte==0 ){
29131     free(zMbcsFilename);
29132     zMbcsFilename = 0;
29133   }
29134   return zMbcsFilename;
29135 }
29136
29137 /*
29138 ** Convert microsoft unicode to multibyte character string, based on the
29139 ** user's Ansi codepage.
29140 **
29141 ** Space to hold the returned string is obtained from
29142 ** malloc().
29143 */
29144 static char *unicodeToMbcs(const WCHAR *zWideFilename){
29145   int nByte;
29146   char *zFilename;
29147   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
29148
29149   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
29150   zFilename = malloc( nByte );
29151   if( zFilename==0 ){
29152     return 0;
29153   }
29154   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte,
29155                               0, 0);
29156   if( nByte == 0 ){
29157     free(zFilename);
29158     zFilename = 0;
29159   }
29160   return zFilename;
29161 }
29162
29163 /*
29164 ** Convert multibyte character string to UTF-8.  Space to hold the
29165 ** returned string is obtained from malloc().
29166 */
29167 SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
29168   char *zFilenameUtf8;
29169   WCHAR *zTmpWide;
29170
29171   zTmpWide = mbcsToUnicode(zFilename);
29172   if( zTmpWide==0 ){
29173     return 0;
29174   }
29175   zFilenameUtf8 = unicodeToUtf8(zTmpWide);
29176   free(zTmpWide);
29177   return zFilenameUtf8;
29178 }
29179
29180 /*
29181 ** Convert UTF-8 to multibyte character string.  Space to hold the 
29182 ** returned string is obtained from malloc().
29183 */
29184 static char *utf8ToMbcs(const char *zFilename){
29185   char *zFilenameMbcs;
29186   WCHAR *zTmpWide;
29187
29188   zTmpWide = utf8ToUnicode(zFilename);
29189   if( zTmpWide==0 ){
29190     return 0;
29191   }
29192   zFilenameMbcs = unicodeToMbcs(zTmpWide);
29193   free(zTmpWide);
29194   return zFilenameMbcs;
29195 }
29196
29197 #if SQLITE_OS_WINCE
29198 /*************************************************************************
29199 ** This section contains code for WinCE only.
29200 */
29201 /*
29202 ** WindowsCE does not have a localtime() function.  So create a
29203 ** substitute.
29204 */
29205 struct tm *__cdecl localtime(const time_t *t)
29206 {
29207   static struct tm y;
29208   FILETIME uTm, lTm;
29209   SYSTEMTIME pTm;
29210   sqlite3_int64 t64;
29211   t64 = *t;
29212   t64 = (t64 + 11644473600)*10000000;
29213   uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
29214   uTm.dwHighDateTime= (DWORD)(t64 >> 32);
29215   FileTimeToLocalFileTime(&uTm,&lTm);
29216   FileTimeToSystemTime(&lTm,&pTm);
29217   y.tm_year = pTm.wYear - 1900;
29218   y.tm_mon = pTm.wMonth - 1;
29219   y.tm_wday = pTm.wDayOfWeek;
29220   y.tm_mday = pTm.wDay;
29221   y.tm_hour = pTm.wHour;
29222   y.tm_min = pTm.wMinute;
29223   y.tm_sec = pTm.wSecond;
29224   return &y;
29225 }
29226
29227 /* This will never be called, but defined to make the code compile */
29228 #define GetTempPathA(a,b)
29229
29230 #define LockFile(a,b,c,d,e)       winceLockFile(&a, b, c, d, e)
29231 #define UnlockFile(a,b,c,d,e)     winceUnlockFile(&a, b, c, d, e)
29232 #define LockFileEx(a,b,c,d,e,f)   winceLockFileEx(&a, b, c, d, e, f)
29233
29234 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
29235
29236 /*
29237 ** Acquire a lock on the handle h
29238 */
29239 static void winceMutexAcquire(HANDLE h){
29240    DWORD dwErr;
29241    do {
29242      dwErr = WaitForSingleObject(h, INFINITE);
29243    } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
29244 }
29245 /*
29246 ** Release a lock acquired by winceMutexAcquire()
29247 */
29248 #define winceMutexRelease(h) ReleaseMutex(h)
29249
29250 /*
29251 ** Create the mutex and shared memory used for locking in the file
29252 ** descriptor pFile
29253 */
29254 static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
29255   WCHAR *zTok;
29256   WCHAR *zName = utf8ToUnicode(zFilename);
29257   BOOL bInit = TRUE;
29258
29259   /* Initialize the local lockdata */
29260   ZeroMemory(&pFile->local, sizeof(pFile->local));
29261
29262   /* Replace the backslashes from the filename and lowercase it
29263   ** to derive a mutex name. */
29264   zTok = CharLowerW(zName);
29265   for (;*zTok;zTok++){
29266     if (*zTok == '\\') *zTok = '_';
29267   }
29268
29269   /* Create/open the named mutex */
29270   pFile->hMutex = CreateMutexW(NULL, FALSE, zName);
29271   if (!pFile->hMutex){
29272     pFile->lastErrno = GetLastError();
29273     free(zName);
29274     return FALSE;
29275   }
29276
29277   /* Acquire the mutex before continuing */
29278   winceMutexAcquire(pFile->hMutex);
29279   
29280   /* Since the names of named mutexes, semaphores, file mappings etc are 
29281   ** case-sensitive, take advantage of that by uppercasing the mutex name
29282   ** and using that as the shared filemapping name.
29283   */
29284   CharUpperW(zName);
29285   pFile->hShared = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
29286                                        PAGE_READWRITE, 0, sizeof(winceLock),
29287                                        zName);  
29288
29289   /* Set a flag that indicates we're the first to create the memory so it 
29290   ** must be zero-initialized */
29291   if (GetLastError() == ERROR_ALREADY_EXISTS){
29292     bInit = FALSE;
29293   }
29294
29295   free(zName);
29296
29297   /* If we succeeded in making the shared memory handle, map it. */
29298   if (pFile->hShared){
29299     pFile->shared = (winceLock*)MapViewOfFile(pFile->hShared, 
29300              FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
29301     /* If mapping failed, close the shared memory handle and erase it */
29302     if (!pFile->shared){
29303       pFile->lastErrno = GetLastError();
29304       CloseHandle(pFile->hShared);
29305       pFile->hShared = NULL;
29306     }
29307   }
29308
29309   /* If shared memory could not be created, then close the mutex and fail */
29310   if (pFile->hShared == NULL){
29311     winceMutexRelease(pFile->hMutex);
29312     CloseHandle(pFile->hMutex);
29313     pFile->hMutex = NULL;
29314     return FALSE;
29315   }
29316   
29317   /* Initialize the shared memory if we're supposed to */
29318   if (bInit) {
29319     ZeroMemory(pFile->shared, sizeof(winceLock));
29320   }
29321
29322   winceMutexRelease(pFile->hMutex);
29323   return TRUE;
29324 }
29325
29326 /*
29327 ** Destroy the part of winFile that deals with wince locks
29328 */
29329 static void winceDestroyLock(winFile *pFile){
29330   if (pFile->hMutex){
29331     /* Acquire the mutex */
29332     winceMutexAcquire(pFile->hMutex);
29333
29334     /* The following blocks should probably assert in debug mode, but they
29335        are to cleanup in case any locks remained open */
29336     if (pFile->local.nReaders){
29337       pFile->shared->nReaders --;
29338     }
29339     if (pFile->local.bReserved){
29340       pFile->shared->bReserved = FALSE;
29341     }
29342     if (pFile->local.bPending){
29343       pFile->shared->bPending = FALSE;
29344     }
29345     if (pFile->local.bExclusive){
29346       pFile->shared->bExclusive = FALSE;
29347     }
29348
29349     /* De-reference and close our copy of the shared memory handle */
29350     UnmapViewOfFile(pFile->shared);
29351     CloseHandle(pFile->hShared);
29352
29353     /* Done with the mutex */
29354     winceMutexRelease(pFile->hMutex);    
29355     CloseHandle(pFile->hMutex);
29356     pFile->hMutex = NULL;
29357   }
29358 }
29359
29360 /* 
29361 ** An implementation of the LockFile() API of windows for wince
29362 */
29363 static BOOL winceLockFile(
29364   HANDLE *phFile,
29365   DWORD dwFileOffsetLow,
29366   DWORD dwFileOffsetHigh,
29367   DWORD nNumberOfBytesToLockLow,
29368   DWORD nNumberOfBytesToLockHigh
29369 ){
29370   winFile *pFile = HANDLE_TO_WINFILE(phFile);
29371   BOOL bReturn = FALSE;
29372
29373   UNUSED_PARAMETER(dwFileOffsetHigh);
29374   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
29375
29376   if (!pFile->hMutex) return TRUE;
29377   winceMutexAcquire(pFile->hMutex);
29378
29379   /* Wanting an exclusive lock? */
29380   if (dwFileOffsetLow == (DWORD)SHARED_FIRST
29381        && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
29382     if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
29383        pFile->shared->bExclusive = TRUE;
29384        pFile->local.bExclusive = TRUE;
29385        bReturn = TRUE;
29386     }
29387   }
29388
29389   /* Want a read-only lock? */
29390   else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
29391            nNumberOfBytesToLockLow == 1){
29392     if (pFile->shared->bExclusive == 0){
29393       pFile->local.nReaders ++;
29394       if (pFile->local.nReaders == 1){
29395         pFile->shared->nReaders ++;
29396       }
29397       bReturn = TRUE;
29398     }
29399   }
29400
29401   /* Want a pending lock? */
29402   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToLockLow == 1){
29403     /* If no pending lock has been acquired, then acquire it */
29404     if (pFile->shared->bPending == 0) {
29405       pFile->shared->bPending = TRUE;
29406       pFile->local.bPending = TRUE;
29407       bReturn = TRUE;
29408     }
29409   }
29410
29411   /* Want a reserved lock? */
29412   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
29413     if (pFile->shared->bReserved == 0) {
29414       pFile->shared->bReserved = TRUE;
29415       pFile->local.bReserved = TRUE;
29416       bReturn = TRUE;
29417     }
29418   }
29419
29420   winceMutexRelease(pFile->hMutex);
29421   return bReturn;
29422 }
29423
29424 /*
29425 ** An implementation of the UnlockFile API of windows for wince
29426 */
29427 static BOOL winceUnlockFile(
29428   HANDLE *phFile,
29429   DWORD dwFileOffsetLow,
29430   DWORD dwFileOffsetHigh,
29431   DWORD nNumberOfBytesToUnlockLow,
29432   DWORD nNumberOfBytesToUnlockHigh
29433 ){
29434   winFile *pFile = HANDLE_TO_WINFILE(phFile);
29435   BOOL bReturn = FALSE;
29436
29437   UNUSED_PARAMETER(dwFileOffsetHigh);
29438   UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
29439
29440   if (!pFile->hMutex) return TRUE;
29441   winceMutexAcquire(pFile->hMutex);
29442
29443   /* Releasing a reader lock or an exclusive lock */
29444   if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
29445     /* Did we have an exclusive lock? */
29446     if (pFile->local.bExclusive){
29447       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
29448       pFile->local.bExclusive = FALSE;
29449       pFile->shared->bExclusive = FALSE;
29450       bReturn = TRUE;
29451     }
29452
29453     /* Did we just have a reader lock? */
29454     else if (pFile->local.nReaders){
29455       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE || nNumberOfBytesToUnlockLow == 1);
29456       pFile->local.nReaders --;
29457       if (pFile->local.nReaders == 0)
29458       {
29459         pFile->shared->nReaders --;
29460       }
29461       bReturn = TRUE;
29462     }
29463   }
29464
29465   /* Releasing a pending lock */
29466   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
29467     if (pFile->local.bPending){
29468       pFile->local.bPending = FALSE;
29469       pFile->shared->bPending = FALSE;
29470       bReturn = TRUE;
29471     }
29472   }
29473   /* Releasing a reserved lock */
29474   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
29475     if (pFile->local.bReserved) {
29476       pFile->local.bReserved = FALSE;
29477       pFile->shared->bReserved = FALSE;
29478       bReturn = TRUE;
29479     }
29480   }
29481
29482   winceMutexRelease(pFile->hMutex);
29483   return bReturn;
29484 }
29485
29486 /*
29487 ** An implementation of the LockFileEx() API of windows for wince
29488 */
29489 static BOOL winceLockFileEx(
29490   HANDLE *phFile,
29491   DWORD dwFlags,
29492   DWORD dwReserved,
29493   DWORD nNumberOfBytesToLockLow,
29494   DWORD nNumberOfBytesToLockHigh,
29495   LPOVERLAPPED lpOverlapped
29496 ){
29497   UNUSED_PARAMETER(dwReserved);
29498   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
29499
29500   /* If the caller wants a shared read lock, forward this call
29501   ** to winceLockFile */
29502   if (lpOverlapped->Offset == (DWORD)SHARED_FIRST &&
29503       dwFlags == 1 &&
29504       nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
29505     return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
29506   }
29507   return FALSE;
29508 }
29509 /*
29510 ** End of the special code for wince
29511 *****************************************************************************/
29512 #endif /* SQLITE_OS_WINCE */
29513
29514 /*****************************************************************************
29515 ** The next group of routines implement the I/O methods specified
29516 ** by the sqlite3_io_methods object.
29517 ******************************************************************************/
29518
29519 /*
29520 ** Close a file.
29521 **
29522 ** It is reported that an attempt to close a handle might sometimes
29523 ** fail.  This is a very unreasonable result, but windows is notorious
29524 ** for being unreasonable so I do not doubt that it might happen.  If
29525 ** the close fails, we pause for 100 milliseconds and try again.  As
29526 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
29527 ** giving up and returning an error.
29528 */
29529 #define MX_CLOSE_ATTEMPT 3
29530 static int winClose(sqlite3_file *id){
29531   int rc, cnt = 0;
29532   winFile *pFile = (winFile*)id;
29533
29534   assert( id!=0 );
29535   assert( pFile->pShm==0 );
29536   OSTRACE(("CLOSE %d\n", pFile->h));
29537   do{
29538     rc = CloseHandle(pFile->h);
29539     /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
29540   }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (Sleep(100), 1) );
29541 #if SQLITE_OS_WINCE
29542 #define WINCE_DELETION_ATTEMPTS 3
29543   winceDestroyLock(pFile);
29544   if( pFile->zDeleteOnClose ){
29545     int cnt = 0;
29546     while(
29547            DeleteFileW(pFile->zDeleteOnClose)==0
29548         && GetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff 
29549         && cnt++ < WINCE_DELETION_ATTEMPTS
29550     ){
29551        Sleep(100);  /* Wait a little before trying again */
29552     }
29553     free(pFile->zDeleteOnClose);
29554   }
29555 #endif
29556   OSTRACE(("CLOSE %d %s\n", pFile->h, rc ? "ok" : "failed"));
29557   OpenCounter(-1);
29558   return rc ? SQLITE_OK : SQLITE_IOERR;
29559 }
29560
29561 /*
29562 ** Some microsoft compilers lack this definition.
29563 */
29564 #ifndef INVALID_SET_FILE_POINTER
29565 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
29566 #endif
29567
29568 /*
29569 ** Read data from a file into a buffer.  Return SQLITE_OK if all
29570 ** bytes were read successfully and SQLITE_IOERR if anything goes
29571 ** wrong.
29572 */
29573 static int winRead(
29574   sqlite3_file *id,          /* File to read from */
29575   void *pBuf,                /* Write content into this buffer */
29576   int amt,                   /* Number of bytes to read */
29577   sqlite3_int64 offset       /* Begin reading at this offset */
29578 ){
29579   LONG upperBits = (LONG)((offset>>32) & 0x7fffffff);
29580   LONG lowerBits = (LONG)(offset & 0xffffffff);
29581   DWORD rc;
29582   winFile *pFile = (winFile*)id;
29583   DWORD error;
29584   DWORD got;
29585
29586   assert( id!=0 );
29587   SimulateIOError(return SQLITE_IOERR_READ);
29588   OSTRACE(("READ %d lock=%d\n", pFile->h, pFile->locktype));
29589   rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
29590   if( rc==INVALID_SET_FILE_POINTER && (error=GetLastError())!=NO_ERROR ){
29591     pFile->lastErrno = error;
29592     return SQLITE_FULL;
29593   }
29594   if( !ReadFile(pFile->h, pBuf, amt, &got, 0) ){
29595     pFile->lastErrno = GetLastError();
29596     return SQLITE_IOERR_READ;
29597   }
29598   if( got==(DWORD)amt ){
29599     return SQLITE_OK;
29600   }else{
29601     /* Unread parts of the buffer must be zero-filled */
29602     memset(&((char*)pBuf)[got], 0, amt-got);
29603     return SQLITE_IOERR_SHORT_READ;
29604   }
29605 }
29606
29607 /*
29608 ** Write data from a buffer into a file.  Return SQLITE_OK on success
29609 ** or some other error code on failure.
29610 */
29611 static int winWrite(
29612   sqlite3_file *id,         /* File to write into */
29613   const void *pBuf,         /* The bytes to be written */
29614   int amt,                  /* Number of bytes to write */
29615   sqlite3_int64 offset      /* Offset into the file to begin writing at */
29616 ){
29617   LONG upperBits = (LONG)((offset>>32) & 0x7fffffff);
29618   LONG lowerBits = (LONG)(offset & 0xffffffff);
29619   DWORD rc;
29620   winFile *pFile = (winFile*)id;
29621   DWORD error;
29622   DWORD wrote = 0;
29623
29624   assert( id!=0 );
29625   SimulateIOError(return SQLITE_IOERR_WRITE);
29626   SimulateDiskfullError(return SQLITE_FULL);
29627   OSTRACE(("WRITE %d lock=%d\n", pFile->h, pFile->locktype));
29628   rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
29629   if( rc==INVALID_SET_FILE_POINTER && (error=GetLastError())!=NO_ERROR ){
29630     pFile->lastErrno = error;
29631     if( pFile->lastErrno==ERROR_HANDLE_DISK_FULL ){
29632       return SQLITE_FULL;
29633     }else{
29634       return SQLITE_IOERR_WRITE;
29635     }
29636   }
29637   assert( amt>0 );
29638   while(
29639      amt>0
29640      && (rc = WriteFile(pFile->h, pBuf, amt, &wrote, 0))!=0
29641      && wrote>0
29642   ){
29643     amt -= wrote;
29644     pBuf = &((char*)pBuf)[wrote];
29645   }
29646   if( !rc || amt>(int)wrote ){
29647     pFile->lastErrno = GetLastError();
29648     if( pFile->lastErrno==ERROR_HANDLE_DISK_FULL ){
29649       return SQLITE_FULL;
29650     }else{
29651       return SQLITE_IOERR_WRITE;
29652     }
29653   }
29654   return SQLITE_OK;
29655 }
29656
29657 /*
29658 ** Truncate an open file to a specified size
29659 */
29660 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
29661   LONG upperBits = (LONG)((nByte>>32) & 0x7fffffff);
29662   LONG lowerBits = (LONG)(nByte & 0xffffffff);
29663   DWORD dwRet;
29664   winFile *pFile = (winFile*)id;
29665   DWORD error;
29666   int rc = SQLITE_OK;
29667
29668   assert( id!=0 );
29669   OSTRACE(("TRUNCATE %d %lld\n", pFile->h, nByte));
29670   SimulateIOError(return SQLITE_IOERR_TRUNCATE);
29671   dwRet = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
29672   if( dwRet==INVALID_SET_FILE_POINTER && (error=GetLastError())!=NO_ERROR ){
29673     pFile->lastErrno = error;
29674     rc = SQLITE_IOERR_TRUNCATE;
29675   /* SetEndOfFile will fail if nByte is negative */
29676   }else if( !SetEndOfFile(pFile->h) ){
29677     pFile->lastErrno = GetLastError();
29678     rc = SQLITE_IOERR_TRUNCATE;
29679   }
29680   OSTRACE(("TRUNCATE %d %lld %s\n", pFile->h, nByte, rc==SQLITE_OK ? "ok" : "failed"));
29681   return rc;
29682 }
29683
29684 #ifdef SQLITE_TEST
29685 /*
29686 ** Count the number of fullsyncs and normal syncs.  This is used to test
29687 ** that syncs and fullsyncs are occuring at the right times.
29688 */
29689 SQLITE_API int sqlite3_sync_count = 0;
29690 SQLITE_API int sqlite3_fullsync_count = 0;
29691 #endif
29692
29693 /*
29694 ** Make sure all writes to a particular file are committed to disk.
29695 */
29696 static int winSync(sqlite3_file *id, int flags){
29697 #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || defined(SQLITE_DEBUG)
29698   winFile *pFile = (winFile*)id;
29699 #else
29700   UNUSED_PARAMETER(id);
29701 #endif
29702
29703   assert( pFile );
29704   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
29705   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
29706       || (flags&0x0F)==SQLITE_SYNC_FULL
29707   );
29708
29709   OSTRACE(("SYNC %d lock=%d\n", pFile->h, pFile->locktype));
29710
29711 #ifndef SQLITE_TEST
29712   UNUSED_PARAMETER(flags);
29713 #else
29714   if( flags & SQLITE_SYNC_FULL ){
29715     sqlite3_fullsync_count++;
29716   }
29717   sqlite3_sync_count++;
29718 #endif
29719
29720   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
29721   ** line is to test that doing so does not cause any problems.
29722   */
29723   SimulateDiskfullError( return SQLITE_FULL );
29724   SimulateIOError( return SQLITE_IOERR; );
29725
29726   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
29727   ** no-op
29728   */
29729 #ifdef SQLITE_NO_SYNC
29730   return SQLITE_OK;
29731 #else
29732   if( FlushFileBuffers(pFile->h) ){
29733     return SQLITE_OK;
29734   }else{
29735     pFile->lastErrno = GetLastError();
29736     return SQLITE_IOERR;
29737   }
29738 #endif
29739 }
29740
29741 /*
29742 ** Determine the current size of a file in bytes
29743 */
29744 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
29745   DWORD upperBits;
29746   DWORD lowerBits;
29747   winFile *pFile = (winFile*)id;
29748   DWORD error;
29749
29750   assert( id!=0 );
29751   SimulateIOError(return SQLITE_IOERR_FSTAT);
29752   lowerBits = GetFileSize(pFile->h, &upperBits);
29753   if(   (lowerBits == INVALID_FILE_SIZE)
29754      && ((error = GetLastError()) != NO_ERROR) )
29755   {
29756     pFile->lastErrno = error;
29757     return SQLITE_IOERR_FSTAT;
29758   }
29759   *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
29760   return SQLITE_OK;
29761 }
29762
29763 /*
29764 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
29765 */
29766 #ifndef LOCKFILE_FAIL_IMMEDIATELY
29767 # define LOCKFILE_FAIL_IMMEDIATELY 1
29768 #endif
29769
29770 /*
29771 ** Acquire a reader lock.
29772 ** Different API routines are called depending on whether or not this
29773 ** is Win95 or WinNT.
29774 */
29775 static int getReadLock(winFile *pFile){
29776   int res;
29777   if( isNT() ){
29778     OVERLAPPED ovlp;
29779     ovlp.Offset = SHARED_FIRST;
29780     ovlp.OffsetHigh = 0;
29781     ovlp.hEvent = 0;
29782     res = LockFileEx(pFile->h, LOCKFILE_FAIL_IMMEDIATELY,
29783                      0, SHARED_SIZE, 0, &ovlp);
29784 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
29785 */
29786 #if SQLITE_OS_WINCE==0
29787   }else{
29788     int lk;
29789     sqlite3_randomness(sizeof(lk), &lk);
29790     pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
29791     res = LockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
29792 #endif
29793   }
29794   if( res == 0 ){
29795     pFile->lastErrno = GetLastError();
29796   }
29797   return res;
29798 }
29799
29800 /*
29801 ** Undo a readlock
29802 */
29803 static int unlockReadLock(winFile *pFile){
29804   int res;
29805   if( isNT() ){
29806     res = UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
29807 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
29808 */
29809 #if SQLITE_OS_WINCE==0
29810   }else{
29811     res = UnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
29812 #endif
29813   }
29814   if( res == 0 ){
29815     pFile->lastErrno = GetLastError();
29816   }
29817   return res;
29818 }
29819
29820 /*
29821 ** Lock the file with the lock specified by parameter locktype - one
29822 ** of the following:
29823 **
29824 **     (1) SHARED_LOCK
29825 **     (2) RESERVED_LOCK
29826 **     (3) PENDING_LOCK
29827 **     (4) EXCLUSIVE_LOCK
29828 **
29829 ** Sometimes when requesting one lock state, additional lock states
29830 ** are inserted in between.  The locking might fail on one of the later
29831 ** transitions leaving the lock state different from what it started but
29832 ** still short of its goal.  The following chart shows the allowed
29833 ** transitions and the inserted intermediate states:
29834 **
29835 **    UNLOCKED -> SHARED
29836 **    SHARED -> RESERVED
29837 **    SHARED -> (PENDING) -> EXCLUSIVE
29838 **    RESERVED -> (PENDING) -> EXCLUSIVE
29839 **    PENDING -> EXCLUSIVE
29840 **
29841 ** This routine will only increase a lock.  The winUnlock() routine
29842 ** erases all locks at once and returns us immediately to locking level 0.
29843 ** It is not possible to lower the locking level one step at a time.  You
29844 ** must go straight to locking level 0.
29845 */
29846 static int winLock(sqlite3_file *id, int locktype){
29847   int rc = SQLITE_OK;    /* Return code from subroutines */
29848   int res = 1;           /* Result of a windows lock call */
29849   int newLocktype;       /* Set pFile->locktype to this value before exiting */
29850   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
29851   winFile *pFile = (winFile*)id;
29852   DWORD error = NO_ERROR;
29853
29854   assert( id!=0 );
29855   OSTRACE(("LOCK %d %d was %d(%d)\n",
29856            pFile->h, locktype, pFile->locktype, pFile->sharedLockByte));
29857
29858   /* If there is already a lock of this type or more restrictive on the
29859   ** OsFile, do nothing. Don't use the end_lock: exit path, as
29860   ** sqlite3OsEnterMutex() hasn't been called yet.
29861   */
29862   if( pFile->locktype>=locktype ){
29863     return SQLITE_OK;
29864   }
29865
29866   /* Make sure the locking sequence is correct
29867   */
29868   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
29869   assert( locktype!=PENDING_LOCK );
29870   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
29871
29872   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
29873   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
29874   ** the PENDING_LOCK byte is temporary.
29875   */
29876   newLocktype = pFile->locktype;
29877   if(   (pFile->locktype==NO_LOCK)
29878      || (   (locktype==EXCLUSIVE_LOCK)
29879          && (pFile->locktype==RESERVED_LOCK))
29880   ){
29881     int cnt = 3;
29882     while( cnt-->0 && (res = LockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
29883       /* Try 3 times to get the pending lock.  The pending lock might be
29884       ** held by another reader process who will release it momentarily.
29885       */
29886       OSTRACE(("could not get a PENDING lock. cnt=%d\n", cnt));
29887       Sleep(1);
29888     }
29889     gotPendingLock = res;
29890     if( !res ){
29891       error = GetLastError();
29892     }
29893   }
29894
29895   /* Acquire a shared lock
29896   */
29897   if( locktype==SHARED_LOCK && res ){
29898     assert( pFile->locktype==NO_LOCK );
29899     res = getReadLock(pFile);
29900     if( res ){
29901       newLocktype = SHARED_LOCK;
29902     }else{
29903       error = GetLastError();
29904     }
29905   }
29906
29907   /* Acquire a RESERVED lock
29908   */
29909   if( locktype==RESERVED_LOCK && res ){
29910     assert( pFile->locktype==SHARED_LOCK );
29911     res = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
29912     if( res ){
29913       newLocktype = RESERVED_LOCK;
29914     }else{
29915       error = GetLastError();
29916     }
29917   }
29918
29919   /* Acquire a PENDING lock
29920   */
29921   if( locktype==EXCLUSIVE_LOCK && res ){
29922     newLocktype = PENDING_LOCK;
29923     gotPendingLock = 0;
29924   }
29925
29926   /* Acquire an EXCLUSIVE lock
29927   */
29928   if( locktype==EXCLUSIVE_LOCK && res ){
29929     assert( pFile->locktype>=SHARED_LOCK );
29930     res = unlockReadLock(pFile);
29931     OSTRACE(("unreadlock = %d\n", res));
29932     res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
29933     if( res ){
29934       newLocktype = EXCLUSIVE_LOCK;
29935     }else{
29936       error = GetLastError();
29937       OSTRACE(("error-code = %d\n", error));
29938       getReadLock(pFile);
29939     }
29940   }
29941
29942   /* If we are holding a PENDING lock that ought to be released, then
29943   ** release it now.
29944   */
29945   if( gotPendingLock && locktype==SHARED_LOCK ){
29946     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
29947   }
29948
29949   /* Update the state of the lock has held in the file descriptor then
29950   ** return the appropriate result code.
29951   */
29952   if( res ){
29953     rc = SQLITE_OK;
29954   }else{
29955     OSTRACE(("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
29956            locktype, newLocktype));
29957     pFile->lastErrno = error;
29958     rc = SQLITE_BUSY;
29959   }
29960   pFile->locktype = (u8)newLocktype;
29961   return rc;
29962 }
29963
29964 /*
29965 ** This routine checks if there is a RESERVED lock held on the specified
29966 ** file by this or any other process. If such a lock is held, return
29967 ** non-zero, otherwise zero.
29968 */
29969 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
29970   int rc;
29971   winFile *pFile = (winFile*)id;
29972
29973   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
29974
29975   assert( id!=0 );
29976   if( pFile->locktype>=RESERVED_LOCK ){
29977     rc = 1;
29978     OSTRACE(("TEST WR-LOCK %d %d (local)\n", pFile->h, rc));
29979   }else{
29980     rc = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
29981     if( rc ){
29982       UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
29983     }
29984     rc = !rc;
29985     OSTRACE(("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc));
29986   }
29987   *pResOut = rc;
29988   return SQLITE_OK;
29989 }
29990
29991 /*
29992 ** Lower the locking level on file descriptor id to locktype.  locktype
29993 ** must be either NO_LOCK or SHARED_LOCK.
29994 **
29995 ** If the locking level of the file descriptor is already at or below
29996 ** the requested locking level, this routine is a no-op.
29997 **
29998 ** It is not possible for this routine to fail if the second argument
29999 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
30000 ** might return SQLITE_IOERR;
30001 */
30002 static int winUnlock(sqlite3_file *id, int locktype){
30003   int type;
30004   winFile *pFile = (winFile*)id;
30005   int rc = SQLITE_OK;
30006   assert( pFile!=0 );
30007   assert( locktype<=SHARED_LOCK );
30008   OSTRACE(("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
30009           pFile->locktype, pFile->sharedLockByte));
30010   type = pFile->locktype;
30011   if( type>=EXCLUSIVE_LOCK ){
30012     UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
30013     if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
30014       /* This should never happen.  We should always be able to
30015       ** reacquire the read lock */
30016       rc = SQLITE_IOERR_UNLOCK;
30017     }
30018   }
30019   if( type>=RESERVED_LOCK ){
30020     UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
30021   }
30022   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
30023     unlockReadLock(pFile);
30024   }
30025   if( type>=PENDING_LOCK ){
30026     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
30027   }
30028   pFile->locktype = (u8)locktype;
30029   return rc;
30030 }
30031
30032 /*
30033 ** Control and query of the open file handle.
30034 */
30035 static int winFileControl(sqlite3_file *id, int op, void *pArg){
30036   switch( op ){
30037     case SQLITE_FCNTL_LOCKSTATE: {
30038       *(int*)pArg = ((winFile*)id)->locktype;
30039       return SQLITE_OK;
30040     }
30041     case SQLITE_LAST_ERRNO: {
30042       *(int*)pArg = (int)((winFile*)id)->lastErrno;
30043       return SQLITE_OK;
30044     }
30045     case SQLITE_FCNTL_SIZE_HINT: {
30046       sqlite3_int64 sz = *(sqlite3_int64*)pArg;
30047       SimulateIOErrorBenign(1);
30048       winTruncate(id, sz);
30049       SimulateIOErrorBenign(0);
30050       return SQLITE_OK;
30051     }
30052   }
30053   return SQLITE_ERROR;
30054 }
30055
30056 /*
30057 ** Return the sector size in bytes of the underlying block device for
30058 ** the specified file. This is almost always 512 bytes, but may be
30059 ** larger for some devices.
30060 **
30061 ** SQLite code assumes this function cannot fail. It also assumes that
30062 ** if two files are created in the same file-system directory (i.e.
30063 ** a database and its journal file) that the sector size will be the
30064 ** same for both.
30065 */
30066 static int winSectorSize(sqlite3_file *id){
30067   assert( id!=0 );
30068   return (int)(((winFile*)id)->sectorSize);
30069 }
30070
30071 /*
30072 ** Return a vector of device characteristics.
30073 */
30074 static int winDeviceCharacteristics(sqlite3_file *id){
30075   UNUSED_PARAMETER(id);
30076   return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN;
30077 }
30078
30079 #ifndef SQLITE_OMIT_WAL
30080
30081 /*
30082 ** Helper functions to obtain and relinquish the global mutex. The
30083 ** global mutex is used to protect the winLockInfo objects used by 
30084 ** this file, all of which may be shared by multiple threads.
30085 **
30086 ** Function winShmMutexHeld() is used to assert() that the global mutex 
30087 ** is held when required. This function is only used as part of assert() 
30088 ** statements. e.g.
30089 **
30090 **   winShmEnterMutex()
30091 **     assert( winShmMutexHeld() );
30092 **   winShmLeaveMutex()
30093 */
30094 static void winShmEnterMutex(void){
30095   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
30096 }
30097 static void winShmLeaveMutex(void){
30098   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
30099 }
30100 #ifdef SQLITE_DEBUG
30101 static int winShmMutexHeld(void) {
30102   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
30103 }
30104 #endif
30105
30106 /*
30107 ** Object used to represent a single file opened and mmapped to provide
30108 ** shared memory.  When multiple threads all reference the same
30109 ** log-summary, each thread has its own winFile object, but they all
30110 ** point to a single instance of this object.  In other words, each
30111 ** log-summary is opened only once per process.
30112 **
30113 ** winShmMutexHeld() must be true when creating or destroying
30114 ** this object or while reading or writing the following fields:
30115 **
30116 **      nRef
30117 **      pNext 
30118 **
30119 ** The following fields are read-only after the object is created:
30120 ** 
30121 **      fid
30122 **      zFilename
30123 **
30124 ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
30125 ** winShmMutexHeld() is true when reading or writing any other field
30126 ** in this structure.
30127 **
30128 */
30129 struct winShmNode {
30130   sqlite3_mutex *mutex;      /* Mutex to access this object */
30131   char *zFilename;           /* Name of the file */
30132   winFile hFile;             /* File handle from winOpen */
30133
30134   int szRegion;              /* Size of shared-memory regions */
30135   int nRegion;               /* Size of array apRegion */
30136   struct ShmRegion {
30137     HANDLE hMap;             /* File handle from CreateFileMapping */
30138     void *pMap;
30139   } *aRegion;
30140   DWORD lastErrno;           /* The Windows errno from the last I/O error */
30141
30142   int nRef;                  /* Number of winShm objects pointing to this */
30143   winShm *pFirst;            /* All winShm objects pointing to this */
30144   winShmNode *pNext;         /* Next in list of all winShmNode objects */
30145 #ifdef SQLITE_DEBUG
30146   u8 nextShmId;              /* Next available winShm.id value */
30147 #endif
30148 };
30149
30150 /*
30151 ** A global array of all winShmNode objects.
30152 **
30153 ** The winShmMutexHeld() must be true while reading or writing this list.
30154 */
30155 static winShmNode *winShmNodeList = 0;
30156
30157 /*
30158 ** Structure used internally by this VFS to record the state of an
30159 ** open shared memory connection.
30160 **
30161 ** The following fields are initialized when this object is created and
30162 ** are read-only thereafter:
30163 **
30164 **    winShm.pShmNode
30165 **    winShm.id
30166 **
30167 ** All other fields are read/write.  The winShm.pShmNode->mutex must be held
30168 ** while accessing any read/write fields.
30169 */
30170 struct winShm {
30171   winShmNode *pShmNode;      /* The underlying winShmNode object */
30172   winShm *pNext;             /* Next winShm with the same winShmNode */
30173   u8 hasMutex;               /* True if holding the winShmNode mutex */
30174   u16 sharedMask;            /* Mask of shared locks held */
30175   u16 exclMask;              /* Mask of exclusive locks held */
30176 #ifdef SQLITE_DEBUG
30177   u8 id;                     /* Id of this connection with its winShmNode */
30178 #endif
30179 };
30180
30181 /*
30182 ** Constants used for locking
30183 */
30184 #define WIN_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
30185 #define WIN_SHM_DMS    (WIN_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
30186
30187 /*
30188 ** Apply advisory locks for all n bytes beginning at ofst.
30189 */
30190 #define _SHM_UNLCK  1
30191 #define _SHM_RDLCK  2
30192 #define _SHM_WRLCK  3
30193 static int winShmSystemLock(
30194   winShmNode *pFile,    /* Apply locks to this open shared-memory segment */
30195   int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
30196   int ofst,             /* Offset to first byte to be locked/unlocked */
30197   int nByte             /* Number of bytes to lock or unlock */
30198 ){
30199   OVERLAPPED ovlp;
30200   DWORD dwFlags;
30201   int rc = 0;           /* Result code form Lock/UnlockFileEx() */
30202
30203   /* Access to the winShmNode object is serialized by the caller */
30204   assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
30205
30206   /* Initialize the locking parameters */
30207   dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
30208   if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
30209
30210   memset(&ovlp, 0, sizeof(OVERLAPPED));
30211   ovlp.Offset = ofst;
30212
30213   /* Release/Acquire the system-level lock */
30214   if( lockType==_SHM_UNLCK ){
30215     rc = UnlockFileEx(pFile->hFile.h, 0, nByte, 0, &ovlp);
30216   }else{
30217     rc = LockFileEx(pFile->hFile.h, dwFlags, 0, nByte, 0, &ovlp);
30218   }
30219   
30220   if( rc!= 0 ){
30221     rc = SQLITE_OK;
30222   }else{
30223     pFile->lastErrno =  GetLastError();
30224     rc = SQLITE_BUSY;
30225   }
30226
30227   OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n", 
30228            pFile->hFile.h,
30229            rc==SQLITE_OK ? "ok" : "failed",
30230            lockType==_SHM_UNLCK ? "UnlockFileEx" : "LockFileEx",
30231            pFile->lastErrno));
30232
30233   return rc;
30234 }
30235
30236 /* Forward references to VFS methods */
30237 static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
30238 static int winDelete(sqlite3_vfs *,const char*,int);
30239
30240 /*
30241 ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
30242 **
30243 ** This is not a VFS shared-memory method; it is a utility function called
30244 ** by VFS shared-memory methods.
30245 */
30246 static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
30247   winShmNode **pp;
30248   winShmNode *p;
30249   assert( winShmMutexHeld() );
30250   pp = &winShmNodeList;
30251   while( (p = *pp)!=0 ){
30252     if( p->nRef==0 ){
30253       int i;
30254       if( p->mutex ) sqlite3_mutex_free(p->mutex);
30255       for(i=0; i<p->nRegion; i++){
30256         UnmapViewOfFile(p->aRegion[i].pMap);
30257         CloseHandle(p->aRegion[i].hMap);
30258       }
30259       if( p->hFile.h != INVALID_HANDLE_VALUE ){
30260         SimulateIOErrorBenign(1);
30261         winClose((sqlite3_file *)&p->hFile);
30262         SimulateIOErrorBenign(0);
30263       }
30264       if( deleteFlag ){
30265         SimulateIOErrorBenign(1);
30266         winDelete(pVfs, p->zFilename, 0);
30267         SimulateIOErrorBenign(0);
30268       }
30269       *pp = p->pNext;
30270       sqlite3_free(p->aRegion);
30271       sqlite3_free(p);
30272     }else{
30273       pp = &p->pNext;
30274     }
30275   }
30276 }
30277
30278 /*
30279 ** Open the shared-memory area associated with database file pDbFd.
30280 **
30281 ** When opening a new shared-memory file, if no other instances of that
30282 ** file are currently open, in this process or in other processes, then
30283 ** the file must be truncated to zero length or have its header cleared.
30284 */
30285 static int winOpenSharedMemory(winFile *pDbFd){
30286   struct winShm *p;                  /* The connection to be opened */
30287   struct winShmNode *pShmNode = 0;   /* The underlying mmapped file */
30288   int rc;                            /* Result code */
30289   struct winShmNode *pNew;           /* Newly allocated winShmNode */
30290   int nName;                         /* Size of zName in bytes */
30291
30292   assert( pDbFd->pShm==0 );    /* Not previously opened */
30293
30294   /* Allocate space for the new sqlite3_shm object.  Also speculatively
30295   ** allocate space for a new winShmNode and filename.
30296   */
30297   p = sqlite3_malloc( sizeof(*p) );
30298   if( p==0 ) return SQLITE_NOMEM;
30299   memset(p, 0, sizeof(*p));
30300   nName = sqlite3Strlen30(pDbFd->zPath);
30301   pNew = sqlite3_malloc( sizeof(*pShmNode) + nName + 15 );
30302   if( pNew==0 ){
30303     sqlite3_free(p);
30304     return SQLITE_NOMEM;
30305   }
30306   memset(pNew, 0, sizeof(*pNew));
30307   pNew->zFilename = (char*)&pNew[1];
30308   sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
30309
30310   /* Look to see if there is an existing winShmNode that can be used.
30311   ** If no matching winShmNode currently exists, create a new one.
30312   */
30313   winShmEnterMutex();
30314   for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
30315     /* TBD need to come up with better match here.  Perhaps
30316     ** use FILE_ID_BOTH_DIR_INFO Structure.
30317     */
30318     if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
30319   }
30320   if( pShmNode ){
30321     sqlite3_free(pNew);
30322   }else{
30323     pShmNode = pNew;
30324     pNew = 0;
30325     ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
30326     pShmNode->pNext = winShmNodeList;
30327     winShmNodeList = pShmNode;
30328
30329     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
30330     if( pShmNode->mutex==0 ){
30331       rc = SQLITE_NOMEM;
30332       goto shm_open_err;
30333     }
30334     rc = winOpen(pDbFd->pVfs,
30335                  pShmNode->zFilename,             /* Name of the file (UTF-8) */
30336                  (sqlite3_file*)&pShmNode->hFile,  /* File handle here */
30337                  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, /* Mode flags */
30338                  0);
30339     if( SQLITE_OK!=rc ){
30340       rc = SQLITE_CANTOPEN_BKPT;
30341       goto shm_open_err;
30342     }
30343
30344     /* Check to see if another process is holding the dead-man switch.
30345     ** If not, truncate the file to zero length. 
30346     */
30347     if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
30348       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
30349       if( rc!=SQLITE_OK ){
30350         rc = SQLITE_IOERR_SHMOPEN;
30351       }
30352     }
30353     if( rc==SQLITE_OK ){
30354       winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
30355       rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
30356     }
30357     if( rc ) goto shm_open_err;
30358   }
30359
30360   /* Make the new connection a child of the winShmNode */
30361   p->pShmNode = pShmNode;
30362 #ifdef SQLITE_DEBUG
30363   p->id = pShmNode->nextShmId++;
30364 #endif
30365   pShmNode->nRef++;
30366   pDbFd->pShm = p;
30367   winShmLeaveMutex();
30368
30369   /* The reference count on pShmNode has already been incremented under
30370   ** the cover of the winShmEnterMutex() mutex and the pointer from the
30371   ** new (struct winShm) object to the pShmNode has been set. All that is
30372   ** left to do is to link the new object into the linked list starting
30373   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex 
30374   ** mutex.
30375   */
30376   sqlite3_mutex_enter(pShmNode->mutex);
30377   p->pNext = pShmNode->pFirst;
30378   pShmNode->pFirst = p;
30379   sqlite3_mutex_leave(pShmNode->mutex);
30380   return SQLITE_OK;
30381
30382   /* Jump here on any error */
30383 shm_open_err:
30384   winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
30385   winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */
30386   sqlite3_free(p);
30387   sqlite3_free(pNew);
30388   winShmLeaveMutex();
30389   return rc;
30390 }
30391
30392 /*
30393 ** Close a connection to shared-memory.  Delete the underlying 
30394 ** storage if deleteFlag is true.
30395 */
30396 static int winShmUnmap(
30397   sqlite3_file *fd,          /* Database holding shared memory */
30398   int deleteFlag             /* Delete after closing if true */
30399 ){
30400   winFile *pDbFd;       /* Database holding shared-memory */
30401   winShm *p;            /* The connection to be closed */
30402   winShmNode *pShmNode; /* The underlying shared-memory file */
30403   winShm **pp;          /* For looping over sibling connections */
30404
30405   pDbFd = (winFile*)fd;
30406   p = pDbFd->pShm;
30407   if( p==0 ) return SQLITE_OK;
30408   pShmNode = p->pShmNode;
30409
30410   /* Remove connection p from the set of connections associated
30411   ** with pShmNode */
30412   sqlite3_mutex_enter(pShmNode->mutex);
30413   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
30414   *pp = p->pNext;
30415
30416   /* Free the connection p */
30417   sqlite3_free(p);
30418   pDbFd->pShm = 0;
30419   sqlite3_mutex_leave(pShmNode->mutex);
30420
30421   /* If pShmNode->nRef has reached 0, then close the underlying
30422   ** shared-memory file, too */
30423   winShmEnterMutex();
30424   assert( pShmNode->nRef>0 );
30425   pShmNode->nRef--;
30426   if( pShmNode->nRef==0 ){
30427     winShmPurge(pDbFd->pVfs, deleteFlag);
30428   }
30429   winShmLeaveMutex();
30430
30431   return SQLITE_OK;
30432 }
30433
30434 /*
30435 ** Change the lock state for a shared-memory segment.
30436 */
30437 static int winShmLock(
30438   sqlite3_file *fd,          /* Database file holding the shared memory */
30439   int ofst,                  /* First lock to acquire or release */
30440   int n,                     /* Number of locks to acquire or release */
30441   int flags                  /* What to do with the lock */
30442 ){
30443   winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */
30444   winShm *p = pDbFd->pShm;              /* The shared memory being locked */
30445   winShm *pX;                           /* For looping over all siblings */
30446   winShmNode *pShmNode = p->pShmNode;
30447   int rc = SQLITE_OK;                   /* Result code */
30448   u16 mask;                             /* Mask of locks to take or release */
30449
30450   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
30451   assert( n>=1 );
30452   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
30453        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
30454        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
30455        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
30456   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
30457
30458   mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
30459   assert( n>1 || mask==(1<<ofst) );
30460   sqlite3_mutex_enter(pShmNode->mutex);
30461   if( flags & SQLITE_SHM_UNLOCK ){
30462     u16 allMask = 0; /* Mask of locks held by siblings */
30463
30464     /* See if any siblings hold this same lock */
30465     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
30466       if( pX==p ) continue;
30467       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
30468       allMask |= pX->sharedMask;
30469     }
30470
30471     /* Unlock the system-level locks */
30472     if( (mask & allMask)==0 ){
30473       rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
30474     }else{
30475       rc = SQLITE_OK;
30476     }
30477
30478     /* Undo the local locks */
30479     if( rc==SQLITE_OK ){
30480       p->exclMask &= ~mask;
30481       p->sharedMask &= ~mask;
30482     } 
30483   }else if( flags & SQLITE_SHM_SHARED ){
30484     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
30485
30486     /* Find out which shared locks are already held by sibling connections.
30487     ** If any sibling already holds an exclusive lock, go ahead and return
30488     ** SQLITE_BUSY.
30489     */
30490     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
30491       if( (pX->exclMask & mask)!=0 ){
30492         rc = SQLITE_BUSY;
30493         break;
30494       }
30495       allShared |= pX->sharedMask;
30496     }
30497
30498     /* Get shared locks at the system level, if necessary */
30499     if( rc==SQLITE_OK ){
30500       if( (allShared & mask)==0 ){
30501         rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
30502       }else{
30503         rc = SQLITE_OK;
30504       }
30505     }
30506
30507     /* Get the local shared locks */
30508     if( rc==SQLITE_OK ){
30509       p->sharedMask |= mask;
30510     }
30511   }else{
30512     /* Make sure no sibling connections hold locks that will block this
30513     ** lock.  If any do, return SQLITE_BUSY right away.
30514     */
30515     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
30516       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
30517         rc = SQLITE_BUSY;
30518         break;
30519       }
30520     }
30521   
30522     /* Get the exclusive locks at the system level.  Then if successful
30523     ** also mark the local connection as being locked.
30524     */
30525     if( rc==SQLITE_OK ){
30526       rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
30527       if( rc==SQLITE_OK ){
30528         assert( (p->sharedMask & mask)==0 );
30529         p->exclMask |= mask;
30530       }
30531     }
30532   }
30533   sqlite3_mutex_leave(pShmNode->mutex);
30534   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
30535            p->id, (int)GetCurrentProcessId(), p->sharedMask, p->exclMask,
30536            rc ? "failed" : "ok"));
30537   return rc;
30538 }
30539
30540 /*
30541 ** Implement a memory barrier or memory fence on shared memory.  
30542 **
30543 ** All loads and stores begun before the barrier must complete before
30544 ** any load or store begun after the barrier.
30545 */
30546 static void winShmBarrier(
30547   sqlite3_file *fd          /* Database holding the shared memory */
30548 ){
30549   UNUSED_PARAMETER(fd);
30550   /* MemoryBarrier(); // does not work -- do not know why not */
30551   winShmEnterMutex();
30552   winShmLeaveMutex();
30553 }
30554
30555 /*
30556 ** This function is called to obtain a pointer to region iRegion of the 
30557 ** shared-memory associated with the database file fd. Shared-memory regions 
30558 ** are numbered starting from zero. Each shared-memory region is szRegion 
30559 ** bytes in size.
30560 **
30561 ** If an error occurs, an error code is returned and *pp is set to NULL.
30562 **
30563 ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
30564 ** region has not been allocated (by any client, including one running in a
30565 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If 
30566 ** isWrite is non-zero and the requested shared-memory region has not yet 
30567 ** been allocated, it is allocated by this function.
30568 **
30569 ** If the shared-memory region has already been allocated or is allocated by
30570 ** this call as described above, then it is mapped into this processes 
30571 ** address space (if it is not already), *pp is set to point to the mapped 
30572 ** memory and SQLITE_OK returned.
30573 */
30574 static int winShmMap(
30575   sqlite3_file *fd,               /* Handle open on database file */
30576   int iRegion,                    /* Region to retrieve */
30577   int szRegion,                   /* Size of regions */
30578   int isWrite,                    /* True to extend file if necessary */
30579   void volatile **pp              /* OUT: Mapped memory */
30580 ){
30581   winFile *pDbFd = (winFile*)fd;
30582   winShm *p = pDbFd->pShm;
30583   winShmNode *pShmNode;
30584   int rc = SQLITE_OK;
30585
30586   if( !p ){
30587     rc = winOpenSharedMemory(pDbFd);
30588     if( rc!=SQLITE_OK ) return rc;
30589     p = pDbFd->pShm;
30590   }
30591   pShmNode = p->pShmNode;
30592
30593   sqlite3_mutex_enter(pShmNode->mutex);
30594   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
30595
30596   if( pShmNode->nRegion<=iRegion ){
30597     struct ShmRegion *apNew;           /* New aRegion[] array */
30598     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
30599     sqlite3_int64 sz;                  /* Current size of wal-index file */
30600
30601     pShmNode->szRegion = szRegion;
30602
30603     /* The requested region is not mapped into this processes address space.
30604     ** Check to see if it has been allocated (i.e. if the wal-index file is
30605     ** large enough to contain the requested region).
30606     */
30607     rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
30608     if( rc!=SQLITE_OK ){
30609       rc = SQLITE_IOERR_SHMSIZE;
30610       goto shmpage_out;
30611     }
30612
30613     if( sz<nByte ){
30614       /* The requested memory region does not exist. If isWrite is set to
30615       ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
30616       **
30617       ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
30618       ** the requested memory region.
30619       */
30620       if( !isWrite ) goto shmpage_out;
30621       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
30622       if( rc!=SQLITE_OK ){
30623         rc = SQLITE_IOERR_SHMSIZE;
30624         goto shmpage_out;
30625       }
30626     }
30627
30628     /* Map the requested memory region into this processes address space. */
30629     apNew = (struct ShmRegion *)sqlite3_realloc(
30630         pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
30631     );
30632     if( !apNew ){
30633       rc = SQLITE_IOERR_NOMEM;
30634       goto shmpage_out;
30635     }
30636     pShmNode->aRegion = apNew;
30637
30638     while( pShmNode->nRegion<=iRegion ){
30639       HANDLE hMap;                /* file-mapping handle */
30640       void *pMap = 0;             /* Mapped memory region */
30641      
30642       hMap = CreateFileMapping(pShmNode->hFile.h, 
30643           NULL, PAGE_READWRITE, 0, nByte, NULL
30644       );
30645       if( hMap ){
30646         pMap = MapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
30647             0, 0, nByte
30648         );
30649       }
30650       if( !pMap ){
30651         pShmNode->lastErrno = GetLastError();
30652         rc = SQLITE_IOERR;
30653         if( hMap ) CloseHandle(hMap);
30654         goto shmpage_out;
30655       }
30656
30657       pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
30658       pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
30659       pShmNode->nRegion++;
30660     }
30661   }
30662
30663 shmpage_out:
30664   if( pShmNode->nRegion>iRegion ){
30665     char *p = (char *)pShmNode->aRegion[iRegion].pMap;
30666     *pp = (void *)&p[iRegion*szRegion];
30667   }else{
30668     *pp = 0;
30669   }
30670   sqlite3_mutex_leave(pShmNode->mutex);
30671   return rc;
30672 }
30673
30674 #else
30675 # define winShmMap     0
30676 # define winShmLock    0
30677 # define winShmBarrier 0
30678 # define winShmUnmap   0
30679 #endif /* #ifndef SQLITE_OMIT_WAL */
30680
30681 /*
30682 ** Here ends the implementation of all sqlite3_file methods.
30683 **
30684 ********************** End sqlite3_file Methods *******************************
30685 ******************************************************************************/
30686
30687 /*
30688 ** This vector defines all the methods that can operate on an
30689 ** sqlite3_file for win32.
30690 */
30691 static const sqlite3_io_methods winIoMethod = {
30692   2,                              /* iVersion */
30693   winClose,                       /* xClose */
30694   winRead,                        /* xRead */
30695   winWrite,                       /* xWrite */
30696   winTruncate,                    /* xTruncate */
30697   winSync,                        /* xSync */
30698   winFileSize,                    /* xFileSize */
30699   winLock,                        /* xLock */
30700   winUnlock,                      /* xUnlock */
30701   winCheckReservedLock,           /* xCheckReservedLock */
30702   winFileControl,                 /* xFileControl */
30703   winSectorSize,                  /* xSectorSize */
30704   winDeviceCharacteristics,       /* xDeviceCharacteristics */
30705   winShmMap,                      /* xShmMap */
30706   winShmLock,                     /* xShmLock */
30707   winShmBarrier,                  /* xShmBarrier */
30708   winShmUnmap                     /* xShmUnmap */
30709 };
30710
30711 /****************************************************************************
30712 **************************** sqlite3_vfs methods ****************************
30713 **
30714 ** This division contains the implementation of methods on the
30715 ** sqlite3_vfs object.
30716 */
30717
30718 /*
30719 ** Convert a UTF-8 filename into whatever form the underlying
30720 ** operating system wants filenames in.  Space to hold the result
30721 ** is obtained from malloc and must be freed by the calling
30722 ** function.
30723 */
30724 static void *convertUtf8Filename(const char *zFilename){
30725   void *zConverted = 0;
30726   if( isNT() ){
30727     zConverted = utf8ToUnicode(zFilename);
30728 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
30729 */
30730 #if SQLITE_OS_WINCE==0
30731   }else{
30732     zConverted = utf8ToMbcs(zFilename);
30733 #endif
30734   }
30735   /* caller will handle out of memory */
30736   return zConverted;
30737 }
30738
30739 /*
30740 ** Create a temporary file name in zBuf.  zBuf must be big enough to
30741 ** hold at pVfs->mxPathname characters.
30742 */
30743 static int getTempname(int nBuf, char *zBuf){
30744   static char zChars[] =
30745     "abcdefghijklmnopqrstuvwxyz"
30746     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
30747     "0123456789";
30748   size_t i, j;
30749   char zTempPath[MAX_PATH+1];
30750
30751   /* It's odd to simulate an io-error here, but really this is just
30752   ** using the io-error infrastructure to test that SQLite handles this
30753   ** function failing. 
30754   */
30755   SimulateIOError( return SQLITE_IOERR );
30756
30757   if( sqlite3_temp_directory ){
30758     sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
30759   }else if( isNT() ){
30760     char *zMulti;
30761     WCHAR zWidePath[MAX_PATH];
30762     GetTempPathW(MAX_PATH-30, zWidePath);
30763     zMulti = unicodeToUtf8(zWidePath);
30764     if( zMulti ){
30765       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
30766       free(zMulti);
30767     }else{
30768       return SQLITE_NOMEM;
30769     }
30770 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
30771 ** Since the ASCII version of these Windows API do not exist for WINCE,
30772 ** it's important to not reference them for WINCE builds.
30773 */
30774 #if SQLITE_OS_WINCE==0
30775   }else{
30776     char *zUtf8;
30777     char zMbcsPath[MAX_PATH];
30778     GetTempPathA(MAX_PATH-30, zMbcsPath);
30779     zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
30780     if( zUtf8 ){
30781       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
30782       free(zUtf8);
30783     }else{
30784       return SQLITE_NOMEM;
30785     }
30786 #endif
30787   }
30788
30789   /* Check that the output buffer is large enough for the temporary file 
30790   ** name. If it is not, return SQLITE_ERROR.
30791   */
30792   if( (sqlite3Strlen30(zTempPath) + sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX) + 17) >= nBuf ){
30793     return SQLITE_ERROR;
30794   }
30795
30796   for(i=sqlite3Strlen30(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
30797   zTempPath[i] = 0;
30798
30799   sqlite3_snprintf(nBuf-17, zBuf,
30800                    "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
30801   j = sqlite3Strlen30(zBuf);
30802   sqlite3_randomness(15, &zBuf[j]);
30803   for(i=0; i<15; i++, j++){
30804     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
30805   }
30806   zBuf[j] = 0;
30807
30808   OSTRACE(("TEMP FILENAME: %s\n", zBuf));
30809   return SQLITE_OK; 
30810 }
30811
30812 /*
30813 ** The return value of getLastErrorMsg
30814 ** is zero if the error message fits in the buffer, or non-zero
30815 ** otherwise (if the message was truncated).
30816 */
30817 static int getLastErrorMsg(int nBuf, char *zBuf){
30818   /* FormatMessage returns 0 on failure.  Otherwise it
30819   ** returns the number of TCHARs written to the output
30820   ** buffer, excluding the terminating null char.
30821   */
30822   DWORD error = GetLastError();
30823   DWORD dwLen = 0;
30824   char *zOut = 0;
30825
30826   if( isNT() ){
30827     WCHAR *zTempWide = NULL;
30828     dwLen = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
30829                            NULL,
30830                            error,
30831                            0,
30832                            (LPWSTR) &zTempWide,
30833                            0,
30834                            0);
30835     if( dwLen > 0 ){
30836       /* allocate a buffer and convert to UTF8 */
30837       zOut = unicodeToUtf8(zTempWide);
30838       /* free the system buffer allocated by FormatMessage */
30839       LocalFree(zTempWide);
30840     }
30841 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
30842 ** Since the ASCII version of these Windows API do not exist for WINCE,
30843 ** it's important to not reference them for WINCE builds.
30844 */
30845 #if SQLITE_OS_WINCE==0
30846   }else{
30847     char *zTemp = NULL;
30848     dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
30849                            NULL,
30850                            error,
30851                            0,
30852                            (LPSTR) &zTemp,
30853                            0,
30854                            0);
30855     if( dwLen > 0 ){
30856       /* allocate a buffer and convert to UTF8 */
30857       zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
30858       /* free the system buffer allocated by FormatMessage */
30859       LocalFree(zTemp);
30860     }
30861 #endif
30862   }
30863   if( 0 == dwLen ){
30864     sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error);
30865   }else{
30866     /* copy a maximum of nBuf chars to output buffer */
30867     sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
30868     /* free the UTF8 buffer */
30869     free(zOut);
30870   }
30871   return 0;
30872 }
30873
30874 /*
30875 ** Open a file.
30876 */
30877 static int winOpen(
30878   sqlite3_vfs *pVfs,        /* Not used */
30879   const char *zName,        /* Name of the file (UTF-8) */
30880   sqlite3_file *id,         /* Write the SQLite file handle here */
30881   int flags,                /* Open mode flags */
30882   int *pOutFlags            /* Status return flags */
30883 ){
30884   HANDLE h;
30885   DWORD dwDesiredAccess;
30886   DWORD dwShareMode;
30887   DWORD dwCreationDisposition;
30888   DWORD dwFlagsAndAttributes = 0;
30889 #if SQLITE_OS_WINCE
30890   int isTemp = 0;
30891 #endif
30892   winFile *pFile = (winFile*)id;
30893   void *zConverted;                 /* Filename in OS encoding */
30894   const char *zUtf8Name = zName;    /* Filename in UTF-8 encoding */
30895   char zTmpname[MAX_PATH+1];        /* Buffer used to create temp filename */
30896
30897   assert( id!=0 );
30898   UNUSED_PARAMETER(pVfs);
30899
30900   pFile->h = INVALID_HANDLE_VALUE;
30901
30902   /* If the second argument to this function is NULL, generate a 
30903   ** temporary file name to use 
30904   */
30905   if( !zUtf8Name ){
30906     int rc = getTempname(MAX_PATH+1, zTmpname);
30907     if( rc!=SQLITE_OK ){
30908       return rc;
30909     }
30910     zUtf8Name = zTmpname;
30911   }
30912
30913   /* Convert the filename to the system encoding. */
30914   zConverted = convertUtf8Filename(zUtf8Name);
30915   if( zConverted==0 ){
30916     return SQLITE_NOMEM;
30917   }
30918
30919   if( flags & SQLITE_OPEN_READWRITE ){
30920     dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
30921   }else{
30922     dwDesiredAccess = GENERIC_READ;
30923   }
30924   /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is 
30925   ** created. SQLite doesn't use it to indicate "exclusive access" 
30926   ** as it is usually understood.
30927   */
30928   assert(!(flags & SQLITE_OPEN_EXCLUSIVE) || (flags & SQLITE_OPEN_CREATE));
30929   if( flags & SQLITE_OPEN_EXCLUSIVE ){
30930     /* Creates a new file, only if it does not already exist. */
30931     /* If the file exists, it fails. */
30932     dwCreationDisposition = CREATE_NEW;
30933   }else if( flags & SQLITE_OPEN_CREATE ){
30934     /* Open existing file, or create if it doesn't exist */
30935     dwCreationDisposition = OPEN_ALWAYS;
30936   }else{
30937     /* Opens a file, only if it exists. */
30938     dwCreationDisposition = OPEN_EXISTING;
30939   }
30940   dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
30941   if( flags & SQLITE_OPEN_DELETEONCLOSE ){
30942 #if SQLITE_OS_WINCE
30943     dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
30944     isTemp = 1;
30945 #else
30946     dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
30947                                | FILE_ATTRIBUTE_HIDDEN
30948                                | FILE_FLAG_DELETE_ON_CLOSE;
30949 #endif
30950   }else{
30951     dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
30952   }
30953   /* Reports from the internet are that performance is always
30954   ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
30955 #if SQLITE_OS_WINCE
30956   dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
30957 #endif
30958   if( isNT() ){
30959     h = CreateFileW((WCHAR*)zConverted,
30960        dwDesiredAccess,
30961        dwShareMode,
30962        NULL,
30963        dwCreationDisposition,
30964        dwFlagsAndAttributes,
30965        NULL
30966     );
30967 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
30968 ** Since the ASCII version of these Windows API do not exist for WINCE,
30969 ** it's important to not reference them for WINCE builds.
30970 */
30971 #if SQLITE_OS_WINCE==0
30972   }else{
30973     h = CreateFileA((char*)zConverted,
30974        dwDesiredAccess,
30975        dwShareMode,
30976        NULL,
30977        dwCreationDisposition,
30978        dwFlagsAndAttributes,
30979        NULL
30980     );
30981 #endif
30982   }
30983   OSTRACE(("OPEN %d %s 0x%lx %s\n", 
30984            h, zName, dwDesiredAccess, 
30985            h==INVALID_HANDLE_VALUE ? "failed" : "ok"));
30986   if( h==INVALID_HANDLE_VALUE ){
30987     pFile->lastErrno = GetLastError();
30988     free(zConverted);
30989     if( flags & SQLITE_OPEN_READWRITE ){
30990       return winOpen(pVfs, zName, id, 
30991              ((flags|SQLITE_OPEN_READONLY)&~SQLITE_OPEN_READWRITE), pOutFlags);
30992     }else{
30993       return SQLITE_CANTOPEN_BKPT;
30994     }
30995   }
30996   if( pOutFlags ){
30997     if( flags & SQLITE_OPEN_READWRITE ){
30998       *pOutFlags = SQLITE_OPEN_READWRITE;
30999     }else{
31000       *pOutFlags = SQLITE_OPEN_READONLY;
31001     }
31002   }
31003   memset(pFile, 0, sizeof(*pFile));
31004   pFile->pMethod = &winIoMethod;
31005   pFile->h = h;
31006   pFile->lastErrno = NO_ERROR;
31007   pFile->pVfs = pVfs;
31008   pFile->pShm = 0;
31009   pFile->zPath = zName;
31010   pFile->sectorSize = getSectorSize(pVfs, zUtf8Name);
31011 #if SQLITE_OS_WINCE
31012   if( (flags & (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)) ==
31013                (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)
31014        && !winceCreateLock(zName, pFile)
31015   ){
31016     CloseHandle(h);
31017     free(zConverted);
31018     return SQLITE_CANTOPEN_BKPT;
31019   }
31020   if( isTemp ){
31021     pFile->zDeleteOnClose = zConverted;
31022   }else
31023 #endif
31024   {
31025     free(zConverted);
31026   }
31027   OpenCounter(+1);
31028   return SQLITE_OK;
31029 }
31030
31031 /*
31032 ** Delete the named file.
31033 **
31034 ** Note that windows does not allow a file to be deleted if some other
31035 ** process has it open.  Sometimes a virus scanner or indexing program
31036 ** will open a journal file shortly after it is created in order to do
31037 ** whatever it does.  While this other process is holding the
31038 ** file open, we will be unable to delete it.  To work around this
31039 ** problem, we delay 100 milliseconds and try to delete again.  Up
31040 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
31041 ** up and returning an error.
31042 */
31043 #define MX_DELETION_ATTEMPTS 5
31044 static int winDelete(
31045   sqlite3_vfs *pVfs,          /* Not used on win32 */
31046   const char *zFilename,      /* Name of file to delete */
31047   int syncDir                 /* Not used on win32 */
31048 ){
31049   int cnt = 0;
31050   DWORD rc;
31051   DWORD error = 0;
31052   void *zConverted;
31053   UNUSED_PARAMETER(pVfs);
31054   UNUSED_PARAMETER(syncDir);
31055
31056   SimulateIOError(return SQLITE_IOERR_DELETE);
31057   zConverted = convertUtf8Filename(zFilename);
31058   if( zConverted==0 ){
31059     return SQLITE_NOMEM;
31060   }
31061   if( isNT() ){
31062     do{
31063       DeleteFileW(zConverted);
31064     }while(   (   ((rc = GetFileAttributesW(zConverted)) != INVALID_FILE_ATTRIBUTES)
31065                || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
31066            && (++cnt < MX_DELETION_ATTEMPTS)
31067            && (Sleep(100), 1) );
31068 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
31069 ** Since the ASCII version of these Windows API do not exist for WINCE,
31070 ** it's important to not reference them for WINCE builds.
31071 */
31072 #if SQLITE_OS_WINCE==0
31073   }else{
31074     do{
31075       DeleteFileA(zConverted);
31076     }while(   (   ((rc = GetFileAttributesA(zConverted)) != INVALID_FILE_ATTRIBUTES)
31077                || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
31078            && (++cnt < MX_DELETION_ATTEMPTS)
31079            && (Sleep(100), 1) );
31080 #endif
31081   }
31082   free(zConverted);
31083   OSTRACE(("DELETE \"%s\" %s\n", zFilename,
31084        ( (rc==INVALID_FILE_ATTRIBUTES) && (error==ERROR_FILE_NOT_FOUND)) ?
31085          "ok" : "failed" ));
31086  
31087   return (   (rc == INVALID_FILE_ATTRIBUTES) 
31088           && (error == ERROR_FILE_NOT_FOUND)) ? SQLITE_OK : SQLITE_IOERR_DELETE;
31089 }
31090
31091 /*
31092 ** Check the existance and status of a file.
31093 */
31094 static int winAccess(
31095   sqlite3_vfs *pVfs,         /* Not used on win32 */
31096   const char *zFilename,     /* Name of file to check */
31097   int flags,                 /* Type of test to make on this file */
31098   int *pResOut               /* OUT: Result */
31099 ){
31100   DWORD attr;
31101   int rc = 0;
31102   void *zConverted;
31103   UNUSED_PARAMETER(pVfs);
31104
31105   SimulateIOError( return SQLITE_IOERR_ACCESS; );
31106   zConverted = convertUtf8Filename(zFilename);
31107   if( zConverted==0 ){
31108     return SQLITE_NOMEM;
31109   }
31110   if( isNT() ){
31111     WIN32_FILE_ATTRIBUTE_DATA sAttrData;
31112     memset(&sAttrData, 0, sizeof(sAttrData));
31113     if( GetFileAttributesExW((WCHAR*)zConverted,
31114                              GetFileExInfoStandard, 
31115                              &sAttrData) ){
31116       /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
31117       ** as if it does not exist.
31118       */
31119       if(    flags==SQLITE_ACCESS_EXISTS
31120           && sAttrData.nFileSizeHigh==0 
31121           && sAttrData.nFileSizeLow==0 ){
31122         attr = INVALID_FILE_ATTRIBUTES;
31123       }else{
31124         attr = sAttrData.dwFileAttributes;
31125       }
31126     }else{
31127       if( GetLastError()!=ERROR_FILE_NOT_FOUND ){
31128         free(zConverted);
31129         return SQLITE_IOERR_ACCESS;
31130       }else{
31131         attr = INVALID_FILE_ATTRIBUTES;
31132       }
31133     }
31134 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
31135 ** Since the ASCII version of these Windows API do not exist for WINCE,
31136 ** it's important to not reference them for WINCE builds.
31137 */
31138 #if SQLITE_OS_WINCE==0
31139   }else{
31140     attr = GetFileAttributesA((char*)zConverted);
31141 #endif
31142   }
31143   free(zConverted);
31144   switch( flags ){
31145     case SQLITE_ACCESS_READ:
31146     case SQLITE_ACCESS_EXISTS:
31147       rc = attr!=INVALID_FILE_ATTRIBUTES;
31148       break;
31149     case SQLITE_ACCESS_READWRITE:
31150       rc = (attr & FILE_ATTRIBUTE_READONLY)==0;
31151       break;
31152     default:
31153       assert(!"Invalid flags argument");
31154   }
31155   *pResOut = rc;
31156   return SQLITE_OK;
31157 }
31158
31159
31160 /*
31161 ** Turn a relative pathname into a full pathname.  Write the full
31162 ** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
31163 ** bytes in size.
31164 */
31165 static int winFullPathname(
31166   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
31167   const char *zRelative,        /* Possibly relative input path */
31168   int nFull,                    /* Size of output buffer in bytes */
31169   char *zFull                   /* Output buffer */
31170 ){
31171   
31172 #if defined(__CYGWIN__)
31173   SimulateIOError( return SQLITE_ERROR );
31174   UNUSED_PARAMETER(nFull);
31175   cygwin_conv_to_full_win32_path(zRelative, zFull);
31176   return SQLITE_OK;
31177 #endif
31178
31179 #if SQLITE_OS_WINCE
31180   SimulateIOError( return SQLITE_ERROR );
31181   UNUSED_PARAMETER(nFull);
31182   /* WinCE has no concept of a relative pathname, or so I am told. */
31183   sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zRelative);
31184   return SQLITE_OK;
31185 #endif
31186
31187 #if !SQLITE_OS_WINCE && !defined(__CYGWIN__)
31188   int nByte;
31189   void *zConverted;
31190   char *zOut;
31191
31192   /* It's odd to simulate an io-error here, but really this is just
31193   ** using the io-error infrastructure to test that SQLite handles this
31194   ** function failing. This function could fail if, for example, the
31195   ** current working directory has been unlinked.
31196   */
31197   SimulateIOError( return SQLITE_ERROR );
31198   UNUSED_PARAMETER(nFull);
31199   zConverted = convertUtf8Filename(zRelative);
31200   if( isNT() ){
31201     WCHAR *zTemp;
31202     nByte = GetFullPathNameW((WCHAR*)zConverted, 0, 0, 0) + 3;
31203     zTemp = malloc( nByte*sizeof(zTemp[0]) );
31204     if( zTemp==0 ){
31205       free(zConverted);
31206       return SQLITE_NOMEM;
31207     }
31208     GetFullPathNameW((WCHAR*)zConverted, nByte, zTemp, 0);
31209     free(zConverted);
31210     zOut = unicodeToUtf8(zTemp);
31211     free(zTemp);
31212 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
31213 ** Since the ASCII version of these Windows API do not exist for WINCE,
31214 ** it's important to not reference them for WINCE builds.
31215 */
31216 #if SQLITE_OS_WINCE==0
31217   }else{
31218     char *zTemp;
31219     nByte = GetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
31220     zTemp = malloc( nByte*sizeof(zTemp[0]) );
31221     if( zTemp==0 ){
31222       free(zConverted);
31223       return SQLITE_NOMEM;
31224     }
31225     GetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
31226     free(zConverted);
31227     zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
31228     free(zTemp);
31229 #endif
31230   }
31231   if( zOut ){
31232     sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zOut);
31233     free(zOut);
31234     return SQLITE_OK;
31235   }else{
31236     return SQLITE_NOMEM;
31237   }
31238 #endif
31239 }
31240
31241 /*
31242 ** Get the sector size of the device used to store
31243 ** file.
31244 */
31245 static int getSectorSize(
31246     sqlite3_vfs *pVfs,
31247     const char *zRelative     /* UTF-8 file name */
31248 ){
31249   DWORD bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
31250   /* GetDiskFreeSpace is not supported under WINCE */
31251 #if SQLITE_OS_WINCE
31252   UNUSED_PARAMETER(pVfs);
31253   UNUSED_PARAMETER(zRelative);
31254 #else
31255   char zFullpath[MAX_PATH+1];
31256   int rc;
31257   DWORD dwRet = 0;
31258   DWORD dwDummy;
31259
31260   /*
31261   ** We need to get the full path name of the file
31262   ** to get the drive letter to look up the sector
31263   ** size.
31264   */
31265   SimulateIOErrorBenign(1);
31266   rc = winFullPathname(pVfs, zRelative, MAX_PATH, zFullpath);
31267   SimulateIOErrorBenign(0);
31268   if( rc == SQLITE_OK )
31269   {
31270     void *zConverted = convertUtf8Filename(zFullpath);
31271     if( zConverted ){
31272       if( isNT() ){
31273         /* trim path to just drive reference */
31274         WCHAR *p = zConverted;
31275         for(;*p;p++){
31276           if( *p == '\\' ){
31277             *p = '\0';
31278             break;
31279           }
31280         }
31281         dwRet = GetDiskFreeSpaceW((WCHAR*)zConverted,
31282                                   &dwDummy,
31283                                   &bytesPerSector,
31284                                   &dwDummy,
31285                                   &dwDummy);
31286       }else{
31287         /* trim path to just drive reference */
31288         char *p = (char *)zConverted;
31289         for(;*p;p++){
31290           if( *p == '\\' ){
31291             *p = '\0';
31292             break;
31293           }
31294         }
31295         dwRet = GetDiskFreeSpaceA((char*)zConverted,
31296                                   &dwDummy,
31297                                   &bytesPerSector,
31298                                   &dwDummy,
31299                                   &dwDummy);
31300       }
31301       free(zConverted);
31302     }
31303     if( !dwRet ){
31304       bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
31305     }
31306   }
31307 #endif
31308   return (int) bytesPerSector; 
31309 }
31310
31311 #ifndef SQLITE_OMIT_LOAD_EXTENSION
31312 /*
31313 ** Interfaces for opening a shared library, finding entry points
31314 ** within the shared library, and closing the shared library.
31315 */
31316 /*
31317 ** Interfaces for opening a shared library, finding entry points
31318 ** within the shared library, and closing the shared library.
31319 */
31320 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
31321   HANDLE h;
31322   void *zConverted = convertUtf8Filename(zFilename);
31323   UNUSED_PARAMETER(pVfs);
31324   if( zConverted==0 ){
31325     return 0;
31326   }
31327   if( isNT() ){
31328     h = LoadLibraryW((WCHAR*)zConverted);
31329 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
31330 ** Since the ASCII version of these Windows API do not exist for WINCE,
31331 ** it's important to not reference them for WINCE builds.
31332 */
31333 #if SQLITE_OS_WINCE==0
31334   }else{
31335     h = LoadLibraryA((char*)zConverted);
31336 #endif
31337   }
31338   free(zConverted);
31339   return (void*)h;
31340 }
31341 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
31342   UNUSED_PARAMETER(pVfs);
31343   getLastErrorMsg(nBuf, zBufOut);
31344 }
31345 void (*winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
31346   UNUSED_PARAMETER(pVfs);
31347 #if SQLITE_OS_WINCE
31348   /* The GetProcAddressA() routine is only available on wince. */
31349   return (void(*)(void))GetProcAddressA((HANDLE)pHandle, zSymbol);
31350 #else
31351   /* All other windows platforms expect GetProcAddress() to take
31352   ** an Ansi string regardless of the _UNICODE setting */
31353   return (void(*)(void))GetProcAddress((HANDLE)pHandle, zSymbol);
31354 #endif
31355 }
31356 void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
31357   UNUSED_PARAMETER(pVfs);
31358   FreeLibrary((HANDLE)pHandle);
31359 }
31360 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
31361   #define winDlOpen  0
31362   #define winDlError 0
31363   #define winDlSym   0
31364   #define winDlClose 0
31365 #endif
31366
31367
31368 /*
31369 ** Write up to nBuf bytes of randomness into zBuf.
31370 */
31371 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
31372   int n = 0;
31373   UNUSED_PARAMETER(pVfs);
31374 #if defined(SQLITE_TEST)
31375   n = nBuf;
31376   memset(zBuf, 0, nBuf);
31377 #else
31378   if( sizeof(SYSTEMTIME)<=nBuf-n ){
31379     SYSTEMTIME x;
31380     GetSystemTime(&x);
31381     memcpy(&zBuf[n], &x, sizeof(x));
31382     n += sizeof(x);
31383   }
31384   if( sizeof(DWORD)<=nBuf-n ){
31385     DWORD pid = GetCurrentProcessId();
31386     memcpy(&zBuf[n], &pid, sizeof(pid));
31387     n += sizeof(pid);
31388   }
31389   if( sizeof(DWORD)<=nBuf-n ){
31390     DWORD cnt = GetTickCount();
31391     memcpy(&zBuf[n], &cnt, sizeof(cnt));
31392     n += sizeof(cnt);
31393   }
31394   if( sizeof(LARGE_INTEGER)<=nBuf-n ){
31395     LARGE_INTEGER i;
31396     QueryPerformanceCounter(&i);
31397     memcpy(&zBuf[n], &i, sizeof(i));
31398     n += sizeof(i);
31399   }
31400 #endif
31401   return n;
31402 }
31403
31404
31405 /*
31406 ** Sleep for a little while.  Return the amount of time slept.
31407 */
31408 static int winSleep(sqlite3_vfs *pVfs, int microsec){
31409   Sleep((microsec+999)/1000);
31410   UNUSED_PARAMETER(pVfs);
31411   return ((microsec+999)/1000)*1000;
31412 }
31413
31414 /*
31415 ** The following variable, if set to a non-zero value, is interpreted as
31416 ** the number of seconds since 1970 and is used to set the result of
31417 ** sqlite3OsCurrentTime() during testing.
31418 */
31419 #ifdef SQLITE_TEST
31420 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
31421 #endif
31422
31423 /*
31424 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
31425 ** the current time and date as a Julian Day number times 86_400_000.  In
31426 ** other words, write into *piNow the number of milliseconds since the Julian
31427 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
31428 ** proleptic Gregorian calendar.
31429 **
31430 ** On success, return 0.  Return 1 if the time and date cannot be found.
31431 */
31432 static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
31433   /* FILETIME structure is a 64-bit value representing the number of 
31434      100-nanosecond intervals since January 1, 1601 (= JD 2305813.5). 
31435   */
31436   FILETIME ft;
31437   static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
31438 #ifdef SQLITE_TEST
31439   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
31440 #endif
31441   /* 2^32 - to avoid use of LL and warnings in gcc */
31442   static const sqlite3_int64 max32BitValue = 
31443       (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + (sqlite3_int64)294967296;
31444
31445 #if SQLITE_OS_WINCE
31446   SYSTEMTIME time;
31447   GetSystemTime(&time);
31448   /* if SystemTimeToFileTime() fails, it returns zero. */
31449   if (!SystemTimeToFileTime(&time,&ft)){
31450     return 1;
31451   }
31452 #else
31453   GetSystemTimeAsFileTime( &ft );
31454 #endif
31455
31456   *piNow = winFiletimeEpoch +
31457             ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) + 
31458                (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
31459
31460 #ifdef SQLITE_TEST
31461   if( sqlite3_current_time ){
31462     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
31463   }
31464 #endif
31465   UNUSED_PARAMETER(pVfs);
31466   return 0;
31467 }
31468
31469 /*
31470 ** Find the current time (in Universal Coordinated Time).  Write the
31471 ** current time and date as a Julian Day number into *prNow and
31472 ** return 0.  Return 1 if the time and date cannot be found.
31473 */
31474 int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
31475   int rc;
31476   sqlite3_int64 i;
31477   rc = winCurrentTimeInt64(pVfs, &i);
31478   if( !rc ){
31479     *prNow = i/86400000.0;
31480   }
31481   return rc;
31482 }
31483
31484 /*
31485 ** The idea is that this function works like a combination of
31486 ** GetLastError() and FormatMessage() on windows (or errno and
31487 ** strerror_r() on unix). After an error is returned by an OS
31488 ** function, SQLite calls this function with zBuf pointing to
31489 ** a buffer of nBuf bytes. The OS layer should populate the
31490 ** buffer with a nul-terminated UTF-8 encoded error message
31491 ** describing the last IO error to have occurred within the calling
31492 ** thread.
31493 **
31494 ** If the error message is too large for the supplied buffer,
31495 ** it should be truncated. The return value of xGetLastError
31496 ** is zero if the error message fits in the buffer, or non-zero
31497 ** otherwise (if the message was truncated). If non-zero is returned,
31498 ** then it is not necessary to include the nul-terminator character
31499 ** in the output buffer.
31500 **
31501 ** Not supplying an error message will have no adverse effect
31502 ** on SQLite. It is fine to have an implementation that never
31503 ** returns an error message:
31504 **
31505 **   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
31506 **     assert(zBuf[0]=='\0');
31507 **     return 0;
31508 **   }
31509 **
31510 ** However if an error message is supplied, it will be incorporated
31511 ** by sqlite into the error message available to the user using
31512 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
31513 */
31514 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
31515   UNUSED_PARAMETER(pVfs);
31516   return getLastErrorMsg(nBuf, zBuf);
31517 }
31518
31519
31520
31521 /*
31522 ** Initialize and deinitialize the operating system interface.
31523 */
31524 SQLITE_API int sqlite3_os_init(void){
31525   static sqlite3_vfs winVfs = {
31526     2,                   /* iVersion */
31527     sizeof(winFile),     /* szOsFile */
31528     MAX_PATH,            /* mxPathname */
31529     0,                   /* pNext */
31530     "win32",             /* zName */
31531     0,                   /* pAppData */
31532     winOpen,             /* xOpen */
31533     winDelete,           /* xDelete */
31534     winAccess,           /* xAccess */
31535     winFullPathname,     /* xFullPathname */
31536     winDlOpen,           /* xDlOpen */
31537     winDlError,          /* xDlError */
31538     winDlSym,            /* xDlSym */
31539     winDlClose,          /* xDlClose */
31540     winRandomness,       /* xRandomness */
31541     winSleep,            /* xSleep */
31542     winCurrentTime,      /* xCurrentTime */
31543     winGetLastError,     /* xGetLastError */
31544     winCurrentTimeInt64, /* xCurrentTimeInt64 */
31545   };
31546
31547   sqlite3_vfs_register(&winVfs, 1);
31548   return SQLITE_OK; 
31549 }
31550 SQLITE_API int sqlite3_os_end(void){ 
31551   return SQLITE_OK;
31552 }
31553
31554 #endif /* SQLITE_OS_WIN */
31555
31556 /************** End of os_win.c **********************************************/
31557 /************** Begin file bitvec.c ******************************************/
31558 /*
31559 ** 2008 February 16
31560 **
31561 ** The author disclaims copyright to this source code.  In place of
31562 ** a legal notice, here is a blessing:
31563 **
31564 **    May you do good and not evil.
31565 **    May you find forgiveness for yourself and forgive others.
31566 **    May you share freely, never taking more than you give.
31567 **
31568 *************************************************************************
31569 ** This file implements an object that represents a fixed-length
31570 ** bitmap.  Bits are numbered starting with 1.
31571 **
31572 ** A bitmap is used to record which pages of a database file have been
31573 ** journalled during a transaction, or which pages have the "dont-write"
31574 ** property.  Usually only a few pages are meet either condition.
31575 ** So the bitmap is usually sparse and has low cardinality.
31576 ** But sometimes (for example when during a DROP of a large table) most
31577 ** or all of the pages in a database can get journalled.  In those cases, 
31578 ** the bitmap becomes dense with high cardinality.  The algorithm needs 
31579 ** to handle both cases well.
31580 **
31581 ** The size of the bitmap is fixed when the object is created.
31582 **
31583 ** All bits are clear when the bitmap is created.  Individual bits
31584 ** may be set or cleared one at a time.
31585 **
31586 ** Test operations are about 100 times more common that set operations.
31587 ** Clear operations are exceedingly rare.  There are usually between
31588 ** 5 and 500 set operations per Bitvec object, though the number of sets can
31589 ** sometimes grow into tens of thousands or larger.  The size of the
31590 ** Bitvec object is the number of pages in the database file at the
31591 ** start of a transaction, and is thus usually less than a few thousand,
31592 ** but can be as large as 2 billion for a really big database.
31593 */
31594
31595 /* Size of the Bitvec structure in bytes. */
31596 #define BITVEC_SZ        (sizeof(void*)*128)  /* 512 on 32bit.  1024 on 64bit */
31597
31598 /* Round the union size down to the nearest pointer boundary, since that's how 
31599 ** it will be aligned within the Bitvec struct. */
31600 #define BITVEC_USIZE     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
31601
31602 /* Type of the array "element" for the bitmap representation. 
31603 ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE. 
31604 ** Setting this to the "natural word" size of your CPU may improve
31605 ** performance. */
31606 #define BITVEC_TELEM     u8
31607 /* Size, in bits, of the bitmap element. */
31608 #define BITVEC_SZELEM    8
31609 /* Number of elements in a bitmap array. */
31610 #define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
31611 /* Number of bits in the bitmap array. */
31612 #define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
31613
31614 /* Number of u32 values in hash table. */
31615 #define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
31616 /* Maximum number of entries in hash table before 
31617 ** sub-dividing and re-hashing. */
31618 #define BITVEC_MXHASH    (BITVEC_NINT/2)
31619 /* Hashing function for the aHash representation.
31620 ** Empirical testing showed that the *37 multiplier 
31621 ** (an arbitrary prime)in the hash function provided 
31622 ** no fewer collisions than the no-op *1. */
31623 #define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
31624
31625 #define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
31626
31627
31628 /*
31629 ** A bitmap is an instance of the following structure.
31630 **
31631 ** This bitmap records the existance of zero or more bits
31632 ** with values between 1 and iSize, inclusive.
31633 **
31634 ** There are three possible representations of the bitmap.
31635 ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
31636 ** bitmap.  The least significant bit is bit 1.
31637 **
31638 ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
31639 ** a hash table that will hold up to BITVEC_MXHASH distinct values.
31640 **
31641 ** Otherwise, the value i is redirected into one of BITVEC_NPTR
31642 ** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
31643 ** handles up to iDivisor separate values of i.  apSub[0] holds
31644 ** values between 1 and iDivisor.  apSub[1] holds values between
31645 ** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
31646 ** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
31647 ** to hold deal with values between 1 and iDivisor.
31648 */
31649 struct Bitvec {
31650   u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
31651   u32 nSet;       /* Number of bits that are set - only valid for aHash
31652                   ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
31653                   ** this would be 125. */
31654   u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
31655                   /* Should >=0 for apSub element. */
31656                   /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
31657                   /* For a BITVEC_SZ of 512, this would be 34,359,739. */
31658   union {
31659     BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
31660     u32 aHash[BITVEC_NINT];      /* Hash table representation */
31661     Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
31662   } u;
31663 };
31664
31665 /*
31666 ** Create a new bitmap object able to handle bits between 0 and iSize,
31667 ** inclusive.  Return a pointer to the new object.  Return NULL if 
31668 ** malloc fails.
31669 */
31670 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
31671   Bitvec *p;
31672   assert( sizeof(*p)==BITVEC_SZ );
31673   p = sqlite3MallocZero( sizeof(*p) );
31674   if( p ){
31675     p->iSize = iSize;
31676   }
31677   return p;
31678 }
31679
31680 /*
31681 ** Check to see if the i-th bit is set.  Return true or false.
31682 ** If p is NULL (if the bitmap has not been created) or if
31683 ** i is out of range, then return false.
31684 */
31685 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
31686   if( p==0 ) return 0;
31687   if( i>p->iSize || i==0 ) return 0;
31688   i--;
31689   while( p->iDivisor ){
31690     u32 bin = i/p->iDivisor;
31691     i = i%p->iDivisor;
31692     p = p->u.apSub[bin];
31693     if (!p) {
31694       return 0;
31695     }
31696   }
31697   if( p->iSize<=BITVEC_NBIT ){
31698     return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
31699   } else{
31700     u32 h = BITVEC_HASH(i++);
31701     while( p->u.aHash[h] ){
31702       if( p->u.aHash[h]==i ) return 1;
31703       h = (h+1) % BITVEC_NINT;
31704     }
31705     return 0;
31706   }
31707 }
31708
31709 /*
31710 ** Set the i-th bit.  Return 0 on success and an error code if
31711 ** anything goes wrong.
31712 **
31713 ** This routine might cause sub-bitmaps to be allocated.  Failing
31714 ** to get the memory needed to hold the sub-bitmap is the only
31715 ** that can go wrong with an insert, assuming p and i are valid.
31716 **
31717 ** The calling function must ensure that p is a valid Bitvec object
31718 ** and that the value for "i" is within range of the Bitvec object.
31719 ** Otherwise the behavior is undefined.
31720 */
31721 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
31722   u32 h;
31723   if( p==0 ) return SQLITE_OK;
31724   assert( i>0 );
31725   assert( i<=p->iSize );
31726   i--;
31727   while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
31728     u32 bin = i/p->iDivisor;
31729     i = i%p->iDivisor;
31730     if( p->u.apSub[bin]==0 ){
31731       p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
31732       if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
31733     }
31734     p = p->u.apSub[bin];
31735   }
31736   if( p->iSize<=BITVEC_NBIT ){
31737     p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
31738     return SQLITE_OK;
31739   }
31740   h = BITVEC_HASH(i++);
31741   /* if there wasn't a hash collision, and this doesn't */
31742   /* completely fill the hash, then just add it without */
31743   /* worring about sub-dividing and re-hashing. */
31744   if( !p->u.aHash[h] ){
31745     if (p->nSet<(BITVEC_NINT-1)) {
31746       goto bitvec_set_end;
31747     } else {
31748       goto bitvec_set_rehash;
31749     }
31750   }
31751   /* there was a collision, check to see if it's already */
31752   /* in hash, if not, try to find a spot for it */
31753   do {
31754     if( p->u.aHash[h]==i ) return SQLITE_OK;
31755     h++;
31756     if( h>=BITVEC_NINT ) h = 0;
31757   } while( p->u.aHash[h] );
31758   /* we didn't find it in the hash.  h points to the first */
31759   /* available free spot. check to see if this is going to */
31760   /* make our hash too "full".  */
31761 bitvec_set_rehash:
31762   if( p->nSet>=BITVEC_MXHASH ){
31763     unsigned int j;
31764     int rc;
31765     u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
31766     if( aiValues==0 ){
31767       return SQLITE_NOMEM;
31768     }else{
31769       memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
31770       memset(p->u.apSub, 0, sizeof(p->u.apSub));
31771       p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
31772       rc = sqlite3BitvecSet(p, i);
31773       for(j=0; j<BITVEC_NINT; j++){
31774         if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
31775       }
31776       sqlite3StackFree(0, aiValues);
31777       return rc;
31778     }
31779   }
31780 bitvec_set_end:
31781   p->nSet++;
31782   p->u.aHash[h] = i;
31783   return SQLITE_OK;
31784 }
31785
31786 /*
31787 ** Clear the i-th bit.
31788 **
31789 ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
31790 ** that BitvecClear can use to rebuilt its hash table.
31791 */
31792 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
31793   if( p==0 ) return;
31794   assert( i>0 );
31795   i--;
31796   while( p->iDivisor ){
31797     u32 bin = i/p->iDivisor;
31798     i = i%p->iDivisor;
31799     p = p->u.apSub[bin];
31800     if (!p) {
31801       return;
31802     }
31803   }
31804   if( p->iSize<=BITVEC_NBIT ){
31805     p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
31806   }else{
31807     unsigned int j;
31808     u32 *aiValues = pBuf;
31809     memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
31810     memset(p->u.aHash, 0, sizeof(p->u.aHash));
31811     p->nSet = 0;
31812     for(j=0; j<BITVEC_NINT; j++){
31813       if( aiValues[j] && aiValues[j]!=(i+1) ){
31814         u32 h = BITVEC_HASH(aiValues[j]-1);
31815         p->nSet++;
31816         while( p->u.aHash[h] ){
31817           h++;
31818           if( h>=BITVEC_NINT ) h = 0;
31819         }
31820         p->u.aHash[h] = aiValues[j];
31821       }
31822     }
31823   }
31824 }
31825
31826 /*
31827 ** Destroy a bitmap object.  Reclaim all memory used.
31828 */
31829 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
31830   if( p==0 ) return;
31831   if( p->iDivisor ){
31832     unsigned int i;
31833     for(i=0; i<BITVEC_NPTR; i++){
31834       sqlite3BitvecDestroy(p->u.apSub[i]);
31835     }
31836   }
31837   sqlite3_free(p);
31838 }
31839
31840 /*
31841 ** Return the value of the iSize parameter specified when Bitvec *p
31842 ** was created.
31843 */
31844 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
31845   return p->iSize;
31846 }
31847
31848 #ifndef SQLITE_OMIT_BUILTIN_TEST
31849 /*
31850 ** Let V[] be an array of unsigned characters sufficient to hold
31851 ** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
31852 ** Then the following macros can be used to set, clear, or test
31853 ** individual bits within V.
31854 */
31855 #define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
31856 #define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
31857 #define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
31858
31859 /*
31860 ** This routine runs an extensive test of the Bitvec code.
31861 **
31862 ** The input is an array of integers that acts as a program
31863 ** to test the Bitvec.  The integers are opcodes followed
31864 ** by 0, 1, or 3 operands, depending on the opcode.  Another
31865 ** opcode follows immediately after the last operand.
31866 **
31867 ** There are 6 opcodes numbered from 0 through 5.  0 is the
31868 ** "halt" opcode and causes the test to end.
31869 **
31870 **    0          Halt and return the number of errors
31871 **    1 N S X    Set N bits beginning with S and incrementing by X
31872 **    2 N S X    Clear N bits beginning with S and incrementing by X
31873 **    3 N        Set N randomly chosen bits
31874 **    4 N        Clear N randomly chosen bits
31875 **    5 N S X    Set N bits from S increment X in array only, not in bitvec
31876 **
31877 ** The opcodes 1 through 4 perform set and clear operations are performed
31878 ** on both a Bitvec object and on a linear array of bits obtained from malloc.
31879 ** Opcode 5 works on the linear array only, not on the Bitvec.
31880 ** Opcode 5 is used to deliberately induce a fault in order to
31881 ** confirm that error detection works.
31882 **
31883 ** At the conclusion of the test the linear array is compared
31884 ** against the Bitvec object.  If there are any differences,
31885 ** an error is returned.  If they are the same, zero is returned.
31886 **
31887 ** If a memory allocation error occurs, return -1.
31888 */
31889 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
31890   Bitvec *pBitvec = 0;
31891   unsigned char *pV = 0;
31892   int rc = -1;
31893   int i, nx, pc, op;
31894   void *pTmpSpace;
31895
31896   /* Allocate the Bitvec to be tested and a linear array of
31897   ** bits to act as the reference */
31898   pBitvec = sqlite3BitvecCreate( sz );
31899   pV = sqlite3_malloc( (sz+7)/8 + 1 );
31900   pTmpSpace = sqlite3_malloc(BITVEC_SZ);
31901   if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
31902   memset(pV, 0, (sz+7)/8 + 1);
31903
31904   /* NULL pBitvec tests */
31905   sqlite3BitvecSet(0, 1);
31906   sqlite3BitvecClear(0, 1, pTmpSpace);
31907
31908   /* Run the program */
31909   pc = 0;
31910   while( (op = aOp[pc])!=0 ){
31911     switch( op ){
31912       case 1:
31913       case 2:
31914       case 5: {
31915         nx = 4;
31916         i = aOp[pc+2] - 1;
31917         aOp[pc+2] += aOp[pc+3];
31918         break;
31919       }
31920       case 3:
31921       case 4: 
31922       default: {
31923         nx = 2;
31924         sqlite3_randomness(sizeof(i), &i);
31925         break;
31926       }
31927     }
31928     if( (--aOp[pc+1]) > 0 ) nx = 0;
31929     pc += nx;
31930     i = (i & 0x7fffffff)%sz;
31931     if( (op & 1)!=0 ){
31932       SETBIT(pV, (i+1));
31933       if( op!=5 ){
31934         if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
31935       }
31936     }else{
31937       CLEARBIT(pV, (i+1));
31938       sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
31939     }
31940   }
31941
31942   /* Test to make sure the linear array exactly matches the
31943   ** Bitvec object.  Start with the assumption that they do
31944   ** match (rc==0).  Change rc to non-zero if a discrepancy
31945   ** is found.
31946   */
31947   rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
31948           + sqlite3BitvecTest(pBitvec, 0)
31949           + (sqlite3BitvecSize(pBitvec) - sz);
31950   for(i=1; i<=sz; i++){
31951     if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
31952       rc = i;
31953       break;
31954     }
31955   }
31956
31957   /* Free allocated structure */
31958 bitvec_end:
31959   sqlite3_free(pTmpSpace);
31960   sqlite3_free(pV);
31961   sqlite3BitvecDestroy(pBitvec);
31962   return rc;
31963 }
31964 #endif /* SQLITE_OMIT_BUILTIN_TEST */
31965
31966 /************** End of bitvec.c **********************************************/
31967 /************** Begin file pcache.c ******************************************/
31968 /*
31969 ** 2008 August 05
31970 **
31971 ** The author disclaims copyright to this source code.  In place of
31972 ** a legal notice, here is a blessing:
31973 **
31974 **    May you do good and not evil.
31975 **    May you find forgiveness for yourself and forgive others.
31976 **    May you share freely, never taking more than you give.
31977 **
31978 *************************************************************************
31979 ** This file implements that page cache.
31980 */
31981
31982 /*
31983 ** A complete page cache is an instance of this structure.
31984 */
31985 struct PCache {
31986   PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
31987   PgHdr *pSynced;                     /* Last synced page in dirty page list */
31988   int nRef;                           /* Number of referenced pages */
31989   int nMax;                           /* Configured cache size */
31990   int szPage;                         /* Size of every page in this cache */
31991   int szExtra;                        /* Size of extra space for each page */
31992   int bPurgeable;                     /* True if pages are on backing store */
31993   int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
31994   void *pStress;                      /* Argument to xStress */
31995   sqlite3_pcache *pCache;             /* Pluggable cache module */
31996   PgHdr *pPage1;                      /* Reference to page 1 */
31997 };
31998
31999 /*
32000 ** Some of the assert() macros in this code are too expensive to run
32001 ** even during normal debugging.  Use them only rarely on long-running
32002 ** tests.  Enable the expensive asserts using the
32003 ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
32004 */
32005 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
32006 # define expensive_assert(X)  assert(X)
32007 #else
32008 # define expensive_assert(X)
32009 #endif
32010
32011 /********************************** Linked List Management ********************/
32012
32013 #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
32014 /*
32015 ** Check that the pCache->pSynced variable is set correctly. If it
32016 ** is not, either fail an assert or return zero. Otherwise, return
32017 ** non-zero. This is only used in debugging builds, as follows:
32018 **
32019 **   expensive_assert( pcacheCheckSynced(pCache) );
32020 */
32021 static int pcacheCheckSynced(PCache *pCache){
32022   PgHdr *p;
32023   for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
32024     assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
32025   }
32026   return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
32027 }
32028 #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
32029
32030 /*
32031 ** Remove page pPage from the list of dirty pages.
32032 */
32033 static void pcacheRemoveFromDirtyList(PgHdr *pPage){
32034   PCache *p = pPage->pCache;
32035
32036   assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
32037   assert( pPage->pDirtyPrev || pPage==p->pDirty );
32038
32039   /* Update the PCache1.pSynced variable if necessary. */
32040   if( p->pSynced==pPage ){
32041     PgHdr *pSynced = pPage->pDirtyPrev;
32042     while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
32043       pSynced = pSynced->pDirtyPrev;
32044     }
32045     p->pSynced = pSynced;
32046   }
32047
32048   if( pPage->pDirtyNext ){
32049     pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
32050   }else{
32051     assert( pPage==p->pDirtyTail );
32052     p->pDirtyTail = pPage->pDirtyPrev;
32053   }
32054   if( pPage->pDirtyPrev ){
32055     pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
32056   }else{
32057     assert( pPage==p->pDirty );
32058     p->pDirty = pPage->pDirtyNext;
32059   }
32060   pPage->pDirtyNext = 0;
32061   pPage->pDirtyPrev = 0;
32062
32063   expensive_assert( pcacheCheckSynced(p) );
32064 }
32065
32066 /*
32067 ** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
32068 ** pPage).
32069 */
32070 static void pcacheAddToDirtyList(PgHdr *pPage){
32071   PCache *p = pPage->pCache;
32072
32073   assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
32074
32075   pPage->pDirtyNext = p->pDirty;
32076   if( pPage->pDirtyNext ){
32077     assert( pPage->pDirtyNext->pDirtyPrev==0 );
32078     pPage->pDirtyNext->pDirtyPrev = pPage;
32079   }
32080   p->pDirty = pPage;
32081   if( !p->pDirtyTail ){
32082     p->pDirtyTail = pPage;
32083   }
32084   if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
32085     p->pSynced = pPage;
32086   }
32087   expensive_assert( pcacheCheckSynced(p) );
32088 }
32089
32090 /*
32091 ** Wrapper around the pluggable caches xUnpin method. If the cache is
32092 ** being used for an in-memory database, this function is a no-op.
32093 */
32094 static void pcacheUnpin(PgHdr *p){
32095   PCache *pCache = p->pCache;
32096   if( pCache->bPurgeable ){
32097     if( p->pgno==1 ){
32098       pCache->pPage1 = 0;
32099     }
32100     sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 0);
32101   }
32102 }
32103
32104 /*************************************************** General Interfaces ******
32105 **
32106 ** Initialize and shutdown the page cache subsystem. Neither of these 
32107 ** functions are threadsafe.
32108 */
32109 SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
32110   if( sqlite3GlobalConfig.pcache.xInit==0 ){
32111     sqlite3PCacheSetDefault();
32112   }
32113   return sqlite3GlobalConfig.pcache.xInit(sqlite3GlobalConfig.pcache.pArg);
32114 }
32115 SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
32116   if( sqlite3GlobalConfig.pcache.xShutdown ){
32117     sqlite3GlobalConfig.pcache.xShutdown(sqlite3GlobalConfig.pcache.pArg);
32118   }
32119 }
32120
32121 /*
32122 ** Return the size in bytes of a PCache object.
32123 */
32124 SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
32125
32126 /*
32127 ** Create a new PCache object. Storage space to hold the object
32128 ** has already been allocated and is passed in as the p pointer. 
32129 ** The caller discovers how much space needs to be allocated by 
32130 ** calling sqlite3PcacheSize().
32131 */
32132 SQLITE_PRIVATE void sqlite3PcacheOpen(
32133   int szPage,                  /* Size of every page */
32134   int szExtra,                 /* Extra space associated with each page */
32135   int bPurgeable,              /* True if pages are on backing store */
32136   int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
32137   void *pStress,               /* Argument to xStress */
32138   PCache *p                    /* Preallocated space for the PCache */
32139 ){
32140   memset(p, 0, sizeof(PCache));
32141   p->szPage = szPage;
32142   p->szExtra = szExtra;
32143   p->bPurgeable = bPurgeable;
32144   p->xStress = xStress;
32145   p->pStress = pStress;
32146   p->nMax = 100;
32147 }
32148
32149 /*
32150 ** Change the page size for PCache object. The caller must ensure that there
32151 ** are no outstanding page references when this function is called.
32152 */
32153 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
32154   assert( pCache->nRef==0 && pCache->pDirty==0 );
32155   if( pCache->pCache ){
32156     sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
32157     pCache->pCache = 0;
32158     pCache->pPage1 = 0;
32159   }
32160   pCache->szPage = szPage;
32161 }
32162
32163 /*
32164 ** Try to obtain a page from the cache.
32165 */
32166 SQLITE_PRIVATE int sqlite3PcacheFetch(
32167   PCache *pCache,       /* Obtain the page from this cache */
32168   Pgno pgno,            /* Page number to obtain */
32169   int createFlag,       /* If true, create page if it does not exist already */
32170   PgHdr **ppPage        /* Write the page here */
32171 ){
32172   PgHdr *pPage = 0;
32173   int eCreate;
32174
32175   assert( pCache!=0 );
32176   assert( createFlag==1 || createFlag==0 );
32177   assert( pgno>0 );
32178
32179   /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
32180   ** allocate it now.
32181   */
32182   if( !pCache->pCache && createFlag ){
32183     sqlite3_pcache *p;
32184     int nByte;
32185     nByte = pCache->szPage + pCache->szExtra + sizeof(PgHdr);
32186     p = sqlite3GlobalConfig.pcache.xCreate(nByte, pCache->bPurgeable);
32187     if( !p ){
32188       return SQLITE_NOMEM;
32189     }
32190     sqlite3GlobalConfig.pcache.xCachesize(p, pCache->nMax);
32191     pCache->pCache = p;
32192   }
32193
32194   eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));
32195   if( pCache->pCache ){
32196     pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, eCreate);
32197   }
32198
32199   if( !pPage && eCreate==1 ){
32200     PgHdr *pPg;
32201
32202     /* Find a dirty page to write-out and recycle. First try to find a 
32203     ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
32204     ** cleared), but if that is not possible settle for any other 
32205     ** unreferenced dirty page.
32206     */
32207     expensive_assert( pcacheCheckSynced(pCache) );
32208     for(pPg=pCache->pSynced; 
32209         pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC)); 
32210         pPg=pPg->pDirtyPrev
32211     );
32212     pCache->pSynced = pPg;
32213     if( !pPg ){
32214       for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
32215     }
32216     if( pPg ){
32217       int rc;
32218       rc = pCache->xStress(pCache->pStress, pPg);
32219       if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
32220         return rc;
32221       }
32222     }
32223
32224     pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, 2);
32225   }
32226
32227   if( pPage ){
32228     if( !pPage->pData ){
32229       memset(pPage, 0, sizeof(PgHdr));
32230       pPage->pData = (void *)&pPage[1];
32231       pPage->pExtra = (void*)&((char *)pPage->pData)[pCache->szPage];
32232       memset(pPage->pExtra, 0, pCache->szExtra);
32233       pPage->pCache = pCache;
32234       pPage->pgno = pgno;
32235     }
32236     assert( pPage->pCache==pCache );
32237     assert( pPage->pgno==pgno );
32238     assert( pPage->pData==(void *)&pPage[1] );
32239     assert( pPage->pExtra==(void *)&((char *)&pPage[1])[pCache->szPage] );
32240
32241     if( 0==pPage->nRef ){
32242       pCache->nRef++;
32243     }
32244     pPage->nRef++;
32245     if( pgno==1 ){
32246       pCache->pPage1 = pPage;
32247     }
32248   }
32249   *ppPage = pPage;
32250   return (pPage==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
32251 }
32252
32253 /*
32254 ** Decrement the reference count on a page. If the page is clean and the
32255 ** reference count drops to 0, then it is made elible for recycling.
32256 */
32257 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
32258   assert( p->nRef>0 );
32259   p->nRef--;
32260   if( p->nRef==0 ){
32261     PCache *pCache = p->pCache;
32262     pCache->nRef--;
32263     if( (p->flags&PGHDR_DIRTY)==0 ){
32264       pcacheUnpin(p);
32265     }else{
32266       /* Move the page to the head of the dirty list. */
32267       pcacheRemoveFromDirtyList(p);
32268       pcacheAddToDirtyList(p);
32269     }
32270   }
32271 }
32272
32273 /*
32274 ** Increase the reference count of a supplied page by 1.
32275 */
32276 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
32277   assert(p->nRef>0);
32278   p->nRef++;
32279 }
32280
32281 /*
32282 ** Drop a page from the cache. There must be exactly one reference to the
32283 ** page. This function deletes that reference, so after it returns the
32284 ** page pointed to by p is invalid.
32285 */
32286 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
32287   PCache *pCache;
32288   assert( p->nRef==1 );
32289   if( p->flags&PGHDR_DIRTY ){
32290     pcacheRemoveFromDirtyList(p);
32291   }
32292   pCache = p->pCache;
32293   pCache->nRef--;
32294   if( p->pgno==1 ){
32295     pCache->pPage1 = 0;
32296   }
32297   sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 1);
32298 }
32299
32300 /*
32301 ** Make sure the page is marked as dirty. If it isn't dirty already,
32302 ** make it so.
32303 */
32304 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
32305   p->flags &= ~PGHDR_DONT_WRITE;
32306   assert( p->nRef>0 );
32307   if( 0==(p->flags & PGHDR_DIRTY) ){
32308     p->flags |= PGHDR_DIRTY;
32309     pcacheAddToDirtyList( p);
32310   }
32311 }
32312
32313 /*
32314 ** Make sure the page is marked as clean. If it isn't clean already,
32315 ** make it so.
32316 */
32317 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
32318   if( (p->flags & PGHDR_DIRTY) ){
32319     pcacheRemoveFromDirtyList(p);
32320     p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
32321     if( p->nRef==0 ){
32322       pcacheUnpin(p);
32323     }
32324   }
32325 }
32326
32327 /*
32328 ** Make every page in the cache clean.
32329 */
32330 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
32331   PgHdr *p;
32332   while( (p = pCache->pDirty)!=0 ){
32333     sqlite3PcacheMakeClean(p);
32334   }
32335 }
32336
32337 /*
32338 ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
32339 */
32340 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
32341   PgHdr *p;
32342   for(p=pCache->pDirty; p; p=p->pDirtyNext){
32343     p->flags &= ~PGHDR_NEED_SYNC;
32344   }
32345   pCache->pSynced = pCache->pDirtyTail;
32346 }
32347
32348 /*
32349 ** Change the page number of page p to newPgno. 
32350 */
32351 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
32352   PCache *pCache = p->pCache;
32353   assert( p->nRef>0 );
32354   assert( newPgno>0 );
32355   sqlite3GlobalConfig.pcache.xRekey(pCache->pCache, p, p->pgno, newPgno);
32356   p->pgno = newPgno;
32357   if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
32358     pcacheRemoveFromDirtyList(p);
32359     pcacheAddToDirtyList(p);
32360   }
32361 }
32362
32363 /*
32364 ** Drop every cache entry whose page number is greater than "pgno". The
32365 ** caller must ensure that there are no outstanding references to any pages
32366 ** other than page 1 with a page number greater than pgno.
32367 **
32368 ** If there is a reference to page 1 and the pgno parameter passed to this
32369 ** function is 0, then the data area associated with page 1 is zeroed, but
32370 ** the page object is not dropped.
32371 */
32372 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
32373   if( pCache->pCache ){
32374     PgHdr *p;
32375     PgHdr *pNext;
32376     for(p=pCache->pDirty; p; p=pNext){
32377       pNext = p->pDirtyNext;
32378       /* This routine never gets call with a positive pgno except right
32379       ** after sqlite3PcacheCleanAll().  So if there are dirty pages,
32380       ** it must be that pgno==0.
32381       */
32382       assert( p->pgno>0 );
32383       if( ALWAYS(p->pgno>pgno) ){
32384         assert( p->flags&PGHDR_DIRTY );
32385         sqlite3PcacheMakeClean(p);
32386       }
32387     }
32388     if( pgno==0 && pCache->pPage1 ){
32389       memset(pCache->pPage1->pData, 0, pCache->szPage);
32390       pgno = 1;
32391     }
32392     sqlite3GlobalConfig.pcache.xTruncate(pCache->pCache, pgno+1);
32393   }
32394 }
32395
32396 /*
32397 ** Close a cache.
32398 */
32399 SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
32400   if( pCache->pCache ){
32401     sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
32402   }
32403 }
32404
32405 /* 
32406 ** Discard the contents of the cache.
32407 */
32408 SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
32409   sqlite3PcacheTruncate(pCache, 0);
32410 }
32411
32412 /*
32413 ** Merge two lists of pages connected by pDirty and in pgno order.
32414 ** Do not both fixing the pDirtyPrev pointers.
32415 */
32416 static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
32417   PgHdr result, *pTail;
32418   pTail = &result;
32419   while( pA && pB ){
32420     if( pA->pgno<pB->pgno ){
32421       pTail->pDirty = pA;
32422       pTail = pA;
32423       pA = pA->pDirty;
32424     }else{
32425       pTail->pDirty = pB;
32426       pTail = pB;
32427       pB = pB->pDirty;
32428     }
32429   }
32430   if( pA ){
32431     pTail->pDirty = pA;
32432   }else if( pB ){
32433     pTail->pDirty = pB;
32434   }else{
32435     pTail->pDirty = 0;
32436   }
32437   return result.pDirty;
32438 }
32439
32440 /*
32441 ** Sort the list of pages in accending order by pgno.  Pages are
32442 ** connected by pDirty pointers.  The pDirtyPrev pointers are
32443 ** corrupted by this sort.
32444 **
32445 ** Since there cannot be more than 2^31 distinct pages in a database,
32446 ** there cannot be more than 31 buckets required by the merge sorter.
32447 ** One extra bucket is added to catch overflow in case something
32448 ** ever changes to make the previous sentence incorrect.
32449 */
32450 #define N_SORT_BUCKET  32
32451 static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
32452   PgHdr *a[N_SORT_BUCKET], *p;
32453   int i;
32454   memset(a, 0, sizeof(a));
32455   while( pIn ){
32456     p = pIn;
32457     pIn = p->pDirty;
32458     p->pDirty = 0;
32459     for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
32460       if( a[i]==0 ){
32461         a[i] = p;
32462         break;
32463       }else{
32464         p = pcacheMergeDirtyList(a[i], p);
32465         a[i] = 0;
32466       }
32467     }
32468     if( NEVER(i==N_SORT_BUCKET-1) ){
32469       /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
32470       ** the input list.  But that is impossible.
32471       */
32472       a[i] = pcacheMergeDirtyList(a[i], p);
32473     }
32474   }
32475   p = a[0];
32476   for(i=1; i<N_SORT_BUCKET; i++){
32477     p = pcacheMergeDirtyList(p, a[i]);
32478   }
32479   return p;
32480 }
32481
32482 /*
32483 ** Return a list of all dirty pages in the cache, sorted by page number.
32484 */
32485 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
32486   PgHdr *p;
32487   for(p=pCache->pDirty; p; p=p->pDirtyNext){
32488     p->pDirty = p->pDirtyNext;
32489   }
32490   return pcacheSortDirtyList(pCache->pDirty);
32491 }
32492
32493 /* 
32494 ** Return the total number of referenced pages held by the cache.
32495 */
32496 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
32497   return pCache->nRef;
32498 }
32499
32500 /*
32501 ** Return the number of references to the page supplied as an argument.
32502 */
32503 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
32504   return p->nRef;
32505 }
32506
32507 /* 
32508 ** Return the total number of pages in the cache.
32509 */
32510 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
32511   int nPage = 0;
32512   if( pCache->pCache ){
32513     nPage = sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache);
32514   }
32515   return nPage;
32516 }
32517
32518 #ifdef SQLITE_TEST
32519 /*
32520 ** Get the suggested cache-size value.
32521 */
32522 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
32523   return pCache->nMax;
32524 }
32525 #endif
32526
32527 /*
32528 ** Set the suggested cache-size value.
32529 */
32530 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
32531   pCache->nMax = mxPage;
32532   if( pCache->pCache ){
32533     sqlite3GlobalConfig.pcache.xCachesize(pCache->pCache, mxPage);
32534   }
32535 }
32536
32537 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
32538 /*
32539 ** For all dirty pages currently in the cache, invoke the specified
32540 ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
32541 ** defined.
32542 */
32543 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
32544   PgHdr *pDirty;
32545   for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
32546     xIter(pDirty);
32547   }
32548 }
32549 #endif
32550
32551 /************** End of pcache.c **********************************************/
32552 /************** Begin file pcache1.c *****************************************/
32553 /*
32554 ** 2008 November 05
32555 **
32556 ** The author disclaims copyright to this source code.  In place of
32557 ** a legal notice, here is a blessing:
32558 **
32559 **    May you do good and not evil.
32560 **    May you find forgiveness for yourself and forgive others.
32561 **    May you share freely, never taking more than you give.
32562 **
32563 *************************************************************************
32564 **
32565 ** This file implements the default page cache implementation (the
32566 ** sqlite3_pcache interface). It also contains part of the implementation
32567 ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
32568 ** If the default page cache implementation is overriden, then neither of
32569 ** these two features are available.
32570 */
32571
32572
32573 typedef struct PCache1 PCache1;
32574 typedef struct PgHdr1 PgHdr1;
32575 typedef struct PgFreeslot PgFreeslot;
32576
32577 /* Pointers to structures of this type are cast and returned as 
32578 ** opaque sqlite3_pcache* handles
32579 */
32580 struct PCache1 {
32581   /* Cache configuration parameters. Page size (szPage) and the purgeable
32582   ** flag (bPurgeable) are set when the cache is created. nMax may be 
32583   ** modified at any time by a call to the pcache1CacheSize() method.
32584   ** The global mutex must be held when accessing nMax.
32585   */
32586   int szPage;                         /* Size of allocated pages in bytes */
32587   int bPurgeable;                     /* True if cache is purgeable */
32588   unsigned int nMin;                  /* Minimum number of pages reserved */
32589   unsigned int nMax;                  /* Configured "cache_size" value */
32590
32591   /* Hash table of all pages. The following variables may only be accessed
32592   ** when the accessor is holding the global mutex (see pcache1EnterMutex() 
32593   ** and pcache1LeaveMutex()).
32594   */
32595   unsigned int nRecyclable;           /* Number of pages in the LRU list */
32596   unsigned int nPage;                 /* Total number of pages in apHash */
32597   unsigned int nHash;                 /* Number of slots in apHash[] */
32598   PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
32599
32600   unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
32601 };
32602
32603 /*
32604 ** Each cache entry is represented by an instance of the following 
32605 ** structure. A buffer of PgHdr1.pCache->szPage bytes is allocated 
32606 ** directly before this structure in memory (see the PGHDR1_TO_PAGE() 
32607 ** macro below).
32608 */
32609 struct PgHdr1 {
32610   unsigned int iKey;             /* Key value (page number) */
32611   PgHdr1 *pNext;                 /* Next in hash table chain */
32612   PCache1 *pCache;               /* Cache that currently owns this page */
32613   PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
32614   PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
32615 };
32616
32617 /*
32618 ** Free slots in the allocator used to divide up the buffer provided using
32619 ** the SQLITE_CONFIG_PAGECACHE mechanism.
32620 */
32621 struct PgFreeslot {
32622   PgFreeslot *pNext;  /* Next free slot */
32623 };
32624
32625 /*
32626 ** Global data used by this cache.
32627 */
32628 static SQLITE_WSD struct PCacheGlobal {
32629   sqlite3_mutex *mutex;               /* static mutex MUTEX_STATIC_LRU */
32630
32631   int nMaxPage;                       /* Sum of nMaxPage for purgeable caches */
32632   int nMinPage;                       /* Sum of nMinPage for purgeable caches */
32633   int nCurrentPage;                   /* Number of purgeable pages allocated */
32634   PgHdr1 *pLruHead, *pLruTail;        /* LRU list of unpinned pages */
32635
32636   /* Variables related to SQLITE_CONFIG_PAGECACHE settings. */
32637   int szSlot;                         /* Size of each free slot */
32638   void *pStart, *pEnd;                /* Bounds of pagecache malloc range */
32639   PgFreeslot *pFree;                  /* Free page blocks */
32640   int isInit;                         /* True if initialized */
32641 } pcache1_g;
32642
32643 /*
32644 ** All code in this file should access the global structure above via the
32645 ** alias "pcache1". This ensures that the WSD emulation is used when
32646 ** compiling for systems that do not support real WSD.
32647 */
32648 #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
32649
32650 /*
32651 ** When a PgHdr1 structure is allocated, the associated PCache1.szPage
32652 ** bytes of data are located directly before it in memory (i.e. the total
32653 ** size of the allocation is sizeof(PgHdr1)+PCache1.szPage byte). The
32654 ** PGHDR1_TO_PAGE() macro takes a pointer to a PgHdr1 structure as
32655 ** an argument and returns a pointer to the associated block of szPage
32656 ** bytes. The PAGE_TO_PGHDR1() macro does the opposite: its argument is
32657 ** a pointer to a block of szPage bytes of data and the return value is
32658 ** a pointer to the associated PgHdr1 structure.
32659 **
32660 **   assert( PGHDR1_TO_PAGE(PAGE_TO_PGHDR1(pCache, X))==X );
32661 */
32662 #define PGHDR1_TO_PAGE(p)    (void*)(((char*)p) - p->pCache->szPage)
32663 #define PAGE_TO_PGHDR1(c, p) (PgHdr1*)(((char*)p) + c->szPage)
32664
32665 /*
32666 ** Macros to enter and leave the global LRU mutex.
32667 */
32668 #define pcache1EnterMutex() sqlite3_mutex_enter(pcache1.mutex)
32669 #define pcache1LeaveMutex() sqlite3_mutex_leave(pcache1.mutex)
32670
32671 /******************************************************************************/
32672 /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
32673
32674 /*
32675 ** This function is called during initialization if a static buffer is 
32676 ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
32677 ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
32678 ** enough to contain 'n' buffers of 'sz' bytes each.
32679 */
32680 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
32681   if( pcache1.isInit ){
32682     PgFreeslot *p;
32683     sz = ROUNDDOWN8(sz);
32684     pcache1.szSlot = sz;
32685     pcache1.pStart = pBuf;
32686     pcache1.pFree = 0;
32687     while( n-- ){
32688       p = (PgFreeslot*)pBuf;
32689       p->pNext = pcache1.pFree;
32690       pcache1.pFree = p;
32691       pBuf = (void*)&((char*)pBuf)[sz];
32692     }
32693     pcache1.pEnd = pBuf;
32694   }
32695 }
32696
32697 /*
32698 ** Malloc function used within this file to allocate space from the buffer
32699 ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no 
32700 ** such buffer exists or there is no space left in it, this function falls 
32701 ** back to sqlite3Malloc().
32702 */
32703 static void *pcache1Alloc(int nByte){
32704   void *p;
32705   assert( sqlite3_mutex_held(pcache1.mutex) );
32706   if( nByte<=pcache1.szSlot && pcache1.pFree ){
32707     assert( pcache1.isInit );
32708     p = (PgHdr1 *)pcache1.pFree;
32709     pcache1.pFree = pcache1.pFree->pNext;
32710     sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
32711     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
32712   }else{
32713
32714     /* Allocate a new buffer using sqlite3Malloc. Before doing so, exit the
32715     ** global pcache mutex and unlock the pager-cache object pCache. This is 
32716     ** so that if the attempt to allocate a new buffer causes the the 
32717     ** configured soft-heap-limit to be breached, it will be possible to
32718     ** reclaim memory from this pager-cache.
32719     */
32720     pcache1LeaveMutex();
32721     p = sqlite3Malloc(nByte);
32722     pcache1EnterMutex();
32723     if( p ){
32724       int sz = sqlite3MallocSize(p);
32725       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
32726     }
32727     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
32728   }
32729   return p;
32730 }
32731
32732 /*
32733 ** Free an allocated buffer obtained from pcache1Alloc().
32734 */
32735 static void pcache1Free(void *p){
32736   assert( sqlite3_mutex_held(pcache1.mutex) );
32737   if( p==0 ) return;
32738   if( p>=pcache1.pStart && p<pcache1.pEnd ){
32739     PgFreeslot *pSlot;
32740     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
32741     pSlot = (PgFreeslot*)p;
32742     pSlot->pNext = pcache1.pFree;
32743     pcache1.pFree = pSlot;
32744   }else{
32745     int iSize;
32746     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
32747     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
32748     iSize = sqlite3MallocSize(p);
32749     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -iSize);
32750     sqlite3_free(p);
32751   }
32752 }
32753
32754 /*
32755 ** Allocate a new page object initially associated with cache pCache.
32756 */
32757 static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
32758   int nByte = sizeof(PgHdr1) + pCache->szPage;
32759   void *pPg = pcache1Alloc(nByte);
32760   PgHdr1 *p;
32761   if( pPg ){
32762     p = PAGE_TO_PGHDR1(pCache, pPg);
32763     if( pCache->bPurgeable ){
32764       pcache1.nCurrentPage++;
32765     }
32766   }else{
32767     p = 0;
32768   }
32769   return p;
32770 }
32771
32772 /*
32773 ** Free a page object allocated by pcache1AllocPage().
32774 **
32775 ** The pointer is allowed to be NULL, which is prudent.  But it turns out
32776 ** that the current implementation happens to never call this routine
32777 ** with a NULL pointer, so we mark the NULL test with ALWAYS().
32778 */
32779 static void pcache1FreePage(PgHdr1 *p){
32780   if( ALWAYS(p) ){
32781     if( p->pCache->bPurgeable ){
32782       pcache1.nCurrentPage--;
32783     }
32784     pcache1Free(PGHDR1_TO_PAGE(p));
32785   }
32786 }
32787
32788 /*
32789 ** Malloc function used by SQLite to obtain space from the buffer configured
32790 ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
32791 ** exists, this function falls back to sqlite3Malloc().
32792 */
32793 SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
32794   void *p;
32795   pcache1EnterMutex();
32796   p = pcache1Alloc(sz);
32797   pcache1LeaveMutex();
32798   return p;
32799 }
32800
32801 /*
32802 ** Free an allocated buffer obtained from sqlite3PageMalloc().
32803 */
32804 SQLITE_PRIVATE void sqlite3PageFree(void *p){
32805   pcache1EnterMutex();
32806   pcache1Free(p);
32807   pcache1LeaveMutex();
32808 }
32809
32810 /******************************************************************************/
32811 /******** General Implementation Functions ************************************/
32812
32813 /*
32814 ** This function is used to resize the hash table used by the cache passed
32815 ** as the first argument.
32816 **
32817 ** The global mutex must be held when this function is called.
32818 */
32819 static int pcache1ResizeHash(PCache1 *p){
32820   PgHdr1 **apNew;
32821   unsigned int nNew;
32822   unsigned int i;
32823
32824   assert( sqlite3_mutex_held(pcache1.mutex) );
32825
32826   nNew = p->nHash*2;
32827   if( nNew<256 ){
32828     nNew = 256;
32829   }
32830
32831   pcache1LeaveMutex();
32832   if( p->nHash ){ sqlite3BeginBenignMalloc(); }
32833   apNew = (PgHdr1 **)sqlite3_malloc(sizeof(PgHdr1 *)*nNew);
32834   if( p->nHash ){ sqlite3EndBenignMalloc(); }
32835   pcache1EnterMutex();
32836   if( apNew ){
32837     memset(apNew, 0, sizeof(PgHdr1 *)*nNew);
32838     for(i=0; i<p->nHash; i++){
32839       PgHdr1 *pPage;
32840       PgHdr1 *pNext = p->apHash[i];
32841       while( (pPage = pNext)!=0 ){
32842         unsigned int h = pPage->iKey % nNew;
32843         pNext = pPage->pNext;
32844         pPage->pNext = apNew[h];
32845         apNew[h] = pPage;
32846       }
32847     }
32848     sqlite3_free(p->apHash);
32849     p->apHash = apNew;
32850     p->nHash = nNew;
32851   }
32852
32853   return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
32854 }
32855
32856 /*
32857 ** This function is used internally to remove the page pPage from the 
32858 ** global LRU list, if is part of it. If pPage is not part of the global
32859 ** LRU list, then this function is a no-op.
32860 **
32861 ** The global mutex must be held when this function is called.
32862 */
32863 static void pcache1PinPage(PgHdr1 *pPage){
32864   assert( sqlite3_mutex_held(pcache1.mutex) );
32865   if( pPage && (pPage->pLruNext || pPage==pcache1.pLruTail) ){
32866     if( pPage->pLruPrev ){
32867       pPage->pLruPrev->pLruNext = pPage->pLruNext;
32868     }
32869     if( pPage->pLruNext ){
32870       pPage->pLruNext->pLruPrev = pPage->pLruPrev;
32871     }
32872     if( pcache1.pLruHead==pPage ){
32873       pcache1.pLruHead = pPage->pLruNext;
32874     }
32875     if( pcache1.pLruTail==pPage ){
32876       pcache1.pLruTail = pPage->pLruPrev;
32877     }
32878     pPage->pLruNext = 0;
32879     pPage->pLruPrev = 0;
32880     pPage->pCache->nRecyclable--;
32881   }
32882 }
32883
32884
32885 /*
32886 ** Remove the page supplied as an argument from the hash table 
32887 ** (PCache1.apHash structure) that it is currently stored in.
32888 **
32889 ** The global mutex must be held when this function is called.
32890 */
32891 static void pcache1RemoveFromHash(PgHdr1 *pPage){
32892   unsigned int h;
32893   PCache1 *pCache = pPage->pCache;
32894   PgHdr1 **pp;
32895
32896   h = pPage->iKey % pCache->nHash;
32897   for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
32898   *pp = (*pp)->pNext;
32899
32900   pCache->nPage--;
32901 }
32902
32903 /*
32904 ** If there are currently more than pcache.nMaxPage pages allocated, try
32905 ** to recycle pages to reduce the number allocated to pcache.nMaxPage.
32906 */
32907 static void pcache1EnforceMaxPage(void){
32908   assert( sqlite3_mutex_held(pcache1.mutex) );
32909   while( pcache1.nCurrentPage>pcache1.nMaxPage && pcache1.pLruTail ){
32910     PgHdr1 *p = pcache1.pLruTail;
32911     pcache1PinPage(p);
32912     pcache1RemoveFromHash(p);
32913     pcache1FreePage(p);
32914   }
32915 }
32916
32917 /*
32918 ** Discard all pages from cache pCache with a page number (key value) 
32919 ** greater than or equal to iLimit. Any pinned pages that meet this 
32920 ** criteria are unpinned before they are discarded.
32921 **
32922 ** The global mutex must be held when this function is called.
32923 */
32924 static void pcache1TruncateUnsafe(
32925   PCache1 *pCache, 
32926   unsigned int iLimit 
32927 ){
32928   TESTONLY( unsigned int nPage = 0; )      /* Used to assert pCache->nPage is correct */
32929   unsigned int h;
32930   assert( sqlite3_mutex_held(pcache1.mutex) );
32931   for(h=0; h<pCache->nHash; h++){
32932     PgHdr1 **pp = &pCache->apHash[h]; 
32933     PgHdr1 *pPage;
32934     while( (pPage = *pp)!=0 ){
32935       if( pPage->iKey>=iLimit ){
32936         pCache->nPage--;
32937         *pp = pPage->pNext;
32938         pcache1PinPage(pPage);
32939         pcache1FreePage(pPage);
32940       }else{
32941         pp = &pPage->pNext;
32942         TESTONLY( nPage++; )
32943       }
32944     }
32945   }
32946   assert( pCache->nPage==nPage );
32947 }
32948
32949 /******************************************************************************/
32950 /******** sqlite3_pcache Methods **********************************************/
32951
32952 /*
32953 ** Implementation of the sqlite3_pcache.xInit method.
32954 */
32955 static int pcache1Init(void *NotUsed){
32956   UNUSED_PARAMETER(NotUsed);
32957   assert( pcache1.isInit==0 );
32958   memset(&pcache1, 0, sizeof(pcache1));
32959   if( sqlite3GlobalConfig.bCoreMutex ){
32960     pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
32961   }
32962   pcache1.isInit = 1;
32963   return SQLITE_OK;
32964 }
32965
32966 /*
32967 ** Implementation of the sqlite3_pcache.xShutdown method.
32968 ** Note that the static mutex allocated in xInit does 
32969 ** not need to be freed.
32970 */
32971 static void pcache1Shutdown(void *NotUsed){
32972   UNUSED_PARAMETER(NotUsed);
32973   assert( pcache1.isInit!=0 );
32974   memset(&pcache1, 0, sizeof(pcache1));
32975 }
32976
32977 /*
32978 ** Implementation of the sqlite3_pcache.xCreate method.
32979 **
32980 ** Allocate a new cache.
32981 */
32982 static sqlite3_pcache *pcache1Create(int szPage, int bPurgeable){
32983   PCache1 *pCache;
32984
32985   pCache = (PCache1 *)sqlite3_malloc(sizeof(PCache1));
32986   if( pCache ){
32987     memset(pCache, 0, sizeof(PCache1));
32988     pCache->szPage = szPage;
32989     pCache->bPurgeable = (bPurgeable ? 1 : 0);
32990     if( bPurgeable ){
32991       pCache->nMin = 10;
32992       pcache1EnterMutex();
32993       pcache1.nMinPage += pCache->nMin;
32994       pcache1LeaveMutex();
32995     }
32996   }
32997   return (sqlite3_pcache *)pCache;
32998 }
32999
33000 /*
33001 ** Implementation of the sqlite3_pcache.xCachesize method. 
33002 **
33003 ** Configure the cache_size limit for a cache.
33004 */
33005 static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
33006   PCache1 *pCache = (PCache1 *)p;
33007   if( pCache->bPurgeable ){
33008     pcache1EnterMutex();
33009     pcache1.nMaxPage += (nMax - pCache->nMax);
33010     pCache->nMax = nMax;
33011     pcache1EnforceMaxPage();
33012     pcache1LeaveMutex();
33013   }
33014 }
33015
33016 /*
33017 ** Implementation of the sqlite3_pcache.xPagecount method. 
33018 */
33019 static int pcache1Pagecount(sqlite3_pcache *p){
33020   int n;
33021   pcache1EnterMutex();
33022   n = ((PCache1 *)p)->nPage;
33023   pcache1LeaveMutex();
33024   return n;
33025 }
33026
33027 /*
33028 ** Implementation of the sqlite3_pcache.xFetch method. 
33029 **
33030 ** Fetch a page by key value.
33031 **
33032 ** Whether or not a new page may be allocated by this function depends on
33033 ** the value of the createFlag argument.  0 means do not allocate a new
33034 ** page.  1 means allocate a new page if space is easily available.  2 
33035 ** means to try really hard to allocate a new page.
33036 **
33037 ** For a non-purgeable cache (a cache used as the storage for an in-memory
33038 ** database) there is really no difference between createFlag 1 and 2.  So
33039 ** the calling function (pcache.c) will never have a createFlag of 1 on
33040 ** a non-purgable cache.
33041 **
33042 ** There are three different approaches to obtaining space for a page,
33043 ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
33044 **
33045 **   1. Regardless of the value of createFlag, the cache is searched for a 
33046 **      copy of the requested page. If one is found, it is returned.
33047 **
33048 **   2. If createFlag==0 and the page is not already in the cache, NULL is
33049 **      returned.
33050 **
33051 **   3. If createFlag is 1, and the page is not already in the cache,
33052 **      and if either of the following are true, return NULL:
33053 **
33054 **       (a) the number of pages pinned by the cache is greater than
33055 **           PCache1.nMax, or
33056 **       (b) the number of pages pinned by the cache is greater than
33057 **           the sum of nMax for all purgeable caches, less the sum of 
33058 **           nMin for all other purgeable caches. 
33059 **
33060 **   4. If none of the first three conditions apply and the cache is marked
33061 **      as purgeable, and if one of the following is true:
33062 **
33063 **       (a) The number of pages allocated for the cache is already 
33064 **           PCache1.nMax, or
33065 **
33066 **       (b) The number of pages allocated for all purgeable caches is
33067 **           already equal to or greater than the sum of nMax for all
33068 **           purgeable caches,
33069 **
33070 **      then attempt to recycle a page from the LRU list. If it is the right
33071 **      size, return the recycled buffer. Otherwise, free the buffer and
33072 **      proceed to step 5. 
33073 **
33074 **   5. Otherwise, allocate and return a new page buffer.
33075 */
33076 static void *pcache1Fetch(sqlite3_pcache *p, unsigned int iKey, int createFlag){
33077   unsigned int nPinned;
33078   PCache1 *pCache = (PCache1 *)p;
33079   PgHdr1 *pPage = 0;
33080
33081   assert( pCache->bPurgeable || createFlag!=1 );
33082   pcache1EnterMutex();
33083   if( createFlag==1 ) sqlite3BeginBenignMalloc();
33084
33085   /* Search the hash table for an existing entry. */
33086   if( pCache->nHash>0 ){
33087     unsigned int h = iKey % pCache->nHash;
33088     for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
33089   }
33090
33091   if( pPage || createFlag==0 ){
33092     pcache1PinPage(pPage);
33093     goto fetch_out;
33094   }
33095
33096   /* Step 3 of header comment. */
33097   nPinned = pCache->nPage - pCache->nRecyclable;
33098   if( createFlag==1 && (
33099         nPinned>=(pcache1.nMaxPage+pCache->nMin-pcache1.nMinPage)
33100      || nPinned>=(pCache->nMax * 9 / 10)
33101   )){
33102     goto fetch_out;
33103   }
33104
33105   if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
33106     goto fetch_out;
33107   }
33108
33109   /* Step 4. Try to recycle a page buffer if appropriate. */
33110   if( pCache->bPurgeable && pcache1.pLruTail && (
33111      (pCache->nPage+1>=pCache->nMax) || pcache1.nCurrentPage>=pcache1.nMaxPage
33112   )){
33113     pPage = pcache1.pLruTail;
33114     pcache1RemoveFromHash(pPage);
33115     pcache1PinPage(pPage);
33116     if( pPage->pCache->szPage!=pCache->szPage ){
33117       pcache1FreePage(pPage);
33118       pPage = 0;
33119     }else{
33120       pcache1.nCurrentPage -= (pPage->pCache->bPurgeable - pCache->bPurgeable);
33121     }
33122   }
33123
33124   /* Step 5. If a usable page buffer has still not been found, 
33125   ** attempt to allocate a new one. 
33126   */
33127   if( !pPage ){
33128     pPage = pcache1AllocPage(pCache);
33129   }
33130
33131   if( pPage ){
33132     unsigned int h = iKey % pCache->nHash;
33133     pCache->nPage++;
33134     pPage->iKey = iKey;
33135     pPage->pNext = pCache->apHash[h];
33136     pPage->pCache = pCache;
33137     pPage->pLruPrev = 0;
33138     pPage->pLruNext = 0;
33139     *(void **)(PGHDR1_TO_PAGE(pPage)) = 0;
33140     pCache->apHash[h] = pPage;
33141   }
33142
33143 fetch_out:
33144   if( pPage && iKey>pCache->iMaxKey ){
33145     pCache->iMaxKey = iKey;
33146   }
33147   if( createFlag==1 ) sqlite3EndBenignMalloc();
33148   pcache1LeaveMutex();
33149   return (pPage ? PGHDR1_TO_PAGE(pPage) : 0);
33150 }
33151
33152
33153 /*
33154 ** Implementation of the sqlite3_pcache.xUnpin method.
33155 **
33156 ** Mark a page as unpinned (eligible for asynchronous recycling).
33157 */
33158 static void pcache1Unpin(sqlite3_pcache *p, void *pPg, int reuseUnlikely){
33159   PCache1 *pCache = (PCache1 *)p;
33160   PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
33161  
33162   assert( pPage->pCache==pCache );
33163   pcache1EnterMutex();
33164
33165   /* It is an error to call this function if the page is already 
33166   ** part of the global LRU list.
33167   */
33168   assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
33169   assert( pcache1.pLruHead!=pPage && pcache1.pLruTail!=pPage );
33170
33171   if( reuseUnlikely || pcache1.nCurrentPage>pcache1.nMaxPage ){
33172     pcache1RemoveFromHash(pPage);
33173     pcache1FreePage(pPage);
33174   }else{
33175     /* Add the page to the global LRU list. Normally, the page is added to
33176     ** the head of the list (last page to be recycled). However, if the 
33177     ** reuseUnlikely flag passed to this function is true, the page is added
33178     ** to the tail of the list (first page to be recycled).
33179     */
33180     if( pcache1.pLruHead ){
33181       pcache1.pLruHead->pLruPrev = pPage;
33182       pPage->pLruNext = pcache1.pLruHead;
33183       pcache1.pLruHead = pPage;
33184     }else{
33185       pcache1.pLruTail = pPage;
33186       pcache1.pLruHead = pPage;
33187     }
33188     pCache->nRecyclable++;
33189   }
33190
33191   pcache1LeaveMutex();
33192 }
33193
33194 /*
33195 ** Implementation of the sqlite3_pcache.xRekey method. 
33196 */
33197 static void pcache1Rekey(
33198   sqlite3_pcache *p,
33199   void *pPg,
33200   unsigned int iOld,
33201   unsigned int iNew
33202 ){
33203   PCache1 *pCache = (PCache1 *)p;
33204   PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
33205   PgHdr1 **pp;
33206   unsigned int h; 
33207   assert( pPage->iKey==iOld );
33208   assert( pPage->pCache==pCache );
33209
33210   pcache1EnterMutex();
33211
33212   h = iOld%pCache->nHash;
33213   pp = &pCache->apHash[h];
33214   while( (*pp)!=pPage ){
33215     pp = &(*pp)->pNext;
33216   }
33217   *pp = pPage->pNext;
33218
33219   h = iNew%pCache->nHash;
33220   pPage->iKey = iNew;
33221   pPage->pNext = pCache->apHash[h];
33222   pCache->apHash[h] = pPage;
33223   if( iNew>pCache->iMaxKey ){
33224     pCache->iMaxKey = iNew;
33225   }
33226
33227   pcache1LeaveMutex();
33228 }
33229
33230 /*
33231 ** Implementation of the sqlite3_pcache.xTruncate method. 
33232 **
33233 ** Discard all unpinned pages in the cache with a page number equal to
33234 ** or greater than parameter iLimit. Any pinned pages with a page number
33235 ** equal to or greater than iLimit are implicitly unpinned.
33236 */
33237 static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
33238   PCache1 *pCache = (PCache1 *)p;
33239   pcache1EnterMutex();
33240   if( iLimit<=pCache->iMaxKey ){
33241     pcache1TruncateUnsafe(pCache, iLimit);
33242     pCache->iMaxKey = iLimit-1;
33243   }
33244   pcache1LeaveMutex();
33245 }
33246
33247 /*
33248 ** Implementation of the sqlite3_pcache.xDestroy method. 
33249 **
33250 ** Destroy a cache allocated using pcache1Create().
33251 */
33252 static void pcache1Destroy(sqlite3_pcache *p){
33253   PCache1 *pCache = (PCache1 *)p;
33254   pcache1EnterMutex();
33255   pcache1TruncateUnsafe(pCache, 0);
33256   pcache1.nMaxPage -= pCache->nMax;
33257   pcache1.nMinPage -= pCache->nMin;
33258   pcache1EnforceMaxPage();
33259   pcache1LeaveMutex();
33260   sqlite3_free(pCache->apHash);
33261   sqlite3_free(pCache);
33262 }
33263
33264 /*
33265 ** This function is called during initialization (sqlite3_initialize()) to
33266 ** install the default pluggable cache module, assuming the user has not
33267 ** already provided an alternative.
33268 */
33269 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
33270   static const sqlite3_pcache_methods defaultMethods = {
33271     0,                       /* pArg */
33272     pcache1Init,             /* xInit */
33273     pcache1Shutdown,         /* xShutdown */
33274     pcache1Create,           /* xCreate */
33275     pcache1Cachesize,        /* xCachesize */
33276     pcache1Pagecount,        /* xPagecount */
33277     pcache1Fetch,            /* xFetch */
33278     pcache1Unpin,            /* xUnpin */
33279     pcache1Rekey,            /* xRekey */
33280     pcache1Truncate,         /* xTruncate */
33281     pcache1Destroy           /* xDestroy */
33282   };
33283   sqlite3_config(SQLITE_CONFIG_PCACHE, &defaultMethods);
33284 }
33285
33286 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
33287 /*
33288 ** This function is called to free superfluous dynamically allocated memory
33289 ** held by the pager system. Memory in use by any SQLite pager allocated
33290 ** by the current thread may be sqlite3_free()ed.
33291 **
33292 ** nReq is the number of bytes of memory required. Once this much has
33293 ** been released, the function returns. The return value is the total number 
33294 ** of bytes of memory released.
33295 */
33296 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
33297   int nFree = 0;
33298   if( pcache1.pStart==0 ){
33299     PgHdr1 *p;
33300     pcache1EnterMutex();
33301     while( (nReq<0 || nFree<nReq) && (p=pcache1.pLruTail) ){
33302       nFree += sqlite3MallocSize(PGHDR1_TO_PAGE(p));
33303       pcache1PinPage(p);
33304       pcache1RemoveFromHash(p);
33305       pcache1FreePage(p);
33306     }
33307     pcache1LeaveMutex();
33308   }
33309   return nFree;
33310 }
33311 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
33312
33313 #ifdef SQLITE_TEST
33314 /*
33315 ** This function is used by test procedures to inspect the internal state
33316 ** of the global cache.
33317 */
33318 SQLITE_PRIVATE void sqlite3PcacheStats(
33319   int *pnCurrent,      /* OUT: Total number of pages cached */
33320   int *pnMax,          /* OUT: Global maximum cache size */
33321   int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
33322   int *pnRecyclable    /* OUT: Total number of pages available for recycling */
33323 ){
33324   PgHdr1 *p;
33325   int nRecyclable = 0;
33326   for(p=pcache1.pLruHead; p; p=p->pLruNext){
33327     nRecyclable++;
33328   }
33329   *pnCurrent = pcache1.nCurrentPage;
33330   *pnMax = pcache1.nMaxPage;
33331   *pnMin = pcache1.nMinPage;
33332   *pnRecyclable = nRecyclable;
33333 }
33334 #endif
33335
33336 /************** End of pcache1.c *********************************************/
33337 /************** Begin file rowset.c ******************************************/
33338 /*
33339 ** 2008 December 3
33340 **
33341 ** The author disclaims copyright to this source code.  In place of
33342 ** a legal notice, here is a blessing:
33343 **
33344 **    May you do good and not evil.
33345 **    May you find forgiveness for yourself and forgive others.
33346 **    May you share freely, never taking more than you give.
33347 **
33348 *************************************************************************
33349 **
33350 ** This module implements an object we call a "RowSet".
33351 **
33352 ** The RowSet object is a collection of rowids.  Rowids
33353 ** are inserted into the RowSet in an arbitrary order.  Inserts
33354 ** can be intermixed with tests to see if a given rowid has been
33355 ** previously inserted into the RowSet.
33356 **
33357 ** After all inserts are finished, it is possible to extract the
33358 ** elements of the RowSet in sorted order.  Once this extraction
33359 ** process has started, no new elements may be inserted.
33360 **
33361 ** Hence, the primitive operations for a RowSet are:
33362 **
33363 **    CREATE
33364 **    INSERT
33365 **    TEST
33366 **    SMALLEST
33367 **    DESTROY
33368 **
33369 ** The CREATE and DESTROY primitives are the constructor and destructor,
33370 ** obviously.  The INSERT primitive adds a new element to the RowSet.
33371 ** TEST checks to see if an element is already in the RowSet.  SMALLEST
33372 ** extracts the least value from the RowSet.
33373 **
33374 ** The INSERT primitive might allocate additional memory.  Memory is
33375 ** allocated in chunks so most INSERTs do no allocation.  There is an 
33376 ** upper bound on the size of allocated memory.  No memory is freed
33377 ** until DESTROY.
33378 **
33379 ** The TEST primitive includes a "batch" number.  The TEST primitive
33380 ** will only see elements that were inserted before the last change
33381 ** in the batch number.  In other words, if an INSERT occurs between
33382 ** two TESTs where the TESTs have the same batch nubmer, then the
33383 ** value added by the INSERT will not be visible to the second TEST.
33384 ** The initial batch number is zero, so if the very first TEST contains
33385 ** a non-zero batch number, it will see all prior INSERTs.
33386 **
33387 ** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
33388 ** that is attempted.
33389 **
33390 ** The cost of an INSERT is roughly constant.  (Sometime new memory
33391 ** has to be allocated on an INSERT.)  The cost of a TEST with a new
33392 ** batch number is O(NlogN) where N is the number of elements in the RowSet.
33393 ** The cost of a TEST using the same batch number is O(logN).  The cost
33394 ** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
33395 ** primitives are constant time.  The cost of DESTROY is O(N).
33396 **
33397 ** There is an added cost of O(N) when switching between TEST and
33398 ** SMALLEST primitives.
33399 */
33400
33401
33402 /*
33403 ** Target size for allocation chunks.
33404 */
33405 #define ROWSET_ALLOCATION_SIZE 1024
33406
33407 /*
33408 ** The number of rowset entries per allocation chunk.
33409 */
33410 #define ROWSET_ENTRY_PER_CHUNK  \
33411                        ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
33412
33413 /*
33414 ** Each entry in a RowSet is an instance of the following object.
33415 */
33416 struct RowSetEntry {            
33417   i64 v;                        /* ROWID value for this entry */
33418   struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
33419   struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
33420 };
33421
33422 /*
33423 ** RowSetEntry objects are allocated in large chunks (instances of the
33424 ** following structure) to reduce memory allocation overhead.  The
33425 ** chunks are kept on a linked list so that they can be deallocated
33426 ** when the RowSet is destroyed.
33427 */
33428 struct RowSetChunk {
33429   struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
33430   struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
33431 };
33432
33433 /*
33434 ** A RowSet in an instance of the following structure.
33435 **
33436 ** A typedef of this structure if found in sqliteInt.h.
33437 */
33438 struct RowSet {
33439   struct RowSetChunk *pChunk;    /* List of all chunk allocations */
33440   sqlite3 *db;                   /* The database connection */
33441   struct RowSetEntry *pEntry;    /* List of entries using pRight */
33442   struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
33443   struct RowSetEntry *pFresh;    /* Source of new entry objects */
33444   struct RowSetEntry *pTree;     /* Binary tree of entries */
33445   u16 nFresh;                    /* Number of objects on pFresh */
33446   u8 isSorted;                   /* True if pEntry is sorted */
33447   u8 iBatch;                     /* Current insert batch */
33448 };
33449
33450 /*
33451 ** Turn bulk memory into a RowSet object.  N bytes of memory
33452 ** are available at pSpace.  The db pointer is used as a memory context
33453 ** for any subsequent allocations that need to occur.
33454 ** Return a pointer to the new RowSet object.
33455 **
33456 ** It must be the case that N is sufficient to make a Rowset.  If not
33457 ** an assertion fault occurs.
33458 ** 
33459 ** If N is larger than the minimum, use the surplus as an initial
33460 ** allocation of entries available to be filled.
33461 */
33462 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
33463   RowSet *p;
33464   assert( N >= ROUND8(sizeof(*p)) );
33465   p = pSpace;
33466   p->pChunk = 0;
33467   p->db = db;
33468   p->pEntry = 0;
33469   p->pLast = 0;
33470   p->pTree = 0;
33471   p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
33472   p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
33473   p->isSorted = 1;
33474   p->iBatch = 0;
33475   return p;
33476 }
33477
33478 /*
33479 ** Deallocate all chunks from a RowSet.  This frees all memory that
33480 ** the RowSet has allocated over its lifetime.  This routine is
33481 ** the destructor for the RowSet.
33482 */
33483 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
33484   struct RowSetChunk *pChunk, *pNextChunk;
33485   for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
33486     pNextChunk = pChunk->pNextChunk;
33487     sqlite3DbFree(p->db, pChunk);
33488   }
33489   p->pChunk = 0;
33490   p->nFresh = 0;
33491   p->pEntry = 0;
33492   p->pLast = 0;
33493   p->pTree = 0;
33494   p->isSorted = 1;
33495 }
33496
33497 /*
33498 ** Insert a new value into a RowSet.
33499 **
33500 ** The mallocFailed flag of the database connection is set if a
33501 ** memory allocation fails.
33502 */
33503 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
33504   struct RowSetEntry *pEntry;  /* The new entry */
33505   struct RowSetEntry *pLast;   /* The last prior entry */
33506   assert( p!=0 );
33507   if( p->nFresh==0 ){
33508     struct RowSetChunk *pNew;
33509     pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
33510     if( pNew==0 ){
33511       return;
33512     }
33513     pNew->pNextChunk = p->pChunk;
33514     p->pChunk = pNew;
33515     p->pFresh = pNew->aEntry;
33516     p->nFresh = ROWSET_ENTRY_PER_CHUNK;
33517   }
33518   pEntry = p->pFresh++;
33519   p->nFresh--;
33520   pEntry->v = rowid;
33521   pEntry->pRight = 0;
33522   pLast = p->pLast;
33523   if( pLast ){
33524     if( p->isSorted && rowid<=pLast->v ){
33525       p->isSorted = 0;
33526     }
33527     pLast->pRight = pEntry;
33528   }else{
33529     assert( p->pEntry==0 ); /* Fires if INSERT after SMALLEST */
33530     p->pEntry = pEntry;
33531   }
33532   p->pLast = pEntry;
33533 }
33534
33535 /*
33536 ** Merge two lists of RowSetEntry objects.  Remove duplicates.
33537 **
33538 ** The input lists are connected via pRight pointers and are 
33539 ** assumed to each already be in sorted order.
33540 */
33541 static struct RowSetEntry *rowSetMerge(
33542   struct RowSetEntry *pA,    /* First sorted list to be merged */
33543   struct RowSetEntry *pB     /* Second sorted list to be merged */
33544 ){
33545   struct RowSetEntry head;
33546   struct RowSetEntry *pTail;
33547
33548   pTail = &head;
33549   while( pA && pB ){
33550     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
33551     assert( pB->pRight==0 || pB->v<=pB->pRight->v );
33552     if( pA->v<pB->v ){
33553       pTail->pRight = pA;
33554       pA = pA->pRight;
33555       pTail = pTail->pRight;
33556     }else if( pB->v<pA->v ){
33557       pTail->pRight = pB;
33558       pB = pB->pRight;
33559       pTail = pTail->pRight;
33560     }else{
33561       pA = pA->pRight;
33562     }
33563   }
33564   if( pA ){
33565     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
33566     pTail->pRight = pA;
33567   }else{
33568     assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
33569     pTail->pRight = pB;
33570   }
33571   return head.pRight;
33572 }
33573
33574 /*
33575 ** Sort all elements on the pEntry list of the RowSet into ascending order.
33576 */ 
33577 static void rowSetSort(RowSet *p){
33578   unsigned int i;
33579   struct RowSetEntry *pEntry;
33580   struct RowSetEntry *aBucket[40];
33581
33582   assert( p->isSorted==0 );
33583   memset(aBucket, 0, sizeof(aBucket));
33584   while( p->pEntry ){
33585     pEntry = p->pEntry;
33586     p->pEntry = pEntry->pRight;
33587     pEntry->pRight = 0;
33588     for(i=0; aBucket[i]; i++){
33589       pEntry = rowSetMerge(aBucket[i], pEntry);
33590       aBucket[i] = 0;
33591     }
33592     aBucket[i] = pEntry;
33593   }
33594   pEntry = 0;
33595   for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
33596     pEntry = rowSetMerge(pEntry, aBucket[i]);
33597   }
33598   p->pEntry = pEntry;
33599   p->pLast = 0;
33600   p->isSorted = 1;
33601 }
33602
33603
33604 /*
33605 ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
33606 ** Convert this tree into a linked list connected by the pRight pointers
33607 ** and return pointers to the first and last elements of the new list.
33608 */
33609 static void rowSetTreeToList(
33610   struct RowSetEntry *pIn,         /* Root of the input tree */
33611   struct RowSetEntry **ppFirst,    /* Write head of the output list here */
33612   struct RowSetEntry **ppLast      /* Write tail of the output list here */
33613 ){
33614   assert( pIn!=0 );
33615   if( pIn->pLeft ){
33616     struct RowSetEntry *p;
33617     rowSetTreeToList(pIn->pLeft, ppFirst, &p);
33618     p->pRight = pIn;
33619   }else{
33620     *ppFirst = pIn;
33621   }
33622   if( pIn->pRight ){
33623     rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
33624   }else{
33625     *ppLast = pIn;
33626   }
33627   assert( (*ppLast)->pRight==0 );
33628 }
33629
33630
33631 /*
33632 ** Convert a sorted list of elements (connected by pRight) into a binary
33633 ** tree with depth of iDepth.  A depth of 1 means the tree contains a single
33634 ** node taken from the head of *ppList.  A depth of 2 means a tree with
33635 ** three nodes.  And so forth.
33636 **
33637 ** Use as many entries from the input list as required and update the
33638 ** *ppList to point to the unused elements of the list.  If the input
33639 ** list contains too few elements, then construct an incomplete tree
33640 ** and leave *ppList set to NULL.
33641 **
33642 ** Return a pointer to the root of the constructed binary tree.
33643 */
33644 static struct RowSetEntry *rowSetNDeepTree(
33645   struct RowSetEntry **ppList,
33646   int iDepth
33647 ){
33648   struct RowSetEntry *p;         /* Root of the new tree */
33649   struct RowSetEntry *pLeft;     /* Left subtree */
33650   if( *ppList==0 ){
33651     return 0;
33652   }
33653   if( iDepth==1 ){
33654     p = *ppList;
33655     *ppList = p->pRight;
33656     p->pLeft = p->pRight = 0;
33657     return p;
33658   }
33659   pLeft = rowSetNDeepTree(ppList, iDepth-1);
33660   p = *ppList;
33661   if( p==0 ){
33662     return pLeft;
33663   }
33664   p->pLeft = pLeft;
33665   *ppList = p->pRight;
33666   p->pRight = rowSetNDeepTree(ppList, iDepth-1);
33667   return p;
33668 }
33669
33670 /*
33671 ** Convert a sorted list of elements into a binary tree. Make the tree
33672 ** as deep as it needs to be in order to contain the entire list.
33673 */
33674 static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
33675   int iDepth;           /* Depth of the tree so far */
33676   struct RowSetEntry *p;       /* Current tree root */
33677   struct RowSetEntry *pLeft;   /* Left subtree */
33678
33679   assert( pList!=0 );
33680   p = pList;
33681   pList = p->pRight;
33682   p->pLeft = p->pRight = 0;
33683   for(iDepth=1; pList; iDepth++){
33684     pLeft = p;
33685     p = pList;
33686     pList = p->pRight;
33687     p->pLeft = pLeft;
33688     p->pRight = rowSetNDeepTree(&pList, iDepth);
33689   }
33690   return p;
33691 }
33692
33693 /*
33694 ** Convert the list in p->pEntry into a sorted list if it is not
33695 ** sorted already.  If there is a binary tree on p->pTree, then
33696 ** convert it into a list too and merge it into the p->pEntry list.
33697 */
33698 static void rowSetToList(RowSet *p){
33699   if( !p->isSorted ){
33700     rowSetSort(p);
33701   }
33702   if( p->pTree ){
33703     struct RowSetEntry *pHead, *pTail;
33704     rowSetTreeToList(p->pTree, &pHead, &pTail);
33705     p->pTree = 0;
33706     p->pEntry = rowSetMerge(p->pEntry, pHead);
33707   }
33708 }
33709
33710 /*
33711 ** Extract the smallest element from the RowSet.
33712 ** Write the element into *pRowid.  Return 1 on success.  Return
33713 ** 0 if the RowSet is already empty.
33714 **
33715 ** After this routine has been called, the sqlite3RowSetInsert()
33716 ** routine may not be called again.  
33717 */
33718 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
33719   rowSetToList(p);
33720   if( p->pEntry ){
33721     *pRowid = p->pEntry->v;
33722     p->pEntry = p->pEntry->pRight;
33723     if( p->pEntry==0 ){
33724       sqlite3RowSetClear(p);
33725     }
33726     return 1;
33727   }else{
33728     return 0;
33729   }
33730 }
33731
33732 /*
33733 ** Check to see if element iRowid was inserted into the the rowset as
33734 ** part of any insert batch prior to iBatch.  Return 1 or 0.
33735 */
33736 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
33737   struct RowSetEntry *p;
33738   if( iBatch!=pRowSet->iBatch ){
33739     if( pRowSet->pEntry ){
33740       rowSetToList(pRowSet);
33741       pRowSet->pTree = rowSetListToTree(pRowSet->pEntry);
33742       pRowSet->pEntry = 0;
33743       pRowSet->pLast = 0;
33744     }
33745     pRowSet->iBatch = iBatch;
33746   }
33747   p = pRowSet->pTree;
33748   while( p ){
33749     if( p->v<iRowid ){
33750       p = p->pRight;
33751     }else if( p->v>iRowid ){
33752       p = p->pLeft;
33753     }else{
33754       return 1;
33755     }
33756   }
33757   return 0;
33758 }
33759
33760 /************** End of rowset.c **********************************************/
33761 /************** Begin file pager.c *******************************************/
33762 /*
33763 ** 2001 September 15
33764 **
33765 ** The author disclaims copyright to this source code.  In place of
33766 ** a legal notice, here is a blessing:
33767 **
33768 **    May you do good and not evil.
33769 **    May you find forgiveness for yourself and forgive others.
33770 **    May you share freely, never taking more than you give.
33771 **
33772 *************************************************************************
33773 ** This is the implementation of the page cache subsystem or "pager".
33774 ** 
33775 ** The pager is used to access a database disk file.  It implements
33776 ** atomic commit and rollback through the use of a journal file that
33777 ** is separate from the database file.  The pager also implements file
33778 ** locking to prevent two processes from writing the same database
33779 ** file simultaneously, or one process from reading the database while
33780 ** another is writing.
33781 */
33782 #ifndef SQLITE_OMIT_DISKIO
33783 /************** Include wal.h in the middle of pager.c ***********************/
33784 /************** Begin file wal.h *********************************************/
33785 /*
33786 ** 2010 February 1
33787 **
33788 ** The author disclaims copyright to this source code.  In place of
33789 ** a legal notice, here is a blessing:
33790 **
33791 **    May you do good and not evil.
33792 **    May you find forgiveness for yourself and forgive others.
33793 **    May you share freely, never taking more than you give.
33794 **
33795 *************************************************************************
33796 ** This header file defines the interface to the write-ahead logging 
33797 ** system. Refer to the comments below and the header comment attached to 
33798 ** the implementation of each function in log.c for further details.
33799 */
33800
33801 #ifndef _WAL_H_
33802 #define _WAL_H_
33803
33804
33805 #ifdef SQLITE_OMIT_WAL
33806 # define sqlite3WalOpen(x,y,z)                 0
33807 # define sqlite3WalClose(w,x,y,z)              0
33808 # define sqlite3WalBeginReadTransaction(y,z)   0
33809 # define sqlite3WalEndReadTransaction(z)
33810 # define sqlite3WalRead(v,w,x,y,z)             0
33811 # define sqlite3WalDbsize(y,z)
33812 # define sqlite3WalBeginWriteTransaction(y)    0
33813 # define sqlite3WalEndWriteTransaction(x)      0
33814 # define sqlite3WalUndo(x,y,z)                 0
33815 # define sqlite3WalSavepoint(y,z)
33816 # define sqlite3WalSavepointUndo(y,z)          0
33817 # define sqlite3WalFrames(u,v,w,x,y,z)         0
33818 # define sqlite3WalCheckpoint(u,v,w,x)         0
33819 # define sqlite3WalCallback(z)                 0
33820 # define sqlite3WalExclusiveMode(y,z)          0
33821 #else
33822
33823 #define WAL_SAVEPOINT_NDATA 4
33824
33825 /* Connection to a write-ahead log (WAL) file. 
33826 ** There is one object of this type for each pager. 
33827 */
33828 typedef struct Wal Wal;
33829
33830 /* Open and close a connection to a write-ahead log. */
33831 SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *zName, Wal**);
33832 SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
33833
33834 /* Used by readers to open (lock) and close (unlock) a snapshot.  A 
33835 ** snapshot is like a read-transaction.  It is the state of the database
33836 ** at an instant in time.  sqlite3WalOpenSnapshot gets a read lock and
33837 ** preserves the current state even if the other threads or processes
33838 ** write to or checkpoint the WAL.  sqlite3WalCloseSnapshot() closes the
33839 ** transaction and releases the lock.
33840 */
33841 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
33842 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
33843
33844 /* Read a page from the write-ahead log, if it is present. */
33845 SQLITE_PRIVATE int sqlite3WalRead(Wal *pWal, Pgno pgno, int *pInWal, int nOut, u8 *pOut);
33846
33847 /* Return the size of the database as it existed at the beginning
33848 ** of the snapshot */
33849 SQLITE_PRIVATE void sqlite3WalDbsize(Wal *pWal, Pgno *pPgno);
33850
33851 /* Obtain or release the WRITER lock. */
33852 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
33853 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
33854
33855 /* Undo any frames written (but not committed) to the log */
33856 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
33857
33858 /* Return an integer that records the current (uncommitted) write
33859 ** position in the WAL */
33860 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
33861
33862 /* Move the write position of the WAL back to iFrame.  Called in
33863 ** response to a ROLLBACK TO command. */
33864 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
33865
33866 /* Write a frame or frames to the log. */
33867 SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
33868
33869 /* Copy pages from the log to the database file */ 
33870 SQLITE_PRIVATE int sqlite3WalCheckpoint(
33871   Wal *pWal,                      /* Write-ahead log connection */
33872   int sync_flags,                 /* Flags to sync db file with (or 0) */
33873   int nBuf,                       /* Size of buffer nBuf */
33874   u8 *zBuf                        /* Temporary buffer to use */
33875 );
33876
33877 /* Return the value to pass to a sqlite3_wal_hook callback, the
33878 ** number of frames in the WAL at the point of the last commit since
33879 ** sqlite3WalCallback() was called.  If no commits have occurred since
33880 ** the last call, then return 0.
33881 */
33882 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
33883
33884 /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
33885 ** by the pager layer on the database file.
33886 */
33887 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
33888
33889 #endif /* ifndef SQLITE_OMIT_WAL */
33890 #endif /* _WAL_H_ */
33891
33892 /************** End of wal.h *************************************************/
33893 /************** Continuing where we left off in pager.c **********************/
33894
33895 /*
33896 ******************** NOTES ON THE DESIGN OF THE PAGER ************************
33897 **
33898 ** Within this comment block, a page is deemed to have been synced
33899 ** automatically as soon as it is written when PRAGMA synchronous=OFF.
33900 ** Otherwise, the page is not synced until the xSync method of the VFS
33901 ** is called successfully on the file containing the page.
33902 **
33903 ** Definition:  A page of the database file is said to be "overwriteable" if
33904 ** one or more of the following are true about the page:
33905 ** 
33906 **     (a)  The original content of the page as it was at the beginning of
33907 **          the transaction has been written into the rollback journal and
33908 **          synced.
33909 ** 
33910 **     (b)  The page was a freelist leaf page at the start of the transaction.
33911 ** 
33912 **     (c)  The page number is greater than the largest page that existed in
33913 **          the database file at the start of the transaction.
33914 ** 
33915 ** (1) A page of the database file is never overwritten unless one of the
33916 **     following are true:
33917 ** 
33918 **     (a) The page and all other pages on the same sector are overwriteable.
33919 ** 
33920 **     (b) The atomic page write optimization is enabled, and the entire
33921 **         transaction other than the update of the transaction sequence
33922 **         number consists of a single page change.
33923 ** 
33924 ** (2) The content of a page written into the rollback journal exactly matches
33925 **     both the content in the database when the rollback journal was written
33926 **     and the content in the database at the beginning of the current
33927 **     transaction.
33928 ** 
33929 ** (3) Writes to the database file are an integer multiple of the page size
33930 **     in length and are aligned to a page boundary.
33931 ** 
33932 ** (4) Reads from the database file are either aligned on a page boundary and
33933 **     an integer multiple of the page size in length or are taken from the
33934 **     first 100 bytes of the database file.
33935 ** 
33936 ** (5) All writes to the database file are synced prior to the rollback journal
33937 **     being deleted, truncated, or zeroed.
33938 ** 
33939 ** (6) If a master journal file is used, then all writes to the database file
33940 **     are synced prior to the master journal being deleted.
33941 ** 
33942 ** Definition: Two databases (or the same database at two points it time)
33943 ** are said to be "logically equivalent" if they give the same answer to
33944 ** all queries.  Note in particular the the content of freelist leaf
33945 ** pages can be changed arbitarily without effecting the logical equivalence
33946 ** of the database.
33947 ** 
33948 ** (7) At any time, if any subset, including the empty set and the total set,
33949 **     of the unsynced changes to a rollback journal are removed and the 
33950 **     journal is rolled back, the resulting database file will be logical
33951 **     equivalent to the database file at the beginning of the transaction.
33952 ** 
33953 ** (8) When a transaction is rolled back, the xTruncate method of the VFS
33954 **     is called to restore the database file to the same size it was at
33955 **     the beginning of the transaction.  (In some VFSes, the xTruncate
33956 **     method is a no-op, but that does not change the fact the SQLite will
33957 **     invoke it.)
33958 ** 
33959 ** (9) Whenever the database file is modified, at least one bit in the range
33960 **     of bytes from 24 through 39 inclusive will be changed prior to releasing
33961 **     the EXCLUSIVE lock.
33962 **
33963 ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
33964 **      than one billion transactions.
33965 **
33966 ** (11) A database file is well-formed at the beginning and at the conclusion
33967 **      of every transaction.
33968 **
33969 ** (12) An EXCLUSIVE lock is held on the database file when writing to
33970 **      the database file.
33971 **
33972 ** (13) A SHARED lock is held on the database file while reading any
33973 **      content out of the database file.
33974 */
33975
33976 /*
33977 ** Macros for troubleshooting.  Normally turned off
33978 */
33979 #if 0
33980 int sqlite3PagerTrace=1;  /* True to enable tracing */
33981 #define sqlite3DebugPrintf printf
33982 #define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
33983 #else
33984 #define PAGERTRACE(X)
33985 #endif
33986
33987 /*
33988 ** The following two macros are used within the PAGERTRACE() macros above
33989 ** to print out file-descriptors. 
33990 **
33991 ** PAGERID() takes a pointer to a Pager struct as its argument. The
33992 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
33993 ** struct as its argument.
33994 */
33995 #define PAGERID(p) ((int)(p->fd))
33996 #define FILEHANDLEID(fd) ((int)fd)
33997
33998 /*
33999 ** The page cache as a whole is always in one of the following
34000 ** states:
34001 **
34002 **   PAGER_UNLOCK        The page cache is not currently reading or 
34003 **                       writing the database file.  There is no
34004 **                       data held in memory.  This is the initial
34005 **                       state.
34006 **
34007 **   PAGER_SHARED        The page cache is reading the database.
34008 **                       Writing is not permitted.  There can be
34009 **                       multiple readers accessing the same database
34010 **                       file at the same time.
34011 **
34012 **   PAGER_RESERVED      This process has reserved the database for writing
34013 **                       but has not yet made any changes.  Only one process
34014 **                       at a time can reserve the database.  The original
34015 **                       database file has not been modified so other
34016 **                       processes may still be reading the on-disk
34017 **                       database file.
34018 **
34019 **   PAGER_EXCLUSIVE     The page cache is writing the database.
34020 **                       Access is exclusive.  No other processes or
34021 **                       threads can be reading or writing while one
34022 **                       process is writing.
34023 **
34024 **   PAGER_SYNCED        The pager moves to this state from PAGER_EXCLUSIVE
34025 **                       after all dirty pages have been written to the
34026 **                       database file and the file has been synced to
34027 **                       disk. All that remains to do is to remove or
34028 **                       truncate the journal file and the transaction 
34029 **                       will be committed.
34030 **
34031 ** The page cache comes up in PAGER_UNLOCK.  The first time a
34032 ** sqlite3PagerGet() occurs, the state transitions to PAGER_SHARED.
34033 ** After all pages have been released using sqlite_page_unref(),
34034 ** the state transitions back to PAGER_UNLOCK.  The first time
34035 ** that sqlite3PagerWrite() is called, the state transitions to
34036 ** PAGER_RESERVED.  (Note that sqlite3PagerWrite() can only be
34037 ** called on an outstanding page which means that the pager must
34038 ** be in PAGER_SHARED before it transitions to PAGER_RESERVED.)
34039 ** PAGER_RESERVED means that there is an open rollback journal.
34040 ** The transition to PAGER_EXCLUSIVE occurs before any changes
34041 ** are made to the database file, though writes to the rollback
34042 ** journal occurs with just PAGER_RESERVED.  After an sqlite3PagerRollback()
34043 ** or sqlite3PagerCommitPhaseTwo(), the state can go back to PAGER_SHARED,
34044 ** or it can stay at PAGER_EXCLUSIVE if we are in exclusive access mode.
34045 */
34046 #define PAGER_UNLOCK      0
34047 #define PAGER_SHARED      1   /* same as SHARED_LOCK */
34048 #define PAGER_RESERVED    2   /* same as RESERVED_LOCK */
34049 #define PAGER_EXCLUSIVE   4   /* same as EXCLUSIVE_LOCK */
34050 #define PAGER_SYNCED      5
34051
34052 /*
34053 ** A macro used for invoking the codec if there is one
34054 */
34055 #ifdef SQLITE_HAS_CODEC
34056 # define CODEC1(P,D,N,X,E) \
34057     if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
34058 # define CODEC2(P,D,N,X,E,O) \
34059     if( P->xCodec==0 ){ O=(char*)D; }else \
34060     if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
34061 #else
34062 # define CODEC1(P,D,N,X,E)   /* NO-OP */
34063 # define CODEC2(P,D,N,X,E,O) O=(char*)D
34064 #endif
34065
34066 /*
34067 ** The maximum allowed sector size. 64KiB. If the xSectorsize() method 
34068 ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
34069 ** This could conceivably cause corruption following a power failure on
34070 ** such a system. This is currently an undocumented limit.
34071 */
34072 #define MAX_SECTOR_SIZE 0x10000
34073
34074 /*
34075 ** An instance of the following structure is allocated for each active
34076 ** savepoint and statement transaction in the system. All such structures
34077 ** are stored in the Pager.aSavepoint[] array, which is allocated and
34078 ** resized using sqlite3Realloc().
34079 **
34080 ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
34081 ** set to 0. If a journal-header is written into the main journal while
34082 ** the savepoint is active, then iHdrOffset is set to the byte offset 
34083 ** immediately following the last journal record written into the main
34084 ** journal before the journal-header. This is required during savepoint
34085 ** rollback (see pagerPlaybackSavepoint()).
34086 */
34087 typedef struct PagerSavepoint PagerSavepoint;
34088 struct PagerSavepoint {
34089   i64 iOffset;                 /* Starting offset in main journal */
34090   i64 iHdrOffset;              /* See above */
34091   Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
34092   Pgno nOrig;                  /* Original number of pages in file */
34093   Pgno iSubRec;                /* Index of first record in sub-journal */
34094 #ifndef SQLITE_OMIT_WAL
34095   u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */
34096 #endif
34097 };
34098
34099 /*
34100 ** A open page cache is an instance of the following structure.
34101 **
34102 ** errCode
34103 **
34104 **   Pager.errCode may be set to SQLITE_IOERR, SQLITE_CORRUPT, or
34105 **   or SQLITE_FULL. Once one of the first three errors occurs, it persists
34106 **   and is returned as the result of every major pager API call.  The
34107 **   SQLITE_FULL return code is slightly different. It persists only until the
34108 **   next successful rollback is performed on the pager cache. Also,
34109 **   SQLITE_FULL does not affect the sqlite3PagerGet() and sqlite3PagerLookup()
34110 **   APIs, they may still be used successfully.
34111 **
34112 ** dbSizeValid, dbSize, dbOrigSize, dbFileSize
34113 **
34114 **   Managing the size of the database file in pages is a little complicated.
34115 **   The variable Pager.dbSize contains the number of pages that the database
34116 **   image currently contains. As the database image grows or shrinks this
34117 **   variable is updated. The variable Pager.dbFileSize contains the number
34118 **   of pages in the database file. This may be different from Pager.dbSize
34119 **   if some pages have been appended to the database image but not yet written
34120 **   out from the cache to the actual file on disk. Or if the image has been
34121 **   truncated by an incremental-vacuum operation. The Pager.dbOrigSize variable
34122 **   contains the number of pages in the database image when the current
34123 **   transaction was opened. The contents of all three of these variables is
34124 **   only guaranteed to be correct if the boolean Pager.dbSizeValid is true.
34125 **
34126 **   TODO: Under what conditions is dbSizeValid set? Cleared?
34127 **
34128 ** changeCountDone
34129 **
34130 **   This boolean variable is used to make sure that the change-counter 
34131 **   (the 4-byte header field at byte offset 24 of the database file) is 
34132 **   not updated more often than necessary. 
34133 **
34134 **   It is set to true when the change-counter field is updated, which 
34135 **   can only happen if an exclusive lock is held on the database file.
34136 **   It is cleared (set to false) whenever an exclusive lock is 
34137 **   relinquished on the database file. Each time a transaction is committed,
34138 **   The changeCountDone flag is inspected. If it is true, the work of
34139 **   updating the change-counter is omitted for the current transaction.
34140 **
34141 **   This mechanism means that when running in exclusive mode, a connection 
34142 **   need only update the change-counter once, for the first transaction
34143 **   committed.
34144 **
34145 ** dbModified
34146 **
34147 **   The dbModified flag is set whenever a database page is dirtied.
34148 **   It is cleared at the end of each transaction.
34149 **
34150 **   It is used when committing or otherwise ending a transaction. If
34151 **   the dbModified flag is clear then less work has to be done.
34152 **
34153 ** journalStarted
34154 **
34155 **   This flag is set whenever the the main journal is opened and
34156 **   initialized
34157 **
34158 **   The point of this flag is that it must be set after the 
34159 **   first journal header in a journal file has been synced to disk.
34160 **   After this has happened, new pages appended to the database 
34161 **   do not need the PGHDR_NEED_SYNC flag set, as they do not need
34162 **   to wait for a journal sync before they can be written out to
34163 **   the database file (see function pager_write()).
34164 **   
34165 ** setMaster
34166 **
34167 **   This variable is used to ensure that the master journal file name
34168 **   (if any) is only written into the journal file once.
34169 **
34170 **   When committing a transaction, the master journal file name (if any)
34171 **   may be written into the journal file while the pager is still in
34172 **   PAGER_RESERVED state (see CommitPhaseOne() for the action). It
34173 **   then attempts to upgrade to an exclusive lock. If this attempt
34174 **   fails, then SQLITE_BUSY may be returned to the user and the user
34175 **   may attempt to commit the transaction again later (calling
34176 **   CommitPhaseOne() again). This flag is used to ensure that the 
34177 **   master journal name is only written to the journal file the first
34178 **   time CommitPhaseOne() is called.
34179 **
34180 ** doNotSpill, doNotSyncSpill
34181 **
34182 **   When enabled, cache spills are prohibited.  The doNotSpill variable
34183 **   inhibits all cache spill and doNotSyncSpill inhibits those spills that
34184 **   would require a journal sync.  The doNotSyncSpill is set and cleared 
34185 **   by sqlite3PagerWrite() in order to prevent a journal sync from happening 
34186 **   in between the journalling of two pages on the same sector.  The
34187 **   doNotSpill value set to prevent pagerStress() from trying to use
34188 **   the journal during a rollback.
34189 **
34190 ** needSync
34191 **
34192 **   TODO: It might be easier to set this variable in writeJournalHdr()
34193 **   and writeMasterJournal() only. Change its meaning to "unsynced data
34194 **   has been written to the journal".
34195 **
34196 ** subjInMemory
34197 **
34198 **   This is a boolean variable. If true, then any required sub-journal
34199 **   is opened as an in-memory journal file. If false, then in-memory
34200 **   sub-journals are only used for in-memory pager files.
34201 */
34202 struct Pager {
34203   sqlite3_vfs *pVfs;          /* OS functions to use for IO */
34204   u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
34205   u8 journalMode;             /* On of the PAGER_JOURNALMODE_* values */
34206   u8 useJournal;              /* Use a rollback journal on this file */
34207   u8 noReadlock;              /* Do not bother to obtain readlocks */
34208   u8 noSync;                  /* Do not sync the journal if true */
34209   u8 fullSync;                /* Do extra syncs of the journal for robustness */
34210   u8 sync_flags;              /* One of SYNC_NORMAL or SYNC_FULL */
34211   u8 tempFile;                /* zFilename is a temporary file */
34212   u8 readOnly;                /* True for a read-only database */
34213   u8 memDb;                   /* True to inhibit all file I/O */
34214
34215   /* The following block contains those class members that are dynamically
34216   ** modified during normal operations. The other variables in this structure
34217   ** are either constant throughout the lifetime of the pager, or else
34218   ** used to store configuration parameters that affect the way the pager 
34219   ** operates.
34220   **
34221   ** The 'state' variable is described in more detail along with the
34222   ** descriptions of the values it may take - PAGER_UNLOCK etc. Many of the
34223   ** other variables in this block are described in the comment directly 
34224   ** above this class definition.
34225   */
34226   u8 state;                   /* PAGER_UNLOCK, _SHARED, _RESERVED, etc. */
34227   u8 dbModified;              /* True if there are any changes to the Db */
34228   u8 needSync;                /* True if an fsync() is needed on the journal */
34229   u8 journalStarted;          /* True if header of journal is synced */
34230   u8 changeCountDone;         /* Set after incrementing the change-counter */
34231   u8 setMaster;               /* True if a m-j name has been written to jrnl */
34232   u8 doNotSpill;              /* Do not spill the cache when non-zero */
34233   u8 doNotSyncSpill;          /* Do not do a spill that requires jrnl sync */
34234   u8 dbSizeValid;             /* Set when dbSize is correct */
34235   u8 subjInMemory;            /* True to use in-memory sub-journals */
34236   Pgno dbSize;                /* Number of pages in the database */
34237   Pgno dbOrigSize;            /* dbSize before the current transaction */
34238   Pgno dbFileSize;            /* Number of pages in the database file */
34239   int errCode;                /* One of several kinds of errors */
34240   int nRec;                   /* Pages journalled since last j-header written */
34241   u32 cksumInit;              /* Quasi-random value added to every checksum */
34242   u32 nSubRec;                /* Number of records written to sub-journal */
34243   Bitvec *pInJournal;         /* One bit for each page in the database file */
34244   sqlite3_file *fd;           /* File descriptor for database */
34245   sqlite3_file *jfd;          /* File descriptor for main journal */
34246   sqlite3_file *sjfd;         /* File descriptor for sub-journal */
34247   i64 journalOff;             /* Current write offset in the journal file */
34248   i64 journalHdr;             /* Byte offset to previous journal header */
34249   i64 journalSizeLimit;       /* Size limit for persistent journal files */
34250   PagerSavepoint *aSavepoint; /* Array of active savepoints */
34251   int nSavepoint;             /* Number of elements in aSavepoint[] */
34252   char dbFileVers[16];        /* Changes whenever database file changes */
34253   u32 sectorSize;             /* Assumed sector size during rollback */
34254
34255   u16 nExtra;                 /* Add this many bytes to each in-memory page */
34256   i16 nReserve;               /* Number of unused bytes at end of each page */
34257   u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
34258   int pageSize;               /* Number of bytes in a page */
34259   Pgno mxPgno;                /* Maximum allowed size of the database */
34260   char *zFilename;            /* Name of the database file */
34261   char *zJournal;             /* Name of the journal file */
34262   int (*xBusyHandler)(void*); /* Function to call when busy */
34263   void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
34264 #ifdef SQLITE_TEST
34265   int nHit, nMiss;            /* Cache hits and missing */
34266   int nRead, nWrite;          /* Database pages read/written */
34267 #endif
34268   void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
34269 #ifdef SQLITE_HAS_CODEC
34270   void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
34271   void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
34272   void (*xCodecFree)(void*);             /* Destructor for the codec */
34273   void *pCodec;               /* First argument to xCodec... methods */
34274 #endif
34275   char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
34276   PCache *pPCache;            /* Pointer to page cache object */
34277   sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
34278 #ifndef SQLITE_OMIT_WAL
34279   Wal *pWal;                  /* Write-ahead log used by "journal_mode=wal" */
34280   char *zWal;                 /* File name for write-ahead log */
34281 #endif
34282 };
34283
34284 /*
34285 ** The following global variables hold counters used for
34286 ** testing purposes only.  These variables do not exist in
34287 ** a non-testing build.  These variables are not thread-safe.
34288 */
34289 #ifdef SQLITE_TEST
34290 SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
34291 SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
34292 SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
34293 # define PAGER_INCR(v)  v++
34294 #else
34295 # define PAGER_INCR(v)
34296 #endif
34297
34298
34299
34300 /*
34301 ** Journal files begin with the following magic string.  The data
34302 ** was obtained from /dev/random.  It is used only as a sanity check.
34303 **
34304 ** Since version 2.8.0, the journal format contains additional sanity
34305 ** checking information.  If the power fails while the journal is being
34306 ** written, semi-random garbage data might appear in the journal
34307 ** file after power is restored.  If an attempt is then made
34308 ** to roll the journal back, the database could be corrupted.  The additional
34309 ** sanity checking data is an attempt to discover the garbage in the
34310 ** journal and ignore it.
34311 **
34312 ** The sanity checking information for the new journal format consists
34313 ** of a 32-bit checksum on each page of data.  The checksum covers both
34314 ** the page number and the pPager->pageSize bytes of data for the page.
34315 ** This cksum is initialized to a 32-bit random value that appears in the
34316 ** journal file right after the header.  The random initializer is important,
34317 ** because garbage data that appears at the end of a journal is likely
34318 ** data that was once in other files that have now been deleted.  If the
34319 ** garbage data came from an obsolete journal file, the checksums might
34320 ** be correct.  But by initializing the checksum to random value which
34321 ** is different for every journal, we minimize that risk.
34322 */
34323 static const unsigned char aJournalMagic[] = {
34324   0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
34325 };
34326
34327 /*
34328 ** The size of the of each page record in the journal is given by
34329 ** the following macro.
34330 */
34331 #define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
34332
34333 /*
34334 ** The journal header size for this pager. This is usually the same 
34335 ** size as a single disk sector. See also setSectorSize().
34336 */
34337 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
34338
34339 /*
34340 ** The macro MEMDB is true if we are dealing with an in-memory database.
34341 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
34342 ** the value of MEMDB will be a constant and the compiler will optimize
34343 ** out code that would never execute.
34344 */
34345 #ifdef SQLITE_OMIT_MEMORYDB
34346 # define MEMDB 0
34347 #else
34348 # define MEMDB pPager->memDb
34349 #endif
34350
34351 /*
34352 ** The maximum legal page number is (2^31 - 1).
34353 */
34354 #define PAGER_MAX_PGNO 2147483647
34355
34356 #ifndef NDEBUG 
34357 /*
34358 ** Usage:
34359 **
34360 **   assert( assert_pager_state(pPager) );
34361 */
34362 static int assert_pager_state(Pager *pPager){
34363
34364   /* A temp-file is always in PAGER_EXCLUSIVE or PAGER_SYNCED state. */
34365   assert( pPager->tempFile==0 || pPager->state>=PAGER_EXCLUSIVE );
34366
34367   /* The changeCountDone flag is always set for temp-files */
34368   assert( pPager->tempFile==0 || pPager->changeCountDone );
34369
34370   return 1;
34371 }
34372 #endif
34373
34374 /*
34375 ** Return true if it is necessary to write page *pPg into the sub-journal.
34376 ** A page needs to be written into the sub-journal if there exists one
34377 ** or more open savepoints for which:
34378 **
34379 **   * The page-number is less than or equal to PagerSavepoint.nOrig, and
34380 **   * The bit corresponding to the page-number is not set in
34381 **     PagerSavepoint.pInSavepoint.
34382 */
34383 static int subjRequiresPage(PgHdr *pPg){
34384   Pgno pgno = pPg->pgno;
34385   Pager *pPager = pPg->pPager;
34386   int i;
34387   for(i=0; i<pPager->nSavepoint; i++){
34388     PagerSavepoint *p = &pPager->aSavepoint[i];
34389     if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
34390       return 1;
34391     }
34392   }
34393   return 0;
34394 }
34395
34396 /*
34397 ** Return true if the page is already in the journal file.
34398 */
34399 static int pageInJournal(PgHdr *pPg){
34400   return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
34401 }
34402
34403 /*
34404 ** Read a 32-bit integer from the given file descriptor.  Store the integer
34405 ** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
34406 ** error code is something goes wrong.
34407 **
34408 ** All values are stored on disk as big-endian.
34409 */
34410 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
34411   unsigned char ac[4];
34412   int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
34413   if( rc==SQLITE_OK ){
34414     *pRes = sqlite3Get4byte(ac);
34415   }
34416   return rc;
34417 }
34418
34419 /*
34420 ** Write a 32-bit integer into a string buffer in big-endian byte order.
34421 */
34422 #define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
34423
34424 /*
34425 ** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
34426 ** on success or an error code is something goes wrong.
34427 */
34428 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
34429   char ac[4];
34430   put32bits(ac, val);
34431   return sqlite3OsWrite(fd, ac, 4, offset);
34432 }
34433
34434 /*
34435 ** The argument to this macro is a file descriptor (type sqlite3_file*).
34436 ** Return 0 if it is not open, or non-zero (but not 1) if it is.
34437 **
34438 ** This is so that expressions can be written as:
34439 **
34440 **   if( isOpen(pPager->jfd) ){ ...
34441 **
34442 ** instead of
34443 **
34444 **   if( pPager->jfd->pMethods ){ ...
34445 */
34446 #define isOpen(pFd) ((pFd)->pMethods)
34447
34448 /*
34449 ** If file pFd is open, call sqlite3OsUnlock() on it.
34450 */
34451 static int osUnlock(sqlite3_file *pFd, int eLock){
34452   if( !isOpen(pFd) ){
34453     return SQLITE_OK;
34454   }
34455   return sqlite3OsUnlock(pFd, eLock);
34456 }
34457
34458 /*
34459 ** This function determines whether or not the atomic-write optimization
34460 ** can be used with this pager. The optimization can be used if:
34461 **
34462 **  (a) the value returned by OsDeviceCharacteristics() indicates that
34463 **      a database page may be written atomically, and
34464 **  (b) the value returned by OsSectorSize() is less than or equal
34465 **      to the page size.
34466 **
34467 ** The optimization is also always enabled for temporary files. It is
34468 ** an error to call this function if pPager is opened on an in-memory
34469 ** database.
34470 **
34471 ** If the optimization cannot be used, 0 is returned. If it can be used,
34472 ** then the value returned is the size of the journal file when it
34473 ** contains rollback data for exactly one page.
34474 */
34475 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
34476 static int jrnlBufferSize(Pager *pPager){
34477   assert( !MEMDB );
34478   if( !pPager->tempFile ){
34479     int dc;                           /* Device characteristics */
34480     int nSector;                      /* Sector size */
34481     int szPage;                       /* Page size */
34482
34483     assert( isOpen(pPager->fd) );
34484     dc = sqlite3OsDeviceCharacteristics(pPager->fd);
34485     nSector = pPager->sectorSize;
34486     szPage = pPager->pageSize;
34487
34488     assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
34489     assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
34490     if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
34491       return 0;
34492     }
34493   }
34494
34495   return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
34496 }
34497 #endif
34498
34499 /*
34500 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
34501 ** on the cache using a hash function.  This is used for testing
34502 ** and debugging only.
34503 */
34504 #ifdef SQLITE_CHECK_PAGES
34505 /*
34506 ** Return a 32-bit hash of the page data for pPage.
34507 */
34508 static u32 pager_datahash(int nByte, unsigned char *pData){
34509   u32 hash = 0;
34510   int i;
34511   for(i=0; i<nByte; i++){
34512     hash = (hash*1039) + pData[i];
34513   }
34514   return hash;
34515 }
34516 static u32 pager_pagehash(PgHdr *pPage){
34517   return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
34518 }
34519 static void pager_set_pagehash(PgHdr *pPage){
34520   pPage->pageHash = pager_pagehash(pPage);
34521 }
34522
34523 /*
34524 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
34525 ** is defined, and NDEBUG is not defined, an assert() statement checks
34526 ** that the page is either dirty or still matches the calculated page-hash.
34527 */
34528 #define CHECK_PAGE(x) checkPage(x)
34529 static void checkPage(PgHdr *pPg){
34530   Pager *pPager = pPg->pPager;
34531   assert( !pPg->pageHash || pPager->errCode
34532       || (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
34533 }
34534
34535 #else
34536 #define pager_datahash(X,Y)  0
34537 #define pager_pagehash(X)  0
34538 #define CHECK_PAGE(x)
34539 #endif  /* SQLITE_CHECK_PAGES */
34540
34541 /*
34542 ** When this is called the journal file for pager pPager must be open.
34543 ** This function attempts to read a master journal file name from the 
34544 ** end of the file and, if successful, copies it into memory supplied 
34545 ** by the caller. See comments above writeMasterJournal() for the format
34546 ** used to store a master journal file name at the end of a journal file.
34547 **
34548 ** zMaster must point to a buffer of at least nMaster bytes allocated by
34549 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
34550 ** enough space to write the master journal name). If the master journal
34551 ** name in the journal is longer than nMaster bytes (including a
34552 ** nul-terminator), then this is handled as if no master journal name
34553 ** were present in the journal.
34554 **
34555 ** If a master journal file name is present at the end of the journal
34556 ** file, then it is copied into the buffer pointed to by zMaster. A
34557 ** nul-terminator byte is appended to the buffer following the master
34558 ** journal file name.
34559 **
34560 ** If it is determined that no master journal file name is present 
34561 ** zMaster[0] is set to 0 and SQLITE_OK returned.
34562 **
34563 ** If an error occurs while reading from the journal file, an SQLite
34564 ** error code is returned.
34565 */
34566 static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
34567   int rc;                    /* Return code */
34568   u32 len;                   /* Length in bytes of master journal name */
34569   i64 szJ;                   /* Total size in bytes of journal file pJrnl */
34570   u32 cksum;                 /* MJ checksum value read from journal */
34571   u32 u;                     /* Unsigned loop counter */
34572   unsigned char aMagic[8];   /* A buffer to hold the magic header */
34573   zMaster[0] = '\0';
34574
34575   if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
34576    || szJ<16
34577    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
34578    || len>=nMaster 
34579    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
34580    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
34581    || memcmp(aMagic, aJournalMagic, 8)
34582    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
34583   ){
34584     return rc;
34585   }
34586
34587   /* See if the checksum matches the master journal name */
34588   for(u=0; u<len; u++){
34589     cksum -= zMaster[u];
34590   }
34591   if( cksum ){
34592     /* If the checksum doesn't add up, then one or more of the disk sectors
34593     ** containing the master journal filename is corrupted. This means
34594     ** definitely roll back, so just return SQLITE_OK and report a (nul)
34595     ** master-journal filename.
34596     */
34597     len = 0;
34598   }
34599   zMaster[len] = '\0';
34600    
34601   return SQLITE_OK;
34602 }
34603
34604 /*
34605 ** Return the offset of the sector boundary at or immediately 
34606 ** following the value in pPager->journalOff, assuming a sector 
34607 ** size of pPager->sectorSize bytes.
34608 **
34609 ** i.e for a sector size of 512:
34610 **
34611 **   Pager.journalOff          Return value
34612 **   ---------------------------------------
34613 **   0                         0
34614 **   512                       512
34615 **   100                       512
34616 **   2000                      2048
34617 ** 
34618 */
34619 static i64 journalHdrOffset(Pager *pPager){
34620   i64 offset = 0;
34621   i64 c = pPager->journalOff;
34622   if( c ){
34623     offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
34624   }
34625   assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
34626   assert( offset>=c );
34627   assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
34628   return offset;
34629 }
34630
34631 /*
34632 ** The journal file must be open when this function is called.
34633 **
34634 ** This function is a no-op if the journal file has not been written to
34635 ** within the current transaction (i.e. if Pager.journalOff==0).
34636 **
34637 ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
34638 ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
34639 ** zero the 28-byte header at the start of the journal file. In either case, 
34640 ** if the pager is not in no-sync mode, sync the journal file immediately 
34641 ** after writing or truncating it.
34642 **
34643 ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
34644 ** following the truncation or zeroing described above the size of the 
34645 ** journal file in bytes is larger than this value, then truncate the
34646 ** journal file to Pager.journalSizeLimit bytes. The journal file does
34647 ** not need to be synced following this operation.
34648 **
34649 ** If an IO error occurs, abandon processing and return the IO error code.
34650 ** Otherwise, return SQLITE_OK.
34651 */
34652 static int zeroJournalHdr(Pager *pPager, int doTruncate){
34653   int rc = SQLITE_OK;                               /* Return code */
34654   assert( isOpen(pPager->jfd) );
34655   if( pPager->journalOff ){
34656     const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
34657
34658     IOTRACE(("JZEROHDR %p\n", pPager))
34659     if( doTruncate || iLimit==0 ){
34660       rc = sqlite3OsTruncate(pPager->jfd, 0);
34661     }else{
34662       static const char zeroHdr[28] = {0};
34663       rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
34664     }
34665     if( rc==SQLITE_OK && !pPager->noSync ){
34666       rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->sync_flags);
34667     }
34668
34669     /* At this point the transaction is committed but the write lock 
34670     ** is still held on the file. If there is a size limit configured for 
34671     ** the persistent journal and the journal file currently consumes more
34672     ** space than that limit allows for, truncate it now. There is no need
34673     ** to sync the file following this operation.
34674     */
34675     if( rc==SQLITE_OK && iLimit>0 ){
34676       i64 sz;
34677       rc = sqlite3OsFileSize(pPager->jfd, &sz);
34678       if( rc==SQLITE_OK && sz>iLimit ){
34679         rc = sqlite3OsTruncate(pPager->jfd, iLimit);
34680       }
34681     }
34682   }
34683   return rc;
34684 }
34685
34686 /*
34687 ** The journal file must be open when this routine is called. A journal
34688 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
34689 ** current location.
34690 **
34691 ** The format for the journal header is as follows:
34692 ** - 8 bytes: Magic identifying journal format.
34693 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
34694 ** - 4 bytes: Random number used for page hash.
34695 ** - 4 bytes: Initial database page count.
34696 ** - 4 bytes: Sector size used by the process that wrote this journal.
34697 ** - 4 bytes: Database page size.
34698 ** 
34699 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
34700 */
34701 static int writeJournalHdr(Pager *pPager){
34702   int rc = SQLITE_OK;                 /* Return code */
34703   char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
34704   u32 nHeader = pPager->pageSize;     /* Size of buffer pointed to by zHeader */
34705   u32 nWrite;                         /* Bytes of header sector written */
34706   int ii;                             /* Loop counter */
34707
34708   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
34709
34710   if( nHeader>JOURNAL_HDR_SZ(pPager) ){
34711     nHeader = JOURNAL_HDR_SZ(pPager);
34712   }
34713
34714   /* If there are active savepoints and any of them were created 
34715   ** since the most recent journal header was written, update the 
34716   ** PagerSavepoint.iHdrOffset fields now.
34717   */
34718   for(ii=0; ii<pPager->nSavepoint; ii++){
34719     if( pPager->aSavepoint[ii].iHdrOffset==0 ){
34720       pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
34721     }
34722   }
34723
34724   pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
34725
34726   /* 
34727   ** Write the nRec Field - the number of page records that follow this
34728   ** journal header. Normally, zero is written to this value at this time.
34729   ** After the records are added to the journal (and the journal synced, 
34730   ** if in full-sync mode), the zero is overwritten with the true number
34731   ** of records (see syncJournal()).
34732   **
34733   ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
34734   ** reading the journal this value tells SQLite to assume that the
34735   ** rest of the journal file contains valid page records. This assumption
34736   ** is dangerous, as if a failure occurred whilst writing to the journal
34737   ** file it may contain some garbage data. There are two scenarios
34738   ** where this risk can be ignored:
34739   **
34740   **   * When the pager is in no-sync mode. Corruption can follow a
34741   **     power failure in this case anyway.
34742   **
34743   **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
34744   **     that garbage data is never appended to the journal file.
34745   */
34746   assert( isOpen(pPager->fd) || pPager->noSync );
34747   if( (pPager->noSync) || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
34748    || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND) 
34749   ){
34750     memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
34751     put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
34752   }else{
34753     memset(zHeader, 0, sizeof(aJournalMagic)+4);
34754   }
34755
34756   /* The random check-hash initialiser */ 
34757   sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
34758   put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
34759   /* The initial database size */
34760   put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
34761   /* The assumed sector size for this process */
34762   put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
34763
34764   /* The page size */
34765   put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
34766
34767   /* Initializing the tail of the buffer is not necessary.  Everything
34768   ** works find if the following memset() is omitted.  But initializing
34769   ** the memory prevents valgrind from complaining, so we are willing to
34770   ** take the performance hit.
34771   */
34772   memset(&zHeader[sizeof(aJournalMagic)+20], 0,
34773          nHeader-(sizeof(aJournalMagic)+20));
34774
34775   /* In theory, it is only necessary to write the 28 bytes that the 
34776   ** journal header consumes to the journal file here. Then increment the 
34777   ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next 
34778   ** record is written to the following sector (leaving a gap in the file
34779   ** that will be implicitly filled in by the OS).
34780   **
34781   ** However it has been discovered that on some systems this pattern can 
34782   ** be significantly slower than contiguously writing data to the file,
34783   ** even if that means explicitly writing data to the block of 
34784   ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
34785   ** is done. 
34786   **
34787   ** The loop is required here in case the sector-size is larger than the 
34788   ** database page size. Since the zHeader buffer is only Pager.pageSize
34789   ** bytes in size, more than one call to sqlite3OsWrite() may be required
34790   ** to populate the entire journal header sector.
34791   */ 
34792   for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
34793     IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
34794     rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
34795     assert( pPager->journalHdr <= pPager->journalOff );
34796     pPager->journalOff += nHeader;
34797   }
34798
34799   return rc;
34800 }
34801
34802 /*
34803 ** The journal file must be open when this is called. A journal header file
34804 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
34805 ** file. The current location in the journal file is given by
34806 ** pPager->journalOff. See comments above function writeJournalHdr() for
34807 ** a description of the journal header format.
34808 **
34809 ** If the header is read successfully, *pNRec is set to the number of
34810 ** page records following this header and *pDbSize is set to the size of the
34811 ** database before the transaction began, in pages. Also, pPager->cksumInit
34812 ** is set to the value read from the journal header. SQLITE_OK is returned
34813 ** in this case.
34814 **
34815 ** If the journal header file appears to be corrupted, SQLITE_DONE is
34816 ** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
34817 ** cannot be read from the journal file an error code is returned.
34818 */
34819 static int readJournalHdr(
34820   Pager *pPager,               /* Pager object */
34821   int isHot,
34822   i64 journalSize,             /* Size of the open journal file in bytes */
34823   u32 *pNRec,                  /* OUT: Value read from the nRec field */
34824   u32 *pDbSize                 /* OUT: Value of original database size field */
34825 ){
34826   int rc;                      /* Return code */
34827   unsigned char aMagic[8];     /* A buffer to hold the magic header */
34828   i64 iHdrOff;                 /* Offset of journal header being read */
34829
34830   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
34831
34832   /* Advance Pager.journalOff to the start of the next sector. If the
34833   ** journal file is too small for there to be a header stored at this
34834   ** point, return SQLITE_DONE.
34835   */
34836   pPager->journalOff = journalHdrOffset(pPager);
34837   if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
34838     return SQLITE_DONE;
34839   }
34840   iHdrOff = pPager->journalOff;
34841
34842   /* Read in the first 8 bytes of the journal header. If they do not match
34843   ** the  magic string found at the start of each journal header, return
34844   ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
34845   ** proceed.
34846   */
34847   if( isHot || iHdrOff!=pPager->journalHdr ){
34848     rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
34849     if( rc ){
34850       return rc;
34851     }
34852     if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
34853       return SQLITE_DONE;
34854     }
34855   }
34856
34857   /* Read the first three 32-bit fields of the journal header: The nRec
34858   ** field, the checksum-initializer and the database size at the start
34859   ** of the transaction. Return an error code if anything goes wrong.
34860   */
34861   if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
34862    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
34863    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
34864   ){
34865     return rc;
34866   }
34867
34868   if( pPager->journalOff==0 ){
34869     u32 iPageSize;               /* Page-size field of journal header */
34870     u32 iSectorSize;             /* Sector-size field of journal header */
34871     u16 iPageSize16;             /* Copy of iPageSize in 16-bit variable */
34872
34873     /* Read the page-size and sector-size journal header fields. */
34874     if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
34875      || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
34876     ){
34877       return rc;
34878     }
34879
34880     /* Check that the values read from the page-size and sector-size fields
34881     ** are within range. To be 'in range', both values need to be a power
34882     ** of two greater than or equal to 512 or 32, and not greater than their 
34883     ** respective compile time maximum limits.
34884     */
34885     if( iPageSize<512                  || iSectorSize<32
34886      || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
34887      || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0 
34888     ){
34889       /* If the either the page-size or sector-size in the journal-header is 
34890       ** invalid, then the process that wrote the journal-header must have 
34891       ** crashed before the header was synced. In this case stop reading 
34892       ** the journal file here.
34893       */
34894       return SQLITE_DONE;
34895     }
34896
34897     /* Update the page-size to match the value read from the journal. 
34898     ** Use a testcase() macro to make sure that malloc failure within 
34899     ** PagerSetPagesize() is tested.
34900     */
34901     iPageSize16 = (u16)iPageSize;
34902     rc = sqlite3PagerSetPagesize(pPager, &iPageSize16, -1);
34903     testcase( rc!=SQLITE_OK );
34904     assert( rc!=SQLITE_OK || iPageSize16==(u16)iPageSize );
34905
34906     /* Update the assumed sector-size to match the value used by 
34907     ** the process that created this journal. If this journal was
34908     ** created by a process other than this one, then this routine
34909     ** is being called from within pager_playback(). The local value
34910     ** of Pager.sectorSize is restored at the end of that routine.
34911     */
34912     pPager->sectorSize = iSectorSize;
34913   }
34914
34915   pPager->journalOff += JOURNAL_HDR_SZ(pPager);
34916   return rc;
34917 }
34918
34919
34920 /*
34921 ** Write the supplied master journal name into the journal file for pager
34922 ** pPager at the current location. The master journal name must be the last
34923 ** thing written to a journal file. If the pager is in full-sync mode, the
34924 ** journal file descriptor is advanced to the next sector boundary before
34925 ** anything is written. The format is:
34926 **
34927 **   + 4 bytes: PAGER_MJ_PGNO.
34928 **   + N bytes: Master journal filename in utf-8.
34929 **   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
34930 **   + 4 bytes: Master journal name checksum.
34931 **   + 8 bytes: aJournalMagic[].
34932 **
34933 ** The master journal page checksum is the sum of the bytes in the master
34934 ** journal name, where each byte is interpreted as a signed 8-bit integer.
34935 **
34936 ** If zMaster is a NULL pointer (occurs for a single database transaction), 
34937 ** this call is a no-op.
34938 */
34939 static int writeMasterJournal(Pager *pPager, const char *zMaster){
34940   int rc;                          /* Return code */
34941   int nMaster;                     /* Length of string zMaster */
34942   i64 iHdrOff;                     /* Offset of header in journal file */
34943   i64 jrnlSize;                    /* Size of journal file on disk */
34944   u32 cksum = 0;                   /* Checksum of string zMaster */
34945
34946   if( !zMaster || pPager->setMaster
34947    || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
34948    || pPager->journalMode==PAGER_JOURNALMODE_OFF 
34949   ){
34950     return SQLITE_OK;
34951   }
34952   pPager->setMaster = 1;
34953   assert( isOpen(pPager->jfd) );
34954   assert( pPager->journalHdr <= pPager->journalOff );
34955
34956   /* Calculate the length in bytes and the checksum of zMaster */
34957   for(nMaster=0; zMaster[nMaster]; nMaster++){
34958     cksum += zMaster[nMaster];
34959   }
34960
34961   /* If in full-sync mode, advance to the next disk sector before writing
34962   ** the master journal name. This is in case the previous page written to
34963   ** the journal has already been synced.
34964   */
34965   if( pPager->fullSync ){
34966     pPager->journalOff = journalHdrOffset(pPager);
34967   }
34968   iHdrOff = pPager->journalOff;
34969
34970   /* Write the master journal data to the end of the journal file. If
34971   ** an error occurs, return the error code to the caller.
34972   */
34973   if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
34974    || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
34975    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
34976    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
34977    || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
34978   ){
34979     return rc;
34980   }
34981   pPager->journalOff += (nMaster+20);
34982   pPager->needSync = !pPager->noSync;
34983
34984   /* If the pager is in peristent-journal mode, then the physical 
34985   ** journal-file may extend past the end of the master-journal name
34986   ** and 8 bytes of magic data just written to the file. This is 
34987   ** dangerous because the code to rollback a hot-journal file
34988   ** will not be able to find the master-journal name to determine 
34989   ** whether or not the journal is hot. 
34990   **
34991   ** Easiest thing to do in this scenario is to truncate the journal 
34992   ** file to the required size.
34993   */ 
34994   if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
34995    && jrnlSize>pPager->journalOff
34996   ){
34997     rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
34998   }
34999   return rc;
35000 }
35001
35002 /*
35003 ** Find a page in the hash table given its page number. Return
35004 ** a pointer to the page or NULL if the requested page is not 
35005 ** already in memory.
35006 */
35007 static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
35008   PgHdr *p;                         /* Return value */
35009
35010   /* It is not possible for a call to PcacheFetch() with createFlag==0 to
35011   ** fail, since no attempt to allocate dynamic memory will be made.
35012   */
35013   (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
35014   return p;
35015 }
35016
35017 /*
35018 ** Unless the pager is in error-state, discard all in-memory pages. If
35019 ** the pager is in error-state, then this call is a no-op.
35020 **
35021 ** TODO: Why can we not reset the pager while in error state?
35022 */
35023 static void pager_reset(Pager *pPager){
35024   if( SQLITE_OK==pPager->errCode ){
35025     sqlite3BackupRestart(pPager->pBackup);
35026     sqlite3PcacheClear(pPager->pPCache);
35027     pPager->dbSizeValid = 0;
35028   }
35029 }
35030
35031 /*
35032 ** Free all structures in the Pager.aSavepoint[] array and set both
35033 ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
35034 ** if it is open and the pager is not in exclusive mode.
35035 */
35036 static void releaseAllSavepoints(Pager *pPager){
35037   int ii;               /* Iterator for looping through Pager.aSavepoint */
35038   for(ii=0; ii<pPager->nSavepoint; ii++){
35039     sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
35040   }
35041   if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
35042     sqlite3OsClose(pPager->sjfd);
35043   }
35044   sqlite3_free(pPager->aSavepoint);
35045   pPager->aSavepoint = 0;
35046   pPager->nSavepoint = 0;
35047   pPager->nSubRec = 0;
35048 }
35049
35050 /*
35051 ** Set the bit number pgno in the PagerSavepoint.pInSavepoint 
35052 ** bitvecs of all open savepoints. Return SQLITE_OK if successful
35053 ** or SQLITE_NOMEM if a malloc failure occurs.
35054 */
35055 static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
35056   int ii;                   /* Loop counter */
35057   int rc = SQLITE_OK;       /* Result code */
35058
35059   for(ii=0; ii<pPager->nSavepoint; ii++){
35060     PagerSavepoint *p = &pPager->aSavepoint[ii];
35061     if( pgno<=p->nOrig ){
35062       rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
35063       testcase( rc==SQLITE_NOMEM );
35064       assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
35065     }
35066   }
35067   return rc;
35068 }
35069
35070 /*
35071 ** Return true if this pager uses a write-ahead log instead of the usual
35072 ** rollback journal. Otherwise false.
35073 */
35074 #ifndef SQLITE_OMIT_WAL
35075 static int pagerUseWal(Pager *pPager){
35076   return (pPager->pWal!=0);
35077 }
35078 #else
35079 # define pagerUseWal(x) 0
35080 # define pagerRollbackWal(x) 0
35081 # define pagerWalFrames(v,w,x,y,z) 0
35082 # define pagerOpenWalIfPresent(z) SQLITE_OK
35083 # define pagerBeginReadTransaction(z) SQLITE_OK
35084 #endif
35085
35086 /*
35087 ** Unlock the database file. This function is a no-op if the pager
35088 ** is in exclusive mode.
35089 **
35090 ** If the pager is currently in error state, discard the contents of 
35091 ** the cache and reset the Pager structure internal state. If there is
35092 ** an open journal-file, then the next time a shared-lock is obtained
35093 ** on the pager file (by this or any other process), it will be
35094 ** treated as a hot-journal and rolled back.
35095 */
35096 static void pager_unlock(Pager *pPager){
35097   if( !pPager->exclusiveMode ){
35098     int rc = SQLITE_OK;          /* Return code */
35099     int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
35100
35101     /* If the operating system support deletion of open files, then
35102     ** close the journal file when dropping the database lock.  Otherwise
35103     ** another connection with journal_mode=delete might delete the file
35104     ** out from under us.
35105     */
35106     assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );
35107     assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );
35108     assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );
35109     assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );
35110     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
35111     assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );
35112     if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
35113      || 1!=(pPager->journalMode & 5)
35114     ){
35115       sqlite3OsClose(pPager->jfd);
35116     }
35117
35118     sqlite3BitvecDestroy(pPager->pInJournal);
35119     pPager->pInJournal = 0;
35120     releaseAllSavepoints(pPager);
35121
35122     /* If the file is unlocked, somebody else might change it. The
35123     ** values stored in Pager.dbSize etc. might become invalid if
35124     ** this happens.  One can argue that this doesn't need to be cleared
35125     ** until the change-counter check fails in PagerSharedLock().
35126     ** Clearing the page size cache here is being conservative.
35127     */
35128     pPager->dbSizeValid = 0;
35129
35130     if( pagerUseWal(pPager) ){
35131       sqlite3WalEndReadTransaction(pPager->pWal);
35132     }else{
35133       rc = osUnlock(pPager->fd, NO_LOCK);
35134     }
35135     if( rc ){
35136       pPager->errCode = rc;
35137     }
35138     IOTRACE(("UNLOCK %p\n", pPager))
35139
35140     /* If Pager.errCode is set, the contents of the pager cache cannot be
35141     ** trusted. Now that the pager file is unlocked, the contents of the
35142     ** cache can be discarded and the error code safely cleared.
35143     */
35144     if( pPager->errCode ){
35145       if( rc==SQLITE_OK ){
35146         pPager->errCode = SQLITE_OK;
35147       }
35148       pager_reset(pPager);
35149     }
35150
35151     pPager->changeCountDone = 0;
35152     pPager->state = PAGER_UNLOCK;
35153     pPager->dbModified = 0;
35154   }
35155 }
35156
35157 /*
35158 ** This function should be called when an IOERR, CORRUPT or FULL error
35159 ** may have occurred. The first argument is a pointer to the pager 
35160 ** structure, the second the error-code about to be returned by a pager 
35161 ** API function. The value returned is a copy of the second argument 
35162 ** to this function. 
35163 **
35164 ** If the second argument is SQLITE_IOERR, SQLITE_CORRUPT, or SQLITE_FULL
35165 ** the error becomes persistent. Until the persistent error is cleared,
35166 ** subsequent API calls on this Pager will immediately return the same 
35167 ** error code.
35168 **
35169 ** A persistent error indicates that the contents of the pager-cache 
35170 ** cannot be trusted. This state can be cleared by completely discarding 
35171 ** the contents of the pager-cache. If a transaction was active when
35172 ** the persistent error occurred, then the rollback journal may need
35173 ** to be replayed to restore the contents of the database file (as if
35174 ** it were a hot-journal).
35175 */
35176 static int pager_error(Pager *pPager, int rc){
35177   int rc2 = rc & 0xff;
35178   assert( rc==SQLITE_OK || !MEMDB );
35179   assert(
35180        pPager->errCode==SQLITE_FULL ||
35181        pPager->errCode==SQLITE_OK ||
35182        (pPager->errCode & 0xff)==SQLITE_IOERR
35183   );
35184   if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
35185     pPager->errCode = rc;
35186   }
35187   return rc;
35188 }
35189
35190 /*
35191 ** Execute a rollback if a transaction is active and unlock the 
35192 ** database file. 
35193 **
35194 ** If the pager has already entered the error state, do not attempt 
35195 ** the rollback at this time. Instead, pager_unlock() is called. The
35196 ** call to pager_unlock() will discard all in-memory pages, unlock
35197 ** the database file and clear the error state. If this means that
35198 ** there is a hot-journal left in the file-system, the next connection
35199 ** to obtain a shared lock on the pager (which may be this one) will
35200 ** roll it back.
35201 **
35202 ** If the pager has not already entered the error state, but an IO or
35203 ** malloc error occurs during a rollback, then this will itself cause 
35204 ** the pager to enter the error state. Which will be cleared by the
35205 ** call to pager_unlock(), as described above.
35206 */
35207 static void pagerUnlockAndRollback(Pager *pPager){
35208   if( pPager->errCode==SQLITE_OK && pPager->state>=PAGER_RESERVED ){
35209     sqlite3BeginBenignMalloc();
35210     sqlite3PagerRollback(pPager);
35211     sqlite3EndBenignMalloc();
35212   }
35213   pager_unlock(pPager);
35214 }
35215
35216 /*
35217 ** This routine ends a transaction. A transaction is usually ended by 
35218 ** either a COMMIT or a ROLLBACK operation. This routine may be called 
35219 ** after rollback of a hot-journal, or if an error occurs while opening
35220 ** the journal file or writing the very first journal-header of a
35221 ** database transaction.
35222 ** 
35223 ** If the pager is in PAGER_SHARED or PAGER_UNLOCK state when this
35224 ** routine is called, it is a no-op (returns SQLITE_OK).
35225 **
35226 ** Otherwise, any active savepoints are released.
35227 **
35228 ** If the journal file is open, then it is "finalized". Once a journal 
35229 ** file has been finalized it is not possible to use it to roll back a 
35230 ** transaction. Nor will it be considered to be a hot-journal by this
35231 ** or any other database connection. Exactly how a journal is finalized
35232 ** depends on whether or not the pager is running in exclusive mode and
35233 ** the current journal-mode (Pager.journalMode value), as follows:
35234 **
35235 **   journalMode==MEMORY
35236 **     Journal file descriptor is simply closed. This destroys an 
35237 **     in-memory journal.
35238 **
35239 **   journalMode==TRUNCATE
35240 **     Journal file is truncated to zero bytes in size.
35241 **
35242 **   journalMode==PERSIST
35243 **     The first 28 bytes of the journal file are zeroed. This invalidates
35244 **     the first journal header in the file, and hence the entire journal
35245 **     file. An invalid journal file cannot be rolled back.
35246 **
35247 **   journalMode==DELETE
35248 **     The journal file is closed and deleted using sqlite3OsDelete().
35249 **
35250 **     If the pager is running in exclusive mode, this method of finalizing
35251 **     the journal file is never used. Instead, if the journalMode is
35252 **     DELETE and the pager is in exclusive mode, the method described under
35253 **     journalMode==PERSIST is used instead.
35254 **
35255 ** After the journal is finalized, if running in non-exclusive mode, the
35256 ** pager moves to PAGER_SHARED state (and downgrades the lock on the
35257 ** database file accordingly).
35258 **
35259 ** If the pager is running in exclusive mode and is in PAGER_SYNCED state,
35260 ** it moves to PAGER_EXCLUSIVE. No locks are downgraded when running in
35261 ** exclusive mode.
35262 **
35263 ** SQLITE_OK is returned if no error occurs. If an error occurs during
35264 ** any of the IO operations to finalize the journal file or unlock the
35265 ** database then the IO error code is returned to the user. If the 
35266 ** operation to finalize the journal file fails, then the code still
35267 ** tries to unlock the database file if not in exclusive mode. If the
35268 ** unlock operation fails as well, then the first error code related
35269 ** to the first error encountered (the journal finalization one) is
35270 ** returned.
35271 */
35272 static int pager_end_transaction(Pager *pPager, int hasMaster){
35273   int rc = SQLITE_OK;      /* Error code from journal finalization operation */
35274   int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
35275
35276   if( pPager->state<PAGER_RESERVED ){
35277     return SQLITE_OK;
35278   }
35279   releaseAllSavepoints(pPager);
35280
35281   assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
35282   if( isOpen(pPager->jfd) ){
35283     assert( !pagerUseWal(pPager) );
35284
35285     /* Finalize the journal file. */
35286     if( sqlite3IsMemJournal(pPager->jfd) ){
35287       assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
35288       sqlite3OsClose(pPager->jfd);
35289     }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
35290       if( pPager->journalOff==0 ){
35291         rc = SQLITE_OK;
35292       }else{
35293         rc = sqlite3OsTruncate(pPager->jfd, 0);
35294       }
35295       pPager->journalOff = 0;
35296       pPager->journalStarted = 0;
35297     }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
35298       || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
35299     ){
35300       rc = zeroJournalHdr(pPager, hasMaster);
35301       pager_error(pPager, rc);
35302       pPager->journalOff = 0;
35303       pPager->journalStarted = 0;
35304     }else{
35305       /* This branch may be executed with Pager.journalMode==MEMORY if
35306       ** a hot-journal was just rolled back. In this case the journal
35307       ** file should be closed and deleted. If this connection writes to
35308       ** the database file, it will do so using an in-memory journal. 
35309       */
35310       assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE 
35311            || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
35312            || pPager->journalMode==PAGER_JOURNALMODE_WAL 
35313       );
35314       sqlite3OsClose(pPager->jfd);
35315       if( !pPager->tempFile ){
35316         rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
35317       }
35318     }
35319
35320 #ifdef SQLITE_CHECK_PAGES
35321     sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
35322 #endif
35323   }
35324   sqlite3BitvecDestroy(pPager->pInJournal);
35325   pPager->pInJournal = 0;
35326   pPager->nRec = 0;
35327   sqlite3PcacheCleanAll(pPager->pPCache);
35328
35329   if( pagerUseWal(pPager) ){
35330     rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
35331     assert( rc2==SQLITE_OK );
35332     pPager->state = PAGER_SHARED;
35333
35334     /* If the connection was in locking_mode=exclusive mode but is no longer,
35335     ** drop the EXCLUSIVE lock held on the database file.
35336     */
35337     if( !pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, 0) ){
35338       rc2 = osUnlock(pPager->fd, SHARED_LOCK);
35339     }
35340   }else if( !pPager->exclusiveMode ){
35341     rc2 = osUnlock(pPager->fd, SHARED_LOCK);
35342     pPager->state = PAGER_SHARED;
35343     pPager->changeCountDone = 0;
35344   }else if( pPager->state==PAGER_SYNCED ){
35345     pPager->state = PAGER_EXCLUSIVE;
35346   }
35347   pPager->setMaster = 0;
35348   pPager->needSync = 0;
35349   pPager->dbModified = 0;
35350
35351   /* TODO: Is this optimal? Why is the db size invalidated here 
35352   ** when the database file is not unlocked? */
35353   pPager->dbOrigSize = 0;
35354   sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
35355   if( !MEMDB ){
35356     pPager->dbSizeValid = 0;
35357   }
35358
35359   return (rc==SQLITE_OK?rc2:rc);
35360 }
35361
35362 /*
35363 ** Parameter aData must point to a buffer of pPager->pageSize bytes
35364 ** of data. Compute and return a checksum based ont the contents of the 
35365 ** page of data and the current value of pPager->cksumInit.
35366 **
35367 ** This is not a real checksum. It is really just the sum of the 
35368 ** random initial value (pPager->cksumInit) and every 200th byte
35369 ** of the page data, starting with byte offset (pPager->pageSize%200).
35370 ** Each byte is interpreted as an 8-bit unsigned integer.
35371 **
35372 ** Changing the formula used to compute this checksum results in an
35373 ** incompatible journal file format.
35374 **
35375 ** If journal corruption occurs due to a power failure, the most likely 
35376 ** scenario is that one end or the other of the record will be changed. 
35377 ** It is much less likely that the two ends of the journal record will be
35378 ** correct and the middle be corrupt.  Thus, this "checksum" scheme,
35379 ** though fast and simple, catches the mostly likely kind of corruption.
35380 */
35381 static u32 pager_cksum(Pager *pPager, const u8 *aData){
35382   u32 cksum = pPager->cksumInit;         /* Checksum value to return */
35383   int i = pPager->pageSize-200;          /* Loop counter */
35384   while( i>0 ){
35385     cksum += aData[i];
35386     i -= 200;
35387   }
35388   return cksum;
35389 }
35390
35391 /*
35392 ** Report the current page size and number of reserved bytes back
35393 ** to the codec.
35394 */
35395 #ifdef SQLITE_HAS_CODEC
35396 static void pagerReportSize(Pager *pPager){
35397   if( pPager->xCodecSizeChng ){
35398     pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
35399                            (int)pPager->nReserve);
35400   }
35401 }
35402 #else
35403 # define pagerReportSize(X)     /* No-op if we do not support a codec */
35404 #endif
35405
35406 /*
35407 ** Read a single page from either the journal file (if isMainJrnl==1) or
35408 ** from the sub-journal (if isMainJrnl==0) and playback that page.
35409 ** The page begins at offset *pOffset into the file. The *pOffset
35410 ** value is increased to the start of the next page in the journal.
35411 **
35412 ** The isMainJrnl flag is true if this is the main rollback journal and
35413 ** false for the statement journal.  The main rollback journal uses
35414 ** checksums - the statement journal does not.
35415 **
35416 ** If the page number of the page record read from the (sub-)journal file
35417 ** is greater than the current value of Pager.dbSize, then playback is
35418 ** skipped and SQLITE_OK is returned.
35419 **
35420 ** If pDone is not NULL, then it is a record of pages that have already
35421 ** been played back.  If the page at *pOffset has already been played back
35422 ** (if the corresponding pDone bit is set) then skip the playback.
35423 ** Make sure the pDone bit corresponding to the *pOffset page is set
35424 ** prior to returning.
35425 **
35426 ** If the page record is successfully read from the (sub-)journal file
35427 ** and played back, then SQLITE_OK is returned. If an IO error occurs
35428 ** while reading the record from the (sub-)journal file or while writing
35429 ** to the database file, then the IO error code is returned. If data
35430 ** is successfully read from the (sub-)journal file but appears to be
35431 ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
35432 ** two circumstances:
35433 ** 
35434 **   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
35435 **   * If the record is being rolled back from the main journal file
35436 **     and the checksum field does not match the record content.
35437 **
35438 ** Neither of these two scenarios are possible during a savepoint rollback.
35439 **
35440 ** If this is a savepoint rollback, then memory may have to be dynamically
35441 ** allocated by this function. If this is the case and an allocation fails,
35442 ** SQLITE_NOMEM is returned.
35443 */
35444 static int pager_playback_one_page(
35445   Pager *pPager,                /* The pager being played back */
35446   i64 *pOffset,                 /* Offset of record to playback */
35447   Bitvec *pDone,                /* Bitvec of pages already played back */
35448   int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
35449   int isSavepnt                 /* True for a savepoint rollback */
35450 ){
35451   int rc;
35452   PgHdr *pPg;                   /* An existing page in the cache */
35453   Pgno pgno;                    /* The page number of a page in journal */
35454   u32 cksum;                    /* Checksum used for sanity checking */
35455   char *aData;                  /* Temporary storage for the page */
35456   sqlite3_file *jfd;            /* The file descriptor for the journal file */
35457   int isSynced;                 /* True if journal page is synced */
35458
35459   assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
35460   assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
35461   assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
35462   assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
35463
35464   aData = pPager->pTmpSpace;
35465   assert( aData );         /* Temp storage must have already been allocated */
35466   assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
35467
35468   /* Read the page number and page data from the journal or sub-journal
35469   ** file. Return an error code to the caller if an IO error occurs.
35470   */
35471   jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
35472   rc = read32bits(jfd, *pOffset, &pgno);
35473   if( rc!=SQLITE_OK ) return rc;
35474   rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
35475   if( rc!=SQLITE_OK ) return rc;
35476   *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
35477
35478   /* Sanity checking on the page.  This is more important that I originally
35479   ** thought.  If a power failure occurs while the journal is being written,
35480   ** it could cause invalid data to be written into the journal.  We need to
35481   ** detect this invalid data (with high probability) and ignore it.
35482   */
35483   if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
35484     assert( !isSavepnt );
35485     return SQLITE_DONE;
35486   }
35487   if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
35488     return SQLITE_OK;
35489   }
35490   if( isMainJrnl ){
35491     rc = read32bits(jfd, (*pOffset)-4, &cksum);
35492     if( rc ) return rc;
35493     if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
35494       return SQLITE_DONE;
35495     }
35496   }
35497
35498   /* If this page has already been played by before during the current
35499   ** rollback, then don't bother to play it back again.
35500   */
35501   if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
35502     return rc;
35503   }
35504   assert( pPager->state==PAGER_RESERVED || pPager->state>=PAGER_EXCLUSIVE );
35505
35506   /* When playing back page 1, restore the nReserve setting
35507   */
35508   if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
35509     pPager->nReserve = ((u8*)aData)[20];
35510     pagerReportSize(pPager);
35511   }
35512
35513   /* If the pager is in RESERVED state, then there must be a copy of this
35514   ** page in the pager cache. In this case just update the pager cache,
35515   ** not the database file. The page is left marked dirty in this case.
35516   **
35517   ** An exception to the above rule: If the database is in no-sync mode
35518   ** and a page is moved during an incremental vacuum then the page may
35519   ** not be in the pager cache. Later: if a malloc() or IO error occurs
35520   ** during a Movepage() call, then the page may not be in the cache
35521   ** either. So the condition described in the above paragraph is not
35522   ** assert()able.
35523   **
35524   ** If in EXCLUSIVE state, then we update the pager cache if it exists
35525   ** and the main file. The page is then marked not dirty.
35526   **
35527   ** Ticket #1171:  The statement journal might contain page content that is
35528   ** different from the page content at the start of the transaction.
35529   ** This occurs when a page is changed prior to the start of a statement
35530   ** then changed again within the statement.  When rolling back such a
35531   ** statement we must not write to the original database unless we know
35532   ** for certain that original page contents are synced into the main rollback
35533   ** journal.  Otherwise, a power loss might leave modified data in the
35534   ** database file without an entry in the rollback journal that can
35535   ** restore the database to its original form.  Two conditions must be
35536   ** met before writing to the database files. (1) the database must be
35537   ** locked.  (2) we know that the original page content is fully synced
35538   ** in the main journal either because the page is not in cache or else
35539   ** the page is marked as needSync==0.
35540   **
35541   ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
35542   ** is possible to fail a statement on a database that does not yet exist.
35543   ** Do not attempt to write if database file has never been opened.
35544   */
35545   if( pagerUseWal(pPager) ){
35546     pPg = 0;
35547   }else{
35548     pPg = pager_lookup(pPager, pgno);
35549   }
35550   assert( pPg || !MEMDB );
35551   PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
35552            PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
35553            (isMainJrnl?"main-journal":"sub-journal")
35554   ));
35555   if( isMainJrnl ){
35556     isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
35557   }else{
35558     isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
35559   }
35560   if( (pPager->state>=PAGER_EXCLUSIVE)
35561    && isOpen(pPager->fd)
35562    && isSynced
35563   ){
35564     i64 ofst = (pgno-1)*(i64)pPager->pageSize;
35565     testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
35566     assert( !pagerUseWal(pPager) );
35567     rc = sqlite3OsWrite(pPager->fd, (u8*)aData, pPager->pageSize, ofst);
35568     if( pgno>pPager->dbFileSize ){
35569       pPager->dbFileSize = pgno;
35570     }
35571     if( pPager->pBackup ){
35572       CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
35573       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
35574       CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
35575     }
35576   }else if( !isMainJrnl && pPg==0 ){
35577     /* If this is a rollback of a savepoint and data was not written to
35578     ** the database and the page is not in-memory, there is a potential
35579     ** problem. When the page is next fetched by the b-tree layer, it 
35580     ** will be read from the database file, which may or may not be 
35581     ** current. 
35582     **
35583     ** There are a couple of different ways this can happen. All are quite
35584     ** obscure. When running in synchronous mode, this can only happen 
35585     ** if the page is on the free-list at the start of the transaction, then
35586     ** populated, then moved using sqlite3PagerMovepage().
35587     **
35588     ** The solution is to add an in-memory page to the cache containing
35589     ** the data just read from the sub-journal. Mark the page as dirty 
35590     ** and if the pager requires a journal-sync, then mark the page as 
35591     ** requiring a journal-sync before it is written.
35592     */
35593     assert( isSavepnt );
35594     assert( pPager->doNotSpill==0 );
35595     pPager->doNotSpill++;
35596     rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
35597     assert( pPager->doNotSpill==1 );
35598     pPager->doNotSpill--;
35599     if( rc!=SQLITE_OK ) return rc;
35600     pPg->flags &= ~PGHDR_NEED_READ;
35601     sqlite3PcacheMakeDirty(pPg);
35602   }
35603   if( pPg ){
35604     /* No page should ever be explicitly rolled back that is in use, except
35605     ** for page 1 which is held in use in order to keep the lock on the
35606     ** database active. However such a page may be rolled back as a result
35607     ** of an internal error resulting in an automatic call to
35608     ** sqlite3PagerRollback().
35609     */
35610     void *pData;
35611     pData = pPg->pData;
35612     memcpy(pData, (u8*)aData, pPager->pageSize);
35613     pPager->xReiniter(pPg);
35614     if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
35615       /* If the contents of this page were just restored from the main 
35616       ** journal file, then its content must be as they were when the 
35617       ** transaction was first opened. In this case we can mark the page
35618       ** as clean, since there will be no need to write it out to the
35619       ** database.
35620       **
35621       ** There is one exception to this rule. If the page is being rolled
35622       ** back as part of a savepoint (or statement) rollback from an 
35623       ** unsynced portion of the main journal file, then it is not safe
35624       ** to mark the page as clean. This is because marking the page as
35625       ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
35626       ** already in the journal file (recorded in Pager.pInJournal) and
35627       ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
35628       ** again within this transaction, it will be marked as dirty but
35629       ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
35630       ** be written out into the database file before its journal file
35631       ** segment is synced. If a crash occurs during or following this,
35632       ** database corruption may ensue.
35633       */
35634       assert( !pagerUseWal(pPager) );
35635       sqlite3PcacheMakeClean(pPg);
35636     }
35637 #ifdef SQLITE_CHECK_PAGES
35638     pPg->pageHash = pager_pagehash(pPg);
35639 #endif
35640     /* If this was page 1, then restore the value of Pager.dbFileVers.
35641     ** Do this before any decoding. */
35642     if( pgno==1 ){
35643       memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
35644     }
35645
35646     /* Decode the page just read from disk */
35647     CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
35648     sqlite3PcacheRelease(pPg);
35649   }
35650   return rc;
35651 }
35652
35653 /*
35654 ** Parameter zMaster is the name of a master journal file. A single journal
35655 ** file that referred to the master journal file has just been rolled back.
35656 ** This routine checks if it is possible to delete the master journal file,
35657 ** and does so if it is.
35658 **
35659 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not 
35660 ** available for use within this function.
35661 **
35662 ** When a master journal file is created, it is populated with the names 
35663 ** of all of its child journals, one after another, formatted as utf-8 
35664 ** encoded text. The end of each child journal file is marked with a 
35665 ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
35666 ** file for a transaction involving two databases might be:
35667 **
35668 **   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
35669 **
35670 ** A master journal file may only be deleted once all of its child 
35671 ** journals have been rolled back.
35672 **
35673 ** This function reads the contents of the master-journal file into 
35674 ** memory and loops through each of the child journal names. For
35675 ** each child journal, it checks if:
35676 **
35677 **   * if the child journal exists, and if so
35678 **   * if the child journal contains a reference to master journal 
35679 **     file zMaster
35680 **
35681 ** If a child journal can be found that matches both of the criteria
35682 ** above, this function returns without doing anything. Otherwise, if
35683 ** no such child journal can be found, file zMaster is deleted from
35684 ** the file-system using sqlite3OsDelete().
35685 **
35686 ** If an IO error within this function, an error code is returned. This
35687 ** function allocates memory by calling sqlite3Malloc(). If an allocation
35688 ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors 
35689 ** occur, SQLITE_OK is returned.
35690 **
35691 ** TODO: This function allocates a single block of memory to load
35692 ** the entire contents of the master journal file. This could be
35693 ** a couple of kilobytes or so - potentially larger than the page 
35694 ** size.
35695 */
35696 static int pager_delmaster(Pager *pPager, const char *zMaster){
35697   sqlite3_vfs *pVfs = pPager->pVfs;
35698   int rc;                   /* Return code */
35699   sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
35700   sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
35701   char *zMasterJournal = 0; /* Contents of master journal file */
35702   i64 nMasterJournal;       /* Size of master journal file */
35703   char *zJournal;           /* Pointer to one journal within MJ file */
35704   char *zMasterPtr;         /* Space to hold MJ filename from a journal file */
35705   int nMasterPtr;           /* Amount of space allocated to zMasterPtr[] */
35706
35707   /* Allocate space for both the pJournal and pMaster file descriptors.
35708   ** If successful, open the master journal file for reading.
35709   */
35710   pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
35711   pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
35712   if( !pMaster ){
35713     rc = SQLITE_NOMEM;
35714   }else{
35715     const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
35716     rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
35717   }
35718   if( rc!=SQLITE_OK ) goto delmaster_out;
35719
35720   /* Load the entire master journal file into space obtained from
35721   ** sqlite3_malloc() and pointed to by zMasterJournal.   Also obtain
35722   ** sufficient space (in zMasterPtr) to hold the names of master
35723   ** journal files extracted from regular rollback-journals.
35724   */
35725   rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
35726   if( rc!=SQLITE_OK ) goto delmaster_out;
35727   nMasterPtr = pVfs->mxPathname+1;
35728   zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
35729   if( !zMasterJournal ){
35730     rc = SQLITE_NOMEM;
35731     goto delmaster_out;
35732   }
35733   zMasterPtr = &zMasterJournal[nMasterJournal+1];
35734   rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
35735   if( rc!=SQLITE_OK ) goto delmaster_out;
35736   zMasterJournal[nMasterJournal] = 0;
35737
35738   zJournal = zMasterJournal;
35739   while( (zJournal-zMasterJournal)<nMasterJournal ){
35740     int exists;
35741     rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
35742     if( rc!=SQLITE_OK ){
35743       goto delmaster_out;
35744     }
35745     if( exists ){
35746       /* One of the journals pointed to by the master journal exists.
35747       ** Open it and check if it points at the master journal. If
35748       ** so, return without deleting the master journal file.
35749       */
35750       int c;
35751       int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
35752       rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
35753       if( rc!=SQLITE_OK ){
35754         goto delmaster_out;
35755       }
35756
35757       rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
35758       sqlite3OsClose(pJournal);
35759       if( rc!=SQLITE_OK ){
35760         goto delmaster_out;
35761       }
35762
35763       c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
35764       if( c ){
35765         /* We have a match. Do not delete the master journal file. */
35766         goto delmaster_out;
35767       }
35768     }
35769     zJournal += (sqlite3Strlen30(zJournal)+1);
35770   }
35771  
35772   sqlite3OsClose(pMaster);
35773   rc = sqlite3OsDelete(pVfs, zMaster, 0);
35774
35775 delmaster_out:
35776   sqlite3_free(zMasterJournal);
35777   if( pMaster ){
35778     sqlite3OsClose(pMaster);
35779     assert( !isOpen(pJournal) );
35780     sqlite3_free(pMaster);
35781   }
35782   return rc;
35783 }
35784
35785
35786 /*
35787 ** This function is used to change the actual size of the database 
35788 ** file in the file-system. This only happens when committing a transaction,
35789 ** or rolling back a transaction (including rolling back a hot-journal).
35790 **
35791 ** If the main database file is not open, or an exclusive lock is not
35792 ** held, this function is a no-op. Otherwise, the size of the file is
35793 ** changed to nPage pages (nPage*pPager->pageSize bytes). If the file
35794 ** on disk is currently larger than nPage pages, then use the VFS
35795 ** xTruncate() method to truncate it.
35796 **
35797 ** Or, it might might be the case that the file on disk is smaller than 
35798 ** nPage pages. Some operating system implementations can get confused if 
35799 ** you try to truncate a file to some size that is larger than it 
35800 ** currently is, so detect this case and write a single zero byte to 
35801 ** the end of the new file instead.
35802 **
35803 ** If successful, return SQLITE_OK. If an IO error occurs while modifying
35804 ** the database file, return the error code to the caller.
35805 */
35806 static int pager_truncate(Pager *pPager, Pgno nPage){
35807   int rc = SQLITE_OK;
35808   if( pPager->state>=PAGER_EXCLUSIVE && isOpen(pPager->fd) ){
35809     i64 currentSize, newSize;
35810     /* TODO: Is it safe to use Pager.dbFileSize here? */
35811     rc = sqlite3OsFileSize(pPager->fd, &currentSize);
35812     newSize = pPager->pageSize*(i64)nPage;
35813     if( rc==SQLITE_OK && currentSize!=newSize ){
35814       if( currentSize>newSize ){
35815         rc = sqlite3OsTruncate(pPager->fd, newSize);
35816       }else{
35817         rc = sqlite3OsWrite(pPager->fd, "", 1, newSize-1);
35818       }
35819       if( rc==SQLITE_OK ){
35820         pPager->dbFileSize = nPage;
35821       }
35822     }
35823   }
35824   return rc;
35825 }
35826
35827 /*
35828 ** Set the value of the Pager.sectorSize variable for the given
35829 ** pager based on the value returned by the xSectorSize method
35830 ** of the open database file. The sector size will be used used 
35831 ** to determine the size and alignment of journal header and 
35832 ** master journal pointers within created journal files.
35833 **
35834 ** For temporary files the effective sector size is always 512 bytes.
35835 **
35836 ** Otherwise, for non-temporary files, the effective sector size is
35837 ** the value returned by the xSectorSize() method rounded up to 32 if
35838 ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
35839 ** is greater than MAX_SECTOR_SIZE.
35840 */
35841 static void setSectorSize(Pager *pPager){
35842   assert( isOpen(pPager->fd) || pPager->tempFile );
35843
35844   if( !pPager->tempFile ){
35845     /* Sector size doesn't matter for temporary files. Also, the file
35846     ** may not have been opened yet, in which case the OsSectorSize()
35847     ** call will segfault.
35848     */
35849     pPager->sectorSize = sqlite3OsSectorSize(pPager->fd);
35850   }
35851   if( pPager->sectorSize<32 ){
35852     pPager->sectorSize = 512;
35853   }
35854   if( pPager->sectorSize>MAX_SECTOR_SIZE ){
35855     assert( MAX_SECTOR_SIZE>=512 );
35856     pPager->sectorSize = MAX_SECTOR_SIZE;
35857   }
35858 }
35859
35860 /*
35861 ** Playback the journal and thus restore the database file to
35862 ** the state it was in before we started making changes.  
35863 **
35864 ** The journal file format is as follows: 
35865 **
35866 **  (1)  8 byte prefix.  A copy of aJournalMagic[].
35867 **  (2)  4 byte big-endian integer which is the number of valid page records
35868 **       in the journal.  If this value is 0xffffffff, then compute the
35869 **       number of page records from the journal size.
35870 **  (3)  4 byte big-endian integer which is the initial value for the 
35871 **       sanity checksum.
35872 **  (4)  4 byte integer which is the number of pages to truncate the
35873 **       database to during a rollback.
35874 **  (5)  4 byte big-endian integer which is the sector size.  The header
35875 **       is this many bytes in size.
35876 **  (6)  4 byte big-endian integer which is the page size.
35877 **  (7)  zero padding out to the next sector size.
35878 **  (8)  Zero or more pages instances, each as follows:
35879 **        +  4 byte page number.
35880 **        +  pPager->pageSize bytes of data.
35881 **        +  4 byte checksum
35882 **
35883 ** When we speak of the journal header, we mean the first 7 items above.
35884 ** Each entry in the journal is an instance of the 8th item.
35885 **
35886 ** Call the value from the second bullet "nRec".  nRec is the number of
35887 ** valid page entries in the journal.  In most cases, you can compute the
35888 ** value of nRec from the size of the journal file.  But if a power
35889 ** failure occurred while the journal was being written, it could be the
35890 ** case that the size of the journal file had already been increased but
35891 ** the extra entries had not yet made it safely to disk.  In such a case,
35892 ** the value of nRec computed from the file size would be too large.  For
35893 ** that reason, we always use the nRec value in the header.
35894 **
35895 ** If the nRec value is 0xffffffff it means that nRec should be computed
35896 ** from the file size.  This value is used when the user selects the
35897 ** no-sync option for the journal.  A power failure could lead to corruption
35898 ** in this case.  But for things like temporary table (which will be
35899 ** deleted when the power is restored) we don't care.  
35900 **
35901 ** If the file opened as the journal file is not a well-formed
35902 ** journal file then all pages up to the first corrupted page are rolled
35903 ** back (or no pages if the journal header is corrupted). The journal file
35904 ** is then deleted and SQLITE_OK returned, just as if no corruption had
35905 ** been encountered.
35906 **
35907 ** If an I/O or malloc() error occurs, the journal-file is not deleted
35908 ** and an error code is returned.
35909 **
35910 ** The isHot parameter indicates that we are trying to rollback a journal
35911 ** that might be a hot journal.  Or, it could be that the journal is 
35912 ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
35913 ** If the journal really is hot, reset the pager cache prior rolling
35914 ** back any content.  If the journal is merely persistent, no reset is
35915 ** needed.
35916 */
35917 static int pager_playback(Pager *pPager, int isHot){
35918   sqlite3_vfs *pVfs = pPager->pVfs;
35919   i64 szJ;                 /* Size of the journal file in bytes */
35920   u32 nRec;                /* Number of Records in the journal */
35921   u32 u;                   /* Unsigned loop counter */
35922   Pgno mxPg = 0;           /* Size of the original file in pages */
35923   int rc;                  /* Result code of a subroutine */
35924   int res = 1;             /* Value returned by sqlite3OsAccess() */
35925   char *zMaster = 0;       /* Name of master journal file if any */
35926   int needPagerReset;      /* True to reset page prior to first page rollback */
35927
35928   /* Figure out how many records are in the journal.  Abort early if
35929   ** the journal is empty.
35930   */
35931   assert( isOpen(pPager->jfd) );
35932   rc = sqlite3OsFileSize(pPager->jfd, &szJ);
35933   if( rc!=SQLITE_OK || szJ==0 ){
35934     goto end_playback;
35935   }
35936
35937   /* Read the master journal name from the journal, if it is present.
35938   ** If a master journal file name is specified, but the file is not
35939   ** present on disk, then the journal is not hot and does not need to be
35940   ** played back.
35941   **
35942   ** TODO: Technically the following is an error because it assumes that
35943   ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
35944   ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
35945   **  mxPathname is 512, which is the same as the minimum allowable value
35946   ** for pageSize.
35947   */
35948   zMaster = pPager->pTmpSpace;
35949   rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
35950   if( rc==SQLITE_OK && zMaster[0] ){
35951     rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
35952   }
35953   zMaster = 0;
35954   if( rc!=SQLITE_OK || !res ){
35955     goto end_playback;
35956   }
35957   pPager->journalOff = 0;
35958   needPagerReset = isHot;
35959
35960   /* This loop terminates either when a readJournalHdr() or 
35961   ** pager_playback_one_page() call returns SQLITE_DONE or an IO error 
35962   ** occurs. 
35963   */
35964   while( 1 ){
35965     /* Read the next journal header from the journal file.  If there are
35966     ** not enough bytes left in the journal file for a complete header, or
35967     ** it is corrupted, then a process must of failed while writing it.
35968     ** This indicates nothing more needs to be rolled back.
35969     */
35970     rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
35971     if( rc!=SQLITE_OK ){ 
35972       if( rc==SQLITE_DONE ){
35973         rc = SQLITE_OK;
35974       }
35975       goto end_playback;
35976     }
35977
35978     /* If nRec is 0xffffffff, then this journal was created by a process
35979     ** working in no-sync mode. This means that the rest of the journal
35980     ** file consists of pages, there are no more journal headers. Compute
35981     ** the value of nRec based on this assumption.
35982     */
35983     if( nRec==0xffffffff ){
35984       assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
35985       nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
35986     }
35987
35988     /* If nRec is 0 and this rollback is of a transaction created by this
35989     ** process and if this is the final header in the journal, then it means
35990     ** that this part of the journal was being filled but has not yet been
35991     ** synced to disk.  Compute the number of pages based on the remaining
35992     ** size of the file.
35993     **
35994     ** The third term of the test was added to fix ticket #2565.
35995     ** When rolling back a hot journal, nRec==0 always means that the next
35996     ** chunk of the journal contains zero pages to be rolled back.  But
35997     ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
35998     ** the journal, it means that the journal might contain additional
35999     ** pages that need to be rolled back and that the number of pages 
36000     ** should be computed based on the journal file size.
36001     */
36002     if( nRec==0 && !isHot &&
36003         pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
36004       nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
36005     }
36006
36007     /* If this is the first header read from the journal, truncate the
36008     ** database file back to its original size.
36009     */
36010     if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
36011       rc = pager_truncate(pPager, mxPg);
36012       if( rc!=SQLITE_OK ){
36013         goto end_playback;
36014       }
36015       pPager->dbSize = mxPg;
36016     }
36017
36018     /* Copy original pages out of the journal and back into the 
36019     ** database file and/or page cache.
36020     */
36021     for(u=0; u<nRec; u++){
36022       if( needPagerReset ){
36023         pager_reset(pPager);
36024         needPagerReset = 0;
36025       }
36026       rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
36027       if( rc!=SQLITE_OK ){
36028         if( rc==SQLITE_DONE ){
36029           rc = SQLITE_OK;
36030           pPager->journalOff = szJ;
36031           break;
36032         }else if( rc==SQLITE_IOERR_SHORT_READ ){
36033           /* If the journal has been truncated, simply stop reading and
36034           ** processing the journal. This might happen if the journal was
36035           ** not completely written and synced prior to a crash.  In that
36036           ** case, the database should have never been written in the
36037           ** first place so it is OK to simply abandon the rollback. */
36038           rc = SQLITE_OK;
36039           goto end_playback;
36040         }else{
36041           /* If we are unable to rollback, quit and return the error
36042           ** code.  This will cause the pager to enter the error state
36043           ** so that no further harm will be done.  Perhaps the next
36044           ** process to come along will be able to rollback the database.
36045           */
36046           goto end_playback;
36047         }
36048       }
36049     }
36050   }
36051   /*NOTREACHED*/
36052   assert( 0 );
36053
36054 end_playback:
36055   /* Following a rollback, the database file should be back in its original
36056   ** state prior to the start of the transaction, so invoke the
36057   ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
36058   ** assertion that the transaction counter was modified.
36059   */
36060   assert(
36061     pPager->fd->pMethods==0 ||
36062     sqlite3OsFileControl(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0)>=SQLITE_OK
36063   );
36064
36065   /* If this playback is happening automatically as a result of an IO or 
36066   ** malloc error that occurred after the change-counter was updated but 
36067   ** before the transaction was committed, then the change-counter 
36068   ** modification may just have been reverted. If this happens in exclusive 
36069   ** mode, then subsequent transactions performed by the connection will not
36070   ** update the change-counter at all. This may lead to cache inconsistency
36071   ** problems for other processes at some point in the future. So, just
36072   ** in case this has happened, clear the changeCountDone flag now.
36073   */
36074   pPager->changeCountDone = pPager->tempFile;
36075
36076   if( rc==SQLITE_OK ){
36077     zMaster = pPager->pTmpSpace;
36078     rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
36079     testcase( rc!=SQLITE_OK );
36080   }
36081   if( rc==SQLITE_OK && pPager->noSync==0 && pPager->state>=PAGER_EXCLUSIVE ){
36082     rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
36083   }
36084   if( rc==SQLITE_OK && pPager->noSync==0 && pPager->state>=PAGER_EXCLUSIVE ){
36085     rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
36086   }
36087   if( rc==SQLITE_OK ){
36088     rc = pager_end_transaction(pPager, zMaster[0]!='\0');
36089     testcase( rc!=SQLITE_OK );
36090   }
36091   if( rc==SQLITE_OK && zMaster[0] && res ){
36092     /* If there was a master journal and this routine will return success,
36093     ** see if it is possible to delete the master journal.
36094     */
36095     rc = pager_delmaster(pPager, zMaster);
36096     testcase( rc!=SQLITE_OK );
36097   }
36098
36099   /* The Pager.sectorSize variable may have been updated while rolling
36100   ** back a journal created by a process with a different sector size
36101   ** value. Reset it to the correct value for this process.
36102   */
36103   setSectorSize(pPager);
36104   return rc;
36105 }
36106
36107
36108 /*
36109 ** Read the content for page pPg out of the database file and into 
36110 ** pPg->pData. A shared lock or greater must be held on the database
36111 ** file before this function is called.
36112 **
36113 ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
36114 ** the value read from the database file.
36115 **
36116 ** If an IO error occurs, then the IO error is returned to the caller.
36117 ** Otherwise, SQLITE_OK is returned.
36118 */
36119 static int readDbPage(PgHdr *pPg){
36120   Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
36121   Pgno pgno = pPg->pgno;       /* Page number to read */
36122   int rc = SQLITE_OK;          /* Return code */
36123   int isInWal = 0;             /* True if page is in log file */
36124   int pgsz = pPager->pageSize; /* Number of bytes to read */
36125
36126   assert( pPager->state>=PAGER_SHARED && !MEMDB );
36127   assert( isOpen(pPager->fd) );
36128
36129   if( NEVER(!isOpen(pPager->fd)) ){
36130     assert( pPager->tempFile );
36131     memset(pPg->pData, 0, pPager->pageSize);
36132     return SQLITE_OK;
36133   }
36134
36135   if( pagerUseWal(pPager) ){
36136     /* Try to pull the page from the write-ahead log. */
36137     rc = sqlite3WalRead(pPager->pWal, pgno, &isInWal, pgsz, pPg->pData);
36138   }
36139   if( rc==SQLITE_OK && !isInWal ){
36140     i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
36141     rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
36142     if( rc==SQLITE_IOERR_SHORT_READ ){
36143       rc = SQLITE_OK;
36144     }
36145   }
36146
36147   if( pgno==1 ){
36148     if( rc ){
36149       /* If the read is unsuccessful, set the dbFileVers[] to something
36150       ** that will never be a valid file version.  dbFileVers[] is a copy
36151       ** of bytes 24..39 of the database.  Bytes 28..31 should always be
36152       ** zero or the size of the database in page. Bytes 32..35 and 35..39
36153       ** should be page numbers which are never 0xffffffff.  So filling
36154       ** pPager->dbFileVers[] with all 0xff bytes should suffice.
36155       **
36156       ** For an encrypted database, the situation is more complex:  bytes
36157       ** 24..39 of the database are white noise.  But the probability of
36158       ** white noising equaling 16 bytes of 0xff is vanishingly small so
36159       ** we should still be ok.
36160       */
36161       memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
36162     }else{
36163       u8 *dbFileVers = &((u8*)pPg->pData)[24];
36164       memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
36165     }
36166   }
36167   CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
36168
36169   PAGER_INCR(sqlite3_pager_readdb_count);
36170   PAGER_INCR(pPager->nRead);
36171   IOTRACE(("PGIN %p %d\n", pPager, pgno));
36172   PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
36173                PAGERID(pPager), pgno, pager_pagehash(pPg)));
36174
36175   return rc;
36176 }
36177
36178 #ifndef SQLITE_OMIT_WAL
36179 /*
36180 ** This function is invoked once for each page that has already been 
36181 ** written into the log file when a WAL transaction is rolled back.
36182 ** Parameter iPg is the page number of said page. The pCtx argument 
36183 ** is actually a pointer to the Pager structure.
36184 **
36185 ** If page iPg is present in the cache, and has no outstanding references,
36186 ** it is discarded. Otherwise, if there are one or more outstanding
36187 ** references, the page content is reloaded from the database. If the
36188 ** attempt to reload content from the database is required and fails, 
36189 ** return an SQLite error code. Otherwise, SQLITE_OK.
36190 */
36191 static int pagerUndoCallback(void *pCtx, Pgno iPg){
36192   int rc = SQLITE_OK;
36193   Pager *pPager = (Pager *)pCtx;
36194   PgHdr *pPg;
36195
36196   pPg = sqlite3PagerLookup(pPager, iPg);
36197   if( pPg ){
36198     if( sqlite3PcachePageRefcount(pPg)==1 ){
36199       sqlite3PcacheDrop(pPg);
36200     }else{
36201       rc = readDbPage(pPg);
36202       if( rc==SQLITE_OK ){
36203         pPager->xReiniter(pPg);
36204       }
36205       sqlite3PagerUnref(pPg);
36206     }
36207   }
36208
36209   /* Normally, if a transaction is rolled back, any backup processes are
36210   ** updated as data is copied out of the rollback journal and into the
36211   ** database. This is not generally possible with a WAL database, as
36212   ** rollback involves simply truncating the log file. Therefore, if one
36213   ** or more frames have already been written to the log (and therefore 
36214   ** also copied into the backup databases) as part of this transaction,
36215   ** the backups must be restarted.
36216   */
36217   sqlite3BackupRestart(pPager->pBackup);
36218
36219   return rc;
36220 }
36221
36222 /*
36223 ** This function is called to rollback a transaction on a WAL database.
36224 */
36225 static int pagerRollbackWal(Pager *pPager){
36226   int rc;                         /* Return Code */
36227   PgHdr *pList;                   /* List of dirty pages to revert */
36228
36229   /* For all pages in the cache that are currently dirty or have already
36230   ** been written (but not committed) to the log file, do one of the 
36231   ** following:
36232   **
36233   **   + Discard the cached page (if refcount==0), or
36234   **   + Reload page content from the database (if refcount>0).
36235   */
36236   pPager->dbSize = pPager->dbOrigSize;
36237   rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
36238   pList = sqlite3PcacheDirtyList(pPager->pPCache);
36239   while( pList && rc==SQLITE_OK ){
36240     PgHdr *pNext = pList->pDirty;
36241     rc = pagerUndoCallback((void *)pPager, pList->pgno);
36242     pList = pNext;
36243   }
36244
36245   return rc;
36246 }
36247
36248 /*
36249 ** This function is a wrapper around sqlite3WalFrames(). As well as logging
36250 ** the contents of the list of pages headed by pList (connected by pDirty),
36251 ** this function notifies any active backup processes that the pages have
36252 ** changed. 
36253 */ 
36254 static int pagerWalFrames(
36255   Pager *pPager,                  /* Pager object */
36256   PgHdr *pList,                   /* List of frames to log */
36257   Pgno nTruncate,                 /* Database size after this commit */
36258   int isCommit,                   /* True if this is a commit */
36259   int sync_flags                  /* Flags to pass to OsSync() (or 0) */
36260 ){
36261   int rc;                         /* Return code */
36262
36263   assert( pPager->pWal );
36264   rc = sqlite3WalFrames(pPager->pWal, 
36265       pPager->pageSize, pList, nTruncate, isCommit, sync_flags
36266   );
36267   if( rc==SQLITE_OK && pPager->pBackup ){
36268     PgHdr *p;
36269     for(p=pList; p; p=p->pDirty){
36270       sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
36271     }
36272   }
36273   return rc;
36274 }
36275
36276 /*
36277 ** Begin a read transaction on the WAL.
36278 **
36279 ** This routine used to be called "pagerOpenSnapshot()" because it essentially
36280 ** makes a snapshot of the database at the current point in time and preserves
36281 ** that snapshot for use by the reader in spite of concurrently changes by
36282 ** other writers or checkpointers.
36283 */
36284 static int pagerBeginReadTransaction(Pager *pPager){
36285   int rc;                         /* Return code */
36286   int changed = 0;                /* True if cache must be reset */
36287
36288   assert( pagerUseWal(pPager) );
36289
36290   /* sqlite3WalEndReadTransaction() was not called for the previous
36291   ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we
36292   ** are in locking_mode=NORMAL and EndRead() was previously called,
36293   ** the duplicate call is harmless.
36294   */
36295   sqlite3WalEndReadTransaction(pPager->pWal);
36296
36297   rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
36298   if( rc==SQLITE_OK ){
36299     int dummy;
36300     if( changed ){
36301       pager_reset(pPager);
36302       assert( pPager->errCode || pPager->dbSizeValid==0 );
36303     }
36304     rc = sqlite3PagerPagecount(pPager, &dummy);
36305   }
36306   pPager->state = PAGER_SHARED;
36307
36308   return rc;
36309 }
36310
36311 /*
36312 ** Check if the *-wal file that corresponds to the database opened by pPager
36313 ** exists if the database is not empy, or verify that the *-wal file does
36314 ** not exist (by deleting it) if the database file is empty.
36315 **
36316 ** If the database is not empty and the *-wal file exists, open the pager
36317 ** in WAL mode.  If the database is empty or if no *-wal file exists and
36318 ** if no error occurs, make sure Pager.journalMode is not set to
36319 ** PAGER_JOURNALMODE_WAL.
36320 **
36321 ** Return SQLITE_OK or an error code.
36322 **
36323 ** If the WAL file is opened, also open a snapshot (read transaction).
36324 **
36325 ** The caller must hold a SHARED lock on the database file to call this
36326 ** function. Because an EXCLUSIVE lock on the db file is required to delete 
36327 ** a WAL on a none-empty database, this ensures there is no race condition 
36328 ** between the xAccess() below and an xDelete() being executed by some 
36329 ** other connection.
36330 */
36331 static int pagerOpenWalIfPresent(Pager *pPager){
36332   int rc = SQLITE_OK;
36333   if( !pPager->tempFile ){
36334     int isWal;                    /* True if WAL file exists */
36335     int nPage;                    /* Size of the database file */
36336     assert( pPager->state>=SHARED_LOCK );
36337     rc = sqlite3PagerPagecount(pPager, &nPage);
36338     if( rc ) return rc;
36339     if( nPage==0 ){
36340       rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
36341       isWal = 0;
36342     }else{
36343       rc = sqlite3OsAccess(
36344           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
36345       );
36346     }
36347     if( rc==SQLITE_OK ){
36348       if( isWal ){
36349         pager_reset(pPager);
36350         rc = sqlite3PagerOpenWal(pPager, 0);
36351         if( rc==SQLITE_OK ){
36352           rc = pagerBeginReadTransaction(pPager);
36353         }
36354       }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
36355         pPager->journalMode = PAGER_JOURNALMODE_DELETE;
36356       }
36357     }
36358   }
36359   return rc;
36360 }
36361 #endif
36362
36363 /*
36364 ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
36365 ** the entire master journal file. The case pSavepoint==NULL occurs when 
36366 ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction 
36367 ** savepoint.
36368 **
36369 ** When pSavepoint is not NULL (meaning a non-transaction savepoint is 
36370 ** being rolled back), then the rollback consists of up to three stages,
36371 ** performed in the order specified:
36372 **
36373 **   * Pages are played back from the main journal starting at byte
36374 **     offset PagerSavepoint.iOffset and continuing to 
36375 **     PagerSavepoint.iHdrOffset, or to the end of the main journal
36376 **     file if PagerSavepoint.iHdrOffset is zero.
36377 **
36378 **   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
36379 **     back starting from the journal header immediately following 
36380 **     PagerSavepoint.iHdrOffset to the end of the main journal file.
36381 **
36382 **   * Pages are then played back from the sub-journal file, starting
36383 **     with the PagerSavepoint.iSubRec and continuing to the end of
36384 **     the journal file.
36385 **
36386 ** Throughout the rollback process, each time a page is rolled back, the
36387 ** corresponding bit is set in a bitvec structure (variable pDone in the
36388 ** implementation below). This is used to ensure that a page is only
36389 ** rolled back the first time it is encountered in either journal.
36390 **
36391 ** If pSavepoint is NULL, then pages are only played back from the main
36392 ** journal file. There is no need for a bitvec in this case.
36393 **
36394 ** In either case, before playback commences the Pager.dbSize variable
36395 ** is reset to the value that it held at the start of the savepoint 
36396 ** (or transaction). No page with a page-number greater than this value
36397 ** is played back. If one is encountered it is simply skipped.
36398 */
36399 static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
36400   i64 szJ;                 /* Effective size of the main journal */
36401   i64 iHdrOff;             /* End of first segment of main-journal records */
36402   int rc = SQLITE_OK;      /* Return code */
36403   Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
36404
36405   assert( pPager->state>=PAGER_SHARED );
36406
36407   /* Allocate a bitvec to use to store the set of pages rolled back */
36408   if( pSavepoint ){
36409     pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
36410     if( !pDone ){
36411       return SQLITE_NOMEM;
36412     }
36413   }
36414
36415   /* Set the database size back to the value it was before the savepoint 
36416   ** being reverted was opened.
36417   */
36418   pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
36419   pPager->changeCountDone = pPager->tempFile;
36420
36421   if( !pSavepoint && pagerUseWal(pPager) ){
36422     return pagerRollbackWal(pPager);
36423   }
36424
36425   /* Use pPager->journalOff as the effective size of the main rollback
36426   ** journal.  The actual file might be larger than this in
36427   ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
36428   ** past pPager->journalOff is off-limits to us.
36429   */
36430   szJ = pPager->journalOff;
36431   assert( pagerUseWal(pPager)==0 || szJ==0 );
36432
36433   /* Begin by rolling back records from the main journal starting at
36434   ** PagerSavepoint.iOffset and continuing to the next journal header.
36435   ** There might be records in the main journal that have a page number
36436   ** greater than the current database size (pPager->dbSize) but those
36437   ** will be skipped automatically.  Pages are added to pDone as they
36438   ** are played back.
36439   */
36440   if( pSavepoint && !pagerUseWal(pPager) ){
36441     iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
36442     pPager->journalOff = pSavepoint->iOffset;
36443     while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
36444       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
36445     }
36446     assert( rc!=SQLITE_DONE );
36447   }else{
36448     pPager->journalOff = 0;
36449   }
36450
36451   /* Continue rolling back records out of the main journal starting at
36452   ** the first journal header seen and continuing until the effective end
36453   ** of the main journal file.  Continue to skip out-of-range pages and
36454   ** continue adding pages rolled back to pDone.
36455   */
36456   while( rc==SQLITE_OK && pPager->journalOff<szJ ){
36457     u32 ii;            /* Loop counter */
36458     u32 nJRec = 0;     /* Number of Journal Records */
36459     u32 dummy;
36460     rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
36461     assert( rc!=SQLITE_DONE );
36462
36463     /*
36464     ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
36465     ** test is related to ticket #2565.  See the discussion in the
36466     ** pager_playback() function for additional information.
36467     */
36468     if( nJRec==0 
36469      && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
36470     ){
36471       nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
36472     }
36473     for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
36474       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
36475     }
36476     assert( rc!=SQLITE_DONE );
36477   }
36478   assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
36479
36480   /* Finally,  rollback pages from the sub-journal.  Page that were
36481   ** previously rolled back out of the main journal (and are hence in pDone)
36482   ** will be skipped.  Out-of-range pages are also skipped.
36483   */
36484   if( pSavepoint ){
36485     u32 ii;            /* Loop counter */
36486     i64 offset = pSavepoint->iSubRec*(4+pPager->pageSize);
36487
36488     if( pagerUseWal(pPager) ){
36489       rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
36490     }
36491     for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
36492       assert( offset==ii*(4+pPager->pageSize) );
36493       rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
36494     }
36495     assert( rc!=SQLITE_DONE );
36496   }
36497
36498   sqlite3BitvecDestroy(pDone);
36499   if( rc==SQLITE_OK ){
36500     pPager->journalOff = szJ;
36501   }
36502
36503   return rc;
36504 }
36505
36506 /*
36507 ** Change the maximum number of in-memory pages that are allowed.
36508 */
36509 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
36510   sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
36511 }
36512
36513 /*
36514 ** Adjust the robustness of the database to damage due to OS crashes
36515 ** or power failures by changing the number of syncs()s when writing
36516 ** the rollback journal.  There are three levels:
36517 **
36518 **    OFF       sqlite3OsSync() is never called.  This is the default
36519 **              for temporary and transient files.
36520 **
36521 **    NORMAL    The journal is synced once before writes begin on the
36522 **              database.  This is normally adequate protection, but
36523 **              it is theoretically possible, though very unlikely,
36524 **              that an inopertune power failure could leave the journal
36525 **              in a state which would cause damage to the database
36526 **              when it is rolled back.
36527 **
36528 **    FULL      The journal is synced twice before writes begin on the
36529 **              database (with some additional information - the nRec field
36530 **              of the journal header - being written in between the two
36531 **              syncs).  If we assume that writing a
36532 **              single disk sector is atomic, then this mode provides
36533 **              assurance that the journal will not be corrupted to the
36534 **              point of causing damage to the database during rollback.
36535 **
36536 ** Numeric values associated with these states are OFF==1, NORMAL=2,
36537 ** and FULL=3.
36538 */
36539 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
36540 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager *pPager, int level, int bFullFsync){
36541   pPager->noSync =  (level==1 || pPager->tempFile) ?1:0;
36542   pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
36543   pPager->sync_flags = (bFullFsync?SQLITE_SYNC_FULL:SQLITE_SYNC_NORMAL);
36544   if( pPager->noSync ) pPager->needSync = 0;
36545 }
36546 #endif
36547
36548 /*
36549 ** The following global variable is incremented whenever the library
36550 ** attempts to open a temporary file.  This information is used for
36551 ** testing and analysis only.  
36552 */
36553 #ifdef SQLITE_TEST
36554 SQLITE_API int sqlite3_opentemp_count = 0;
36555 #endif
36556
36557 /*
36558 ** Open a temporary file.
36559 **
36560 ** Write the file descriptor into *pFile. Return SQLITE_OK on success 
36561 ** or some other error code if we fail. The OS will automatically 
36562 ** delete the temporary file when it is closed.
36563 **
36564 ** The flags passed to the VFS layer xOpen() call are those specified
36565 ** by parameter vfsFlags ORed with the following:
36566 **
36567 **     SQLITE_OPEN_READWRITE
36568 **     SQLITE_OPEN_CREATE
36569 **     SQLITE_OPEN_EXCLUSIVE
36570 **     SQLITE_OPEN_DELETEONCLOSE
36571 */
36572 static int pagerOpentemp(
36573   Pager *pPager,        /* The pager object */
36574   sqlite3_file *pFile,  /* Write the file descriptor here */
36575   int vfsFlags          /* Flags passed through to the VFS */
36576 ){
36577   int rc;               /* Return code */
36578
36579 #ifdef SQLITE_TEST
36580   sqlite3_opentemp_count++;  /* Used for testing and analysis only */
36581 #endif
36582
36583   vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
36584             SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
36585   rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
36586   assert( rc!=SQLITE_OK || isOpen(pFile) );
36587   return rc;
36588 }
36589
36590 /*
36591 ** Set the busy handler function.
36592 **
36593 ** The pager invokes the busy-handler if sqlite3OsLock() returns 
36594 ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
36595 ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE 
36596 ** lock. It does *not* invoke the busy handler when upgrading from
36597 ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
36598 ** (which occurs during hot-journal rollback). Summary:
36599 **
36600 **   Transition                        | Invokes xBusyHandler
36601 **   --------------------------------------------------------
36602 **   NO_LOCK       -> SHARED_LOCK      | Yes
36603 **   SHARED_LOCK   -> RESERVED_LOCK    | No
36604 **   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
36605 **   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
36606 **
36607 ** If the busy-handler callback returns non-zero, the lock is 
36608 ** retried. If it returns zero, then the SQLITE_BUSY error is
36609 ** returned to the caller of the pager API function.
36610 */
36611 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
36612   Pager *pPager,                       /* Pager object */
36613   int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
36614   void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
36615 ){  
36616   pPager->xBusyHandler = xBusyHandler;
36617   pPager->pBusyHandlerArg = pBusyHandlerArg;
36618 }
36619
36620 /*
36621 ** Change the page size used by the Pager object. The new page size 
36622 ** is passed in *pPageSize.
36623 **
36624 ** If the pager is in the error state when this function is called, it
36625 ** is a no-op. The value returned is the error state error code (i.e. 
36626 ** one of SQLITE_IOERR, SQLITE_CORRUPT or SQLITE_FULL).
36627 **
36628 ** Otherwise, if all of the following are true:
36629 **
36630 **   * the new page size (value of *pPageSize) is valid (a power 
36631 **     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
36632 **
36633 **   * there are no outstanding page references, and
36634 **
36635 **   * the database is either not an in-memory database or it is
36636 **     an in-memory database that currently consists of zero pages.
36637 **
36638 ** then the pager object page size is set to *pPageSize.
36639 **
36640 ** If the page size is changed, then this function uses sqlite3PagerMalloc() 
36641 ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt 
36642 ** fails, SQLITE_NOMEM is returned and the page size remains unchanged. 
36643 ** In all other cases, SQLITE_OK is returned.
36644 **
36645 ** If the page size is not changed, either because one of the enumerated
36646 ** conditions above is not true, the pager was in error state when this
36647 ** function was called, or because the memory allocation attempt failed, 
36648 ** then *pPageSize is set to the old, retained page size before returning.
36649 */
36650 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u16 *pPageSize, int nReserve){
36651   int rc = pPager->errCode;
36652
36653   if( rc==SQLITE_OK ){
36654     u16 pageSize = *pPageSize;
36655     assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
36656     if( (pPager->memDb==0 || pPager->dbSize==0)
36657      && sqlite3PcacheRefCount(pPager->pPCache)==0 
36658      && pageSize && pageSize!=pPager->pageSize 
36659     ){
36660       char *pNew = (char *)sqlite3PageMalloc(pageSize);
36661       if( !pNew ){
36662         rc = SQLITE_NOMEM;
36663       }else{
36664         pager_reset(pPager);
36665         pPager->pageSize = pageSize;
36666         sqlite3PageFree(pPager->pTmpSpace);
36667         pPager->pTmpSpace = pNew;
36668         sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
36669       }
36670     }
36671     *pPageSize = (u16)pPager->pageSize;
36672     if( nReserve<0 ) nReserve = pPager->nReserve;
36673     assert( nReserve>=0 && nReserve<1000 );
36674     pPager->nReserve = (i16)nReserve;
36675     pagerReportSize(pPager);
36676   }
36677   return rc;
36678 }
36679
36680 /*
36681 ** Return a pointer to the "temporary page" buffer held internally
36682 ** by the pager.  This is a buffer that is big enough to hold the
36683 ** entire content of a database page.  This buffer is used internally
36684 ** during rollback and will be overwritten whenever a rollback
36685 ** occurs.  But other modules are free to use it too, as long as
36686 ** no rollbacks are happening.
36687 */
36688 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
36689   return pPager->pTmpSpace;
36690 }
36691
36692 /*
36693 ** Attempt to set the maximum database page count if mxPage is positive. 
36694 ** Make no changes if mxPage is zero or negative.  And never reduce the
36695 ** maximum page count below the current size of the database.
36696 **
36697 ** Regardless of mxPage, return the current maximum page count.
36698 */
36699 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
36700   int nPage;
36701   if( mxPage>0 ){
36702     pPager->mxPgno = mxPage;
36703   }
36704   if( pPager->state!=PAGER_UNLOCK ){
36705     sqlite3PagerPagecount(pPager, &nPage);
36706     assert( (int)pPager->mxPgno>=nPage );
36707   }
36708   return pPager->mxPgno;
36709 }
36710
36711 /*
36712 ** The following set of routines are used to disable the simulated
36713 ** I/O error mechanism.  These routines are used to avoid simulated
36714 ** errors in places where we do not care about errors.
36715 **
36716 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
36717 ** and generate no code.
36718 */
36719 #ifdef SQLITE_TEST
36720 SQLITE_API extern int sqlite3_io_error_pending;
36721 SQLITE_API extern int sqlite3_io_error_hit;
36722 static int saved_cnt;
36723 void disable_simulated_io_errors(void){
36724   saved_cnt = sqlite3_io_error_pending;
36725   sqlite3_io_error_pending = -1;
36726 }
36727 void enable_simulated_io_errors(void){
36728   sqlite3_io_error_pending = saved_cnt;
36729 }
36730 #else
36731 # define disable_simulated_io_errors()
36732 # define enable_simulated_io_errors()
36733 #endif
36734
36735 /*
36736 ** Read the first N bytes from the beginning of the file into memory
36737 ** that pDest points to. 
36738 **
36739 ** If the pager was opened on a transient file (zFilename==""), or
36740 ** opened on a file less than N bytes in size, the output buffer is
36741 ** zeroed and SQLITE_OK returned. The rationale for this is that this 
36742 ** function is used to read database headers, and a new transient or
36743 ** zero sized database has a header than consists entirely of zeroes.
36744 **
36745 ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
36746 ** the error code is returned to the caller and the contents of the
36747 ** output buffer undefined.
36748 */
36749 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
36750   int rc = SQLITE_OK;
36751   memset(pDest, 0, N);
36752   assert( isOpen(pPager->fd) || pPager->tempFile );
36753
36754   /* This routine is only called by btree immediately after creating
36755   ** the Pager object.  There has not been an opportunity to transition
36756   ** to WAL mode yet.
36757   */
36758   assert( !pagerUseWal(pPager) );
36759
36760   if( isOpen(pPager->fd) ){
36761     IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
36762     rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
36763     if( rc==SQLITE_IOERR_SHORT_READ ){
36764       rc = SQLITE_OK;
36765     }
36766   }
36767   return rc;
36768 }
36769
36770 /*
36771 ** Return the total number of pages in the database file associated 
36772 ** with pPager. Normally, this is calculated as (<db file size>/<page-size>).
36773 ** However, if the file is between 1 and <page-size> bytes in size, then 
36774 ** this is considered a 1 page file.
36775 **
36776 ** If the pager is in error state when this function is called, then the
36777 ** error state error code is returned and *pnPage left unchanged. Or,
36778 ** if the file system has to be queried for the size of the file and
36779 ** the query attempt returns an IO error, the IO error code is returned
36780 ** and *pnPage is left unchanged.
36781 **
36782 ** Otherwise, if everything is successful, then SQLITE_OK is returned
36783 ** and *pnPage is set to the number of pages in the database.
36784 */
36785 SQLITE_PRIVATE int sqlite3PagerPagecount(Pager *pPager, int *pnPage){
36786   Pgno nPage = 0;           /* Value to return via *pnPage */
36787
36788   /* Determine the number of pages in the file. Store this in nPage. */
36789   if( pPager->dbSizeValid ){
36790     nPage = pPager->dbSize;
36791   }else{
36792     int rc;                 /* Error returned by OsFileSize() */
36793     i64 n = 0;              /* File size in bytes returned by OsFileSize() */
36794
36795     if( pagerUseWal(pPager) && pPager->state!=PAGER_UNLOCK ){
36796       sqlite3WalDbsize(pPager->pWal, &nPage);
36797     }
36798
36799     if( nPage==0 ){
36800       assert( isOpen(pPager->fd) || pPager->tempFile );
36801       if( isOpen(pPager->fd) ){
36802         if( SQLITE_OK!=(rc = sqlite3OsFileSize(pPager->fd, &n)) ){
36803           pager_error(pPager, rc);
36804           return rc;
36805         }
36806       }
36807       if( n>0 && n<pPager->pageSize ){
36808         nPage = 1;
36809       }else{
36810         nPage = (Pgno)(n / pPager->pageSize);
36811       }
36812     }
36813     if( pPager->state!=PAGER_UNLOCK ){
36814       pPager->dbSize = nPage;
36815       pPager->dbFileSize = nPage;
36816       pPager->dbSizeValid = 1;
36817     }
36818   }
36819
36820   /* If the current number of pages in the file is greater than the 
36821   ** configured maximum pager number, increase the allowed limit so
36822   ** that the file can be read.
36823   */
36824   if( nPage>pPager->mxPgno ){
36825     pPager->mxPgno = (Pgno)nPage;
36826   }
36827
36828   /* Set the output variable and return SQLITE_OK */
36829   *pnPage = nPage;
36830   return SQLITE_OK;
36831 }
36832
36833
36834 /*
36835 ** Try to obtain a lock of type locktype on the database file. If
36836 ** a similar or greater lock is already held, this function is a no-op
36837 ** (returning SQLITE_OK immediately).
36838 **
36839 ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke 
36840 ** the busy callback if the lock is currently not available. Repeat 
36841 ** until the busy callback returns false or until the attempt to 
36842 ** obtain the lock succeeds.
36843 **
36844 ** Return SQLITE_OK on success and an error code if we cannot obtain
36845 ** the lock. If the lock is obtained successfully, set the Pager.state 
36846 ** variable to locktype before returning.
36847 */
36848 static int pager_wait_on_lock(Pager *pPager, int locktype){
36849   int rc;                              /* Return code */
36850
36851   /* The OS lock values must be the same as the Pager lock values */
36852   assert( PAGER_SHARED==SHARED_LOCK );
36853   assert( PAGER_RESERVED==RESERVED_LOCK );
36854   assert( PAGER_EXCLUSIVE==EXCLUSIVE_LOCK );
36855
36856   /* If the file is currently unlocked then the size must be unknown. It
36857   ** must not have been modified at this point.
36858   */
36859   assert( pPager->state>=PAGER_SHARED || pPager->dbSizeValid==0 );
36860   assert( pPager->state>=PAGER_SHARED || pPager->dbModified==0 );
36861
36862   /* Check that this is either a no-op (because the requested lock is 
36863   ** already held, or one of the transistions that the busy-handler
36864   ** may be invoked during, according to the comment above
36865   ** sqlite3PagerSetBusyhandler().
36866   */
36867   assert( (pPager->state>=locktype)
36868        || (pPager->state==PAGER_UNLOCK && locktype==PAGER_SHARED)
36869        || (pPager->state==PAGER_RESERVED && locktype==PAGER_EXCLUSIVE)
36870   );
36871
36872   if( pPager->state>=locktype ){
36873     rc = SQLITE_OK;
36874   }else{
36875     do {
36876       rc = sqlite3OsLock(pPager->fd, locktype);
36877     }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
36878     if( rc==SQLITE_OK ){
36879       pPager->state = (u8)locktype;
36880       IOTRACE(("LOCK %p %d\n", pPager, locktype))
36881     }
36882   }
36883   return rc;
36884 }
36885
36886 /*
36887 ** Function assertTruncateConstraint(pPager) checks that one of the 
36888 ** following is true for all dirty pages currently in the page-cache:
36889 **
36890 **   a) The page number is less than or equal to the size of the 
36891 **      current database image, in pages, OR
36892 **
36893 **   b) if the page content were written at this time, it would not
36894 **      be necessary to write the current content out to the sub-journal
36895 **      (as determined by function subjRequiresPage()).
36896 **
36897 ** If the condition asserted by this function were not true, and the
36898 ** dirty page were to be discarded from the cache via the pagerStress()
36899 ** routine, pagerStress() would not write the current page content to
36900 ** the database file. If a savepoint transaction were rolled back after
36901 ** this happened, the correct behaviour would be to restore the current
36902 ** content of the page. However, since this content is not present in either
36903 ** the database file or the portion of the rollback journal and 
36904 ** sub-journal rolled back the content could not be restored and the
36905 ** database image would become corrupt. It is therefore fortunate that 
36906 ** this circumstance cannot arise.
36907 */
36908 #if defined(SQLITE_DEBUG)
36909 static void assertTruncateConstraintCb(PgHdr *pPg){
36910   assert( pPg->flags&PGHDR_DIRTY );
36911   assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
36912 }
36913 static void assertTruncateConstraint(Pager *pPager){
36914   sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
36915 }
36916 #else
36917 # define assertTruncateConstraint(pPager)
36918 #endif
36919
36920 /*
36921 ** Truncate the in-memory database file image to nPage pages. This 
36922 ** function does not actually modify the database file on disk. It 
36923 ** just sets the internal state of the pager object so that the 
36924 ** truncation will be done when the current transaction is committed.
36925 */
36926 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
36927   assert( pPager->dbSizeValid );
36928   assert( pPager->dbSize>=nPage );
36929   assert( pPager->state>=PAGER_RESERVED );
36930   pPager->dbSize = nPage;
36931   assertTruncateConstraint(pPager);
36932 }
36933
36934
36935 /*
36936 ** This function is called before attempting a hot-journal rollback. It
36937 ** syncs the journal file to disk, then sets pPager->journalHdr to the
36938 ** size of the journal file so that the pager_playback() routine knows
36939 ** that the entire journal file has been synced.
36940 **
36941 ** Syncing a hot-journal to disk before attempting to roll it back ensures 
36942 ** that if a power-failure occurs during the rollback, the process that
36943 ** attempts rollback following system recovery sees the same journal
36944 ** content as this process.
36945 **
36946 ** If everything goes as planned, SQLITE_OK is returned. Otherwise, 
36947 ** an SQLite error code.
36948 */
36949 static int pagerSyncHotJournal(Pager *pPager){
36950   int rc = SQLITE_OK;
36951   if( !pPager->noSync ){
36952     rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
36953   }
36954   if( rc==SQLITE_OK ){
36955     rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
36956   }
36957   return rc;
36958 }
36959
36960 /*
36961 ** Shutdown the page cache.  Free all memory and close all files.
36962 **
36963 ** If a transaction was in progress when this routine is called, that
36964 ** transaction is rolled back.  All outstanding pages are invalidated
36965 ** and their memory is freed.  Any attempt to use a page associated
36966 ** with this page cache after this function returns will likely
36967 ** result in a coredump.
36968 **
36969 ** This function always succeeds. If a transaction is active an attempt
36970 ** is made to roll it back. If an error occurs during the rollback 
36971 ** a hot journal may be left in the filesystem but no error is returned
36972 ** to the caller.
36973 */
36974 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
36975   u8 *pTmp = (u8 *)pPager->pTmpSpace;
36976
36977   disable_simulated_io_errors();
36978   sqlite3BeginBenignMalloc();
36979   pPager->errCode = 0;
36980   pPager->exclusiveMode = 0;
36981 #ifndef SQLITE_OMIT_WAL
36982   sqlite3WalClose(pPager->pWal,
36983     (pPager->noSync ? 0 : pPager->sync_flags), 
36984     pPager->pageSize, pTmp
36985   );
36986   pPager->pWal = 0;
36987 #endif
36988   pager_reset(pPager);
36989   if( MEMDB ){
36990     pager_unlock(pPager);
36991   }else{
36992     /* Set Pager.journalHdr to -1 for the benefit of the pager_playback() 
36993     ** call which may be made from within pagerUnlockAndRollback(). If it
36994     ** is not -1, then the unsynced portion of an open journal file may
36995     ** be played back into the database. If a power failure occurs while
36996     ** this is happening, the database may become corrupt.
36997     */
36998     if( isOpen(pPager->jfd) ){
36999       pPager->errCode = pagerSyncHotJournal(pPager);
37000     }
37001     pagerUnlockAndRollback(pPager);
37002   }
37003   sqlite3EndBenignMalloc();
37004   enable_simulated_io_errors();
37005   PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
37006   IOTRACE(("CLOSE %p\n", pPager))
37007   sqlite3OsClose(pPager->jfd);
37008   sqlite3OsClose(pPager->fd);
37009   sqlite3PageFree(pTmp);
37010   sqlite3PcacheClose(pPager->pPCache);
37011
37012 #ifdef SQLITE_HAS_CODEC
37013   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
37014 #endif
37015
37016   assert( !pPager->aSavepoint && !pPager->pInJournal );
37017   assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
37018
37019   sqlite3_free(pPager);
37020   return SQLITE_OK;
37021 }
37022
37023 #if !defined(NDEBUG) || defined(SQLITE_TEST)
37024 /*
37025 ** Return the page number for page pPg.
37026 */
37027 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
37028   return pPg->pgno;
37029 }
37030 #endif
37031
37032 /*
37033 ** Increment the reference count for page pPg.
37034 */
37035 SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
37036   sqlite3PcacheRef(pPg);
37037 }
37038
37039 /*
37040 ** Sync the journal. In other words, make sure all the pages that have
37041 ** been written to the journal have actually reached the surface of the
37042 ** disk and can be restored in the event of a hot-journal rollback.
37043 **
37044 ** If the Pager.needSync flag is not set, then this function is a
37045 ** no-op. Otherwise, the actions required depend on the journal-mode
37046 ** and the device characteristics of the the file-system, as follows:
37047 **
37048 **   * If the journal file is an in-memory journal file, no action need
37049 **     be taken.
37050 **
37051 **   * Otherwise, if the device does not support the SAFE_APPEND property,
37052 **     then the nRec field of the most recently written journal header
37053 **     is updated to contain the number of journal records that have
37054 **     been written following it. If the pager is operating in full-sync
37055 **     mode, then the journal file is synced before this field is updated.
37056 **
37057 **   * If the device does not support the SEQUENTIAL property, then 
37058 **     journal file is synced.
37059 **
37060 ** Or, in pseudo-code:
37061 **
37062 **   if( NOT <in-memory journal> ){
37063 **     if( NOT SAFE_APPEND ){
37064 **       if( <full-sync mode> ) xSync(<journal file>);
37065 **       <update nRec field>
37066 **     } 
37067 **     if( NOT SEQUENTIAL ) xSync(<journal file>);
37068 **   }
37069 **
37070 ** The Pager.needSync flag is never be set for temporary files, or any
37071 ** file operating in no-sync mode (Pager.noSync set to non-zero).
37072 **
37073 ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every 
37074 ** page currently held in memory before returning SQLITE_OK. If an IO
37075 ** error is encountered, then the IO error code is returned to the caller.
37076 */
37077 static int syncJournal(Pager *pPager){
37078   if( pPager->needSync ){
37079     assert( !pPager->tempFile );
37080     if( pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
37081       int rc;                              /* Return code */
37082       const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
37083       assert( isOpen(pPager->jfd) );
37084
37085       if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
37086         /* This block deals with an obscure problem. If the last connection
37087         ** that wrote to this database was operating in persistent-journal
37088         ** mode, then the journal file may at this point actually be larger
37089         ** than Pager.journalOff bytes. If the next thing in the journal
37090         ** file happens to be a journal-header (written as part of the
37091         ** previous connection's transaction), and a crash or power-failure 
37092         ** occurs after nRec is updated but before this connection writes 
37093         ** anything else to the journal file (or commits/rolls back its 
37094         ** transaction), then SQLite may become confused when doing the 
37095         ** hot-journal rollback following recovery. It may roll back all
37096         ** of this connections data, then proceed to rolling back the old,
37097         ** out-of-date data that follows it. Database corruption.
37098         **
37099         ** To work around this, if the journal file does appear to contain
37100         ** a valid header following Pager.journalOff, then write a 0x00
37101         ** byte to the start of it to prevent it from being recognized.
37102         **
37103         ** Variable iNextHdrOffset is set to the offset at which this
37104         ** problematic header will occur, if it exists. aMagic is used 
37105         ** as a temporary buffer to inspect the first couple of bytes of
37106         ** the potential journal header.
37107         */
37108         i64 iNextHdrOffset;
37109         u8 aMagic[8];
37110         u8 zHeader[sizeof(aJournalMagic)+4];
37111
37112         memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
37113         put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
37114
37115         iNextHdrOffset = journalHdrOffset(pPager);
37116         rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
37117         if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
37118           static const u8 zerobyte = 0;
37119           rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
37120         }
37121         if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
37122           return rc;
37123         }
37124
37125         /* Write the nRec value into the journal file header. If in
37126         ** full-synchronous mode, sync the journal first. This ensures that
37127         ** all data has really hit the disk before nRec is updated to mark
37128         ** it as a candidate for rollback.
37129         **
37130         ** This is not required if the persistent media supports the
37131         ** SAFE_APPEND property. Because in this case it is not possible 
37132         ** for garbage data to be appended to the file, the nRec field
37133         ** is populated with 0xFFFFFFFF when the journal header is written
37134         ** and never needs to be updated.
37135         */
37136         if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
37137           PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
37138           IOTRACE(("JSYNC %p\n", pPager))
37139           rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags);
37140           if( rc!=SQLITE_OK ) return rc;
37141         }
37142         IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
37143         rc = sqlite3OsWrite(
37144             pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
37145         );
37146         if( rc!=SQLITE_OK ) return rc;
37147       }
37148       if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
37149         PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
37150         IOTRACE(("JSYNC %p\n", pPager))
37151         rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags| 
37152           (pPager->sync_flags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
37153         );
37154         if( rc!=SQLITE_OK ) return rc;
37155       }
37156     }
37157
37158     /* The journal file was just successfully synced. Set Pager.needSync 
37159     ** to zero and clear the PGHDR_NEED_SYNC flag on all pagess.
37160     */
37161     pPager->needSync = 0;
37162     pPager->journalStarted = 1;
37163     pPager->journalHdr = pPager->journalOff;
37164     sqlite3PcacheClearSyncFlags(pPager->pPCache);
37165   }
37166
37167   return SQLITE_OK;
37168 }
37169
37170 /*
37171 ** The argument is the first in a linked list of dirty pages connected
37172 ** by the PgHdr.pDirty pointer. This function writes each one of the
37173 ** in-memory pages in the list to the database file. The argument may
37174 ** be NULL, representing an empty list. In this case this function is
37175 ** a no-op.
37176 **
37177 ** The pager must hold at least a RESERVED lock when this function
37178 ** is called. Before writing anything to the database file, this lock
37179 ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
37180 ** SQLITE_BUSY is returned and no data is written to the database file.
37181 ** 
37182 ** If the pager is a temp-file pager and the actual file-system file
37183 ** is not yet open, it is created and opened before any data is 
37184 ** written out.
37185 **
37186 ** Once the lock has been upgraded and, if necessary, the file opened,
37187 ** the pages are written out to the database file in list order. Writing
37188 ** a page is skipped if it meets either of the following criteria:
37189 **
37190 **   * The page number is greater than Pager.dbSize, or
37191 **   * The PGHDR_DONT_WRITE flag is set on the page.
37192 **
37193 ** If writing out a page causes the database file to grow, Pager.dbFileSize
37194 ** is updated accordingly. If page 1 is written out, then the value cached
37195 ** in Pager.dbFileVers[] is updated to match the new value stored in
37196 ** the database file.
37197 **
37198 ** If everything is successful, SQLITE_OK is returned. If an IO error 
37199 ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
37200 ** be obtained, SQLITE_BUSY is returned.
37201 */
37202 static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
37203   int rc;                              /* Return code */
37204
37205   /* At this point there may be either a RESERVED or EXCLUSIVE lock on the
37206   ** database file. If there is already an EXCLUSIVE lock, the following
37207   ** call is a no-op.
37208   **
37209   ** Moving the lock from RESERVED to EXCLUSIVE actually involves going
37210   ** through an intermediate state PENDING.   A PENDING lock prevents new
37211   ** readers from attaching to the database but is unsufficient for us to
37212   ** write.  The idea of a PENDING lock is to prevent new readers from
37213   ** coming in while we wait for existing readers to clear.
37214   **
37215   ** While the pager is in the RESERVED state, the original database file
37216   ** is unchanged and we can rollback without having to playback the
37217   ** journal into the original database file.  Once we transition to
37218   ** EXCLUSIVE, it means the database file has been changed and any rollback
37219   ** will require a journal playback.
37220   */
37221   assert( !pagerUseWal(pPager) );
37222   assert( pPager->state>=PAGER_RESERVED );
37223   rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
37224
37225   /* If the file is a temp-file has not yet been opened, open it now. It
37226   ** is not possible for rc to be other than SQLITE_OK if this branch
37227   ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
37228   */
37229   if( !isOpen(pPager->fd) ){
37230     assert( pPager->tempFile && rc==SQLITE_OK );
37231     rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
37232   }
37233
37234   /* Before the first write, give the VFS a hint of what the final
37235   ** file size will be.
37236   */
37237   assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
37238   if( rc==SQLITE_OK && pPager->dbSize>(pPager->dbOrigSize+1) ){
37239     sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
37240     sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
37241   }
37242
37243   while( rc==SQLITE_OK && pList ){
37244     Pgno pgno = pList->pgno;
37245
37246     /* If there are dirty pages in the page cache with page numbers greater
37247     ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
37248     ** make the file smaller (presumably by auto-vacuum code). Do not write
37249     ** any such pages to the file.
37250     **
37251     ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
37252     ** set (set by sqlite3PagerDontWrite()).
37253     */
37254     if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
37255       i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
37256       char *pData;                                   /* Data to write */    
37257
37258       /* Encode the database */
37259       CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
37260
37261       /* Write out the page data. */
37262       rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
37263
37264       /* If page 1 was just written, update Pager.dbFileVers to match
37265       ** the value now stored in the database file. If writing this 
37266       ** page caused the database file to grow, update dbFileSize. 
37267       */
37268       if( pgno==1 ){
37269         memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
37270       }
37271       if( pgno>pPager->dbFileSize ){
37272         pPager->dbFileSize = pgno;
37273       }
37274
37275       /* Update any backup objects copying the contents of this pager. */
37276       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
37277
37278       PAGERTRACE(("STORE %d page %d hash(%08x)\n",
37279                    PAGERID(pPager), pgno, pager_pagehash(pList)));
37280       IOTRACE(("PGOUT %p %d\n", pPager, pgno));
37281       PAGER_INCR(sqlite3_pager_writedb_count);
37282       PAGER_INCR(pPager->nWrite);
37283     }else{
37284       PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
37285     }
37286 #ifdef SQLITE_CHECK_PAGES
37287     pList->pageHash = pager_pagehash(pList);
37288 #endif
37289     pList = pList->pDirty;
37290   }
37291
37292   return rc;
37293 }
37294
37295 /*
37296 ** Ensure that the sub-journal file is open. If it is already open, this 
37297 ** function is a no-op.
37298 **
37299 ** SQLITE_OK is returned if everything goes according to plan. An 
37300 ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen() 
37301 ** fails.
37302 */
37303 static int openSubJournal(Pager *pPager){
37304   int rc = SQLITE_OK;
37305   if( !isOpen(pPager->sjfd) ){
37306     if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
37307       sqlite3MemJournalOpen(pPager->sjfd);
37308     }else{
37309       rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
37310     }
37311   }
37312   return rc;
37313 }
37314
37315 /*
37316 ** Append a record of the current state of page pPg to the sub-journal. 
37317 ** It is the callers responsibility to use subjRequiresPage() to check 
37318 ** that it is really required before calling this function.
37319 **
37320 ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
37321 ** for all open savepoints before returning.
37322 **
37323 ** This function returns SQLITE_OK if everything is successful, an IO
37324 ** error code if the attempt to write to the sub-journal fails, or 
37325 ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
37326 ** bitvec.
37327 */
37328 static int subjournalPage(PgHdr *pPg){
37329   int rc = SQLITE_OK;
37330   Pager *pPager = pPg->pPager;
37331   if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
37332
37333     /* Open the sub-journal, if it has not already been opened */
37334     assert( pPager->useJournal );
37335     assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
37336     assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
37337     assert( pagerUseWal(pPager) 
37338          || pageInJournal(pPg) 
37339          || pPg->pgno>pPager->dbOrigSize 
37340     );
37341     rc = openSubJournal(pPager);
37342
37343     /* If the sub-journal was opened successfully (or was already open),
37344     ** write the journal record into the file.  */
37345     if( rc==SQLITE_OK ){
37346       void *pData = pPg->pData;
37347       i64 offset = pPager->nSubRec*(4+pPager->pageSize);
37348       char *pData2;
37349   
37350       CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
37351       PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
37352       rc = write32bits(pPager->sjfd, offset, pPg->pgno);
37353       if( rc==SQLITE_OK ){
37354         rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
37355       }
37356     }
37357   }
37358   if( rc==SQLITE_OK ){
37359     pPager->nSubRec++;
37360     assert( pPager->nSavepoint>0 );
37361     rc = addToSavepointBitvecs(pPager, pPg->pgno);
37362   }
37363   return rc;
37364 }
37365
37366 /*
37367 ** This function is called by the pcache layer when it has reached some
37368 ** soft memory limit. The first argument is a pointer to a Pager object
37369 ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
37370 ** database). The second argument is a reference to a page that is 
37371 ** currently dirty but has no outstanding references. The page
37372 ** is always associated with the Pager object passed as the first 
37373 ** argument.
37374 **
37375 ** The job of this function is to make pPg clean by writing its contents
37376 ** out to the database file, if possible. This may involve syncing the
37377 ** journal file. 
37378 **
37379 ** If successful, sqlite3PcacheMakeClean() is called on the page and
37380 ** SQLITE_OK returned. If an IO error occurs while trying to make the
37381 ** page clean, the IO error code is returned. If the page cannot be
37382 ** made clean for some other reason, but no error occurs, then SQLITE_OK
37383 ** is returned by sqlite3PcacheMakeClean() is not called.
37384 */
37385 static int pagerStress(void *p, PgHdr *pPg){
37386   Pager *pPager = (Pager *)p;
37387   int rc = SQLITE_OK;
37388
37389   assert( pPg->pPager==pPager );
37390   assert( pPg->flags&PGHDR_DIRTY );
37391
37392   /* The doNotSyncSpill flag is set during times when doing a sync of
37393   ** journal (and adding a new header) is not allowed.  This occurs
37394   ** during calls to sqlite3PagerWrite() while trying to journal multiple
37395   ** pages belonging to the same sector.
37396   **
37397   ** The doNotSpill flag inhibits all cache spilling regardless of whether
37398   ** or not a sync is required.  This is set during a rollback.
37399   **
37400   ** Spilling is also inhibited when in an error state.
37401   */
37402   if( pPager->errCode ) return SQLITE_OK;
37403   if( pPager->doNotSpill ) return SQLITE_OK;
37404   if( pPager->doNotSyncSpill && (pPg->flags & PGHDR_NEED_SYNC)!=0 ){
37405     return SQLITE_OK;
37406   }
37407
37408   pPg->pDirty = 0;
37409   if( pagerUseWal(pPager) ){
37410     /* Write a single frame for this page to the log. */
37411     if( subjRequiresPage(pPg) ){ 
37412       rc = subjournalPage(pPg); 
37413     }
37414     if( rc==SQLITE_OK ){
37415       rc = pagerWalFrames(pPager, pPg, 0, 0, 0);
37416     }
37417   }else{
37418   
37419     /* Sync the journal file if required. */
37420     if( pPg->flags&PGHDR_NEED_SYNC ){
37421       assert( !pPager->noSync );
37422       rc = syncJournal(pPager);
37423       if( rc==SQLITE_OK && 
37424         !(pPager->journalMode==PAGER_JOURNALMODE_MEMORY) &&
37425         !(sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
37426       ){
37427         pPager->nRec = 0;
37428         rc = writeJournalHdr(pPager);
37429       }
37430     }
37431   
37432     /* If the page number of this page is larger than the current size of
37433     ** the database image, it may need to be written to the sub-journal.
37434     ** This is because the call to pager_write_pagelist() below will not
37435     ** actually write data to the file in this case.
37436     **
37437     ** Consider the following sequence of events:
37438     **
37439     **   BEGIN;
37440     **     <journal page X>
37441     **     <modify page X>
37442     **     SAVEPOINT sp;
37443     **       <shrink database file to Y pages>
37444     **       pagerStress(page X)
37445     **     ROLLBACK TO sp;
37446     **
37447     ** If (X>Y), then when pagerStress is called page X will not be written
37448     ** out to the database file, but will be dropped from the cache. Then,
37449     ** following the "ROLLBACK TO sp" statement, reading page X will read
37450     ** data from the database file. This will be the copy of page X as it
37451     ** was when the transaction started, not as it was when "SAVEPOINT sp"
37452     ** was executed.
37453     **
37454     ** The solution is to write the current data for page X into the 
37455     ** sub-journal file now (if it is not already there), so that it will
37456     ** be restored to its current value when the "ROLLBACK TO sp" is 
37457     ** executed.
37458     */
37459     if( NEVER(
37460         rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
37461     ) ){
37462       rc = subjournalPage(pPg);
37463     }
37464   
37465     /* Write the contents of the page out to the database file. */
37466     if( rc==SQLITE_OK ){
37467       rc = pager_write_pagelist(pPager, pPg);
37468     }
37469   }
37470
37471   /* Mark the page as clean. */
37472   if( rc==SQLITE_OK ){
37473     PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
37474     sqlite3PcacheMakeClean(pPg);
37475   }
37476
37477   return pager_error(pPager, rc);
37478 }
37479
37480
37481 /*
37482 ** Allocate and initialize a new Pager object and put a pointer to it
37483 ** in *ppPager. The pager should eventually be freed by passing it
37484 ** to sqlite3PagerClose().
37485 **
37486 ** The zFilename argument is the path to the database file to open.
37487 ** If zFilename is NULL then a randomly-named temporary file is created
37488 ** and used as the file to be cached. Temporary files are be deleted
37489 ** automatically when they are closed. If zFilename is ":memory:" then 
37490 ** all information is held in cache. It is never written to disk. 
37491 ** This can be used to implement an in-memory database.
37492 **
37493 ** The nExtra parameter specifies the number of bytes of space allocated
37494 ** along with each page reference. This space is available to the user
37495 ** via the sqlite3PagerGetExtra() API.
37496 **
37497 ** The flags argument is used to specify properties that affect the
37498 ** operation of the pager. It should be passed some bitwise combination
37499 ** of the PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK flags.
37500 **
37501 ** The vfsFlags parameter is a bitmask to pass to the flags parameter
37502 ** of the xOpen() method of the supplied VFS when opening files. 
37503 **
37504 ** If the pager object is allocated and the specified file opened 
37505 ** successfully, SQLITE_OK is returned and *ppPager set to point to
37506 ** the new pager object. If an error occurs, *ppPager is set to NULL
37507 ** and error code returned. This function may return SQLITE_NOMEM
37508 ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or 
37509 ** various SQLITE_IO_XXX errors.
37510 */
37511 SQLITE_PRIVATE int sqlite3PagerOpen(
37512   sqlite3_vfs *pVfs,       /* The virtual file system to use */
37513   Pager **ppPager,         /* OUT: Return the Pager structure here */
37514   const char *zFilename,   /* Name of the database file to open */
37515   int nExtra,              /* Extra bytes append to each in-memory page */
37516   int flags,               /* flags controlling this file */
37517   int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
37518   void (*xReinit)(DbPage*) /* Function to reinitialize pages */
37519 ){
37520   u8 *pPtr;
37521   Pager *pPager = 0;       /* Pager object to allocate and return */
37522   int rc = SQLITE_OK;      /* Return code */
37523   int tempFile = 0;        /* True for temp files (incl. in-memory files) */
37524   int memDb = 0;           /* True if this is an in-memory file */
37525   int readOnly = 0;        /* True if this is a read-only file */
37526   int journalFileSize;     /* Bytes to allocate for each journal fd */
37527   char *zPathname = 0;     /* Full path to database file */
37528   int nPathname = 0;       /* Number of bytes in zPathname */
37529   int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
37530   int noReadlock = (flags & PAGER_NO_READLOCK)!=0;  /* True to omit read-lock */
37531   int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
37532   u16 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
37533
37534   /* Figure out how much space is required for each journal file-handle
37535   ** (there are two of them, the main journal and the sub-journal). This
37536   ** is the maximum space required for an in-memory journal file handle 
37537   ** and a regular journal file-handle. Note that a "regular journal-handle"
37538   ** may be a wrapper capable of caching the first portion of the journal
37539   ** file in memory to implement the atomic-write optimization (see 
37540   ** source file journal.c).
37541   */
37542   if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
37543     journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
37544   }else{
37545     journalFileSize = ROUND8(sqlite3MemJournalSize());
37546   }
37547
37548   /* Set the output variable to NULL in case an error occurs. */
37549   *ppPager = 0;
37550
37551   /* Compute and store the full pathname in an allocated buffer pointed
37552   ** to by zPathname, length nPathname. Or, if this is a temporary file,
37553   ** leave both nPathname and zPathname set to 0.
37554   */
37555   if( zFilename && zFilename[0] ){
37556     nPathname = pVfs->mxPathname+1;
37557     zPathname = sqlite3Malloc(nPathname*2);
37558     if( zPathname==0 ){
37559       return SQLITE_NOMEM;
37560     }
37561 #ifndef SQLITE_OMIT_MEMORYDB
37562     if( strcmp(zFilename,":memory:")==0 ){
37563       memDb = 1;
37564       zPathname[0] = 0;
37565     }else
37566 #endif
37567     {
37568       zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
37569       rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
37570     }
37571
37572     nPathname = sqlite3Strlen30(zPathname);
37573     if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
37574       /* This branch is taken when the journal path required by
37575       ** the database being opened will be more than pVfs->mxPathname
37576       ** bytes in length. This means the database cannot be opened,
37577       ** as it will not be possible to open the journal file or even
37578       ** check for a hot-journal before reading.
37579       */
37580       rc = SQLITE_CANTOPEN_BKPT;
37581     }
37582     if( rc!=SQLITE_OK ){
37583       sqlite3_free(zPathname);
37584       return rc;
37585     }
37586   }
37587
37588   /* Allocate memory for the Pager structure, PCache object, the
37589   ** three file descriptors, the database file name and the journal 
37590   ** file name. The layout in memory is as follows:
37591   **
37592   **     Pager object                    (sizeof(Pager) bytes)
37593   **     PCache object                   (sqlite3PcacheSize() bytes)
37594   **     Database file handle            (pVfs->szOsFile bytes)
37595   **     Sub-journal file handle         (journalFileSize bytes)
37596   **     Main journal file handle        (journalFileSize bytes)
37597   **     Database file name              (nPathname+1 bytes)
37598   **     Journal file name               (nPathname+8+1 bytes)
37599   */
37600   pPtr = (u8 *)sqlite3MallocZero(
37601     ROUND8(sizeof(*pPager)) +      /* Pager structure */
37602     ROUND8(pcacheSize) +           /* PCache object */
37603     ROUND8(pVfs->szOsFile) +       /* The main db file */
37604     journalFileSize * 2 +          /* The two journal files */ 
37605     nPathname + 1 +                /* zFilename */
37606     nPathname + 8 + 1              /* zJournal */
37607 #ifndef SQLITE_OMIT_WAL
37608     + nPathname + 4 + 1              /* zWal */
37609 #endif
37610   );
37611   assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
37612   if( !pPtr ){
37613     sqlite3_free(zPathname);
37614     return SQLITE_NOMEM;
37615   }
37616   pPager =              (Pager*)(pPtr);
37617   pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
37618   pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
37619   pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
37620   pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
37621   pPager->zFilename =    (char*)(pPtr += journalFileSize);
37622   assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
37623
37624   /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
37625   if( zPathname ){
37626     pPager->zJournal =   (char*)(pPtr += nPathname + 1);
37627     memcpy(pPager->zFilename, zPathname, nPathname);
37628     memcpy(pPager->zJournal, zPathname, nPathname);
37629     memcpy(&pPager->zJournal[nPathname], "-journal", 8);
37630     if( pPager->zFilename[0]==0 ){
37631       pPager->zJournal[0] = 0;
37632     }
37633 #ifndef SQLITE_OMIT_WAL
37634     else{
37635       pPager->zWal = &pPager->zJournal[nPathname+8+1];
37636       memcpy(pPager->zWal, zPathname, nPathname);
37637       memcpy(&pPager->zWal[nPathname], "-wal", 4);
37638     }
37639 #endif
37640     sqlite3_free(zPathname);
37641   }
37642   pPager->pVfs = pVfs;
37643   pPager->vfsFlags = vfsFlags;
37644
37645   /* Open the pager file.
37646   */
37647   if( zFilename && zFilename[0] && !memDb ){
37648     int fout = 0;                    /* VFS flags returned by xOpen() */
37649     rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
37650     readOnly = (fout&SQLITE_OPEN_READONLY);
37651
37652     /* If the file was successfully opened for read/write access,
37653     ** choose a default page size in case we have to create the
37654     ** database file. The default page size is the maximum of:
37655     **
37656     **    + SQLITE_DEFAULT_PAGE_SIZE,
37657     **    + The value returned by sqlite3OsSectorSize()
37658     **    + The largest page size that can be written atomically.
37659     */
37660     if( rc==SQLITE_OK && !readOnly ){
37661       setSectorSize(pPager);
37662       assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
37663       if( szPageDflt<pPager->sectorSize ){
37664         if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
37665           szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
37666         }else{
37667           szPageDflt = (u16)pPager->sectorSize;
37668         }
37669       }
37670 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
37671       {
37672         int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
37673         int ii;
37674         assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
37675         assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
37676         assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
37677         for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
37678           if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
37679             szPageDflt = ii;
37680           }
37681         }
37682       }
37683 #endif
37684     }
37685   }else{
37686     /* If a temporary file is requested, it is not opened immediately.
37687     ** In this case we accept the default page size and delay actually
37688     ** opening the file until the first call to OsWrite().
37689     **
37690     ** This branch is also run for an in-memory database. An in-memory
37691     ** database is the same as a temp-file that is never written out to
37692     ** disk and uses an in-memory rollback journal.
37693     */ 
37694     tempFile = 1;
37695     pPager->state = PAGER_EXCLUSIVE;
37696     readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
37697   }
37698
37699   /* The following call to PagerSetPagesize() serves to set the value of 
37700   ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
37701   */
37702   if( rc==SQLITE_OK ){
37703     assert( pPager->memDb==0 );
37704     rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
37705     testcase( rc!=SQLITE_OK );
37706   }
37707
37708   /* If an error occurred in either of the blocks above, free the 
37709   ** Pager structure and close the file.
37710   */
37711   if( rc!=SQLITE_OK ){
37712     assert( !pPager->pTmpSpace );
37713     sqlite3OsClose(pPager->fd);
37714     sqlite3_free(pPager);
37715     return rc;
37716   }
37717
37718   /* Initialize the PCache object. */
37719   assert( nExtra<1000 );
37720   nExtra = ROUND8(nExtra);
37721   sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
37722                     !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
37723
37724   PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
37725   IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
37726
37727   pPager->useJournal = (u8)useJournal;
37728   pPager->noReadlock = (noReadlock && readOnly) ?1:0;
37729   /* pPager->stmtOpen = 0; */
37730   /* pPager->stmtInUse = 0; */
37731   /* pPager->nRef = 0; */
37732   pPager->dbSizeValid = (u8)memDb;
37733   /* pPager->stmtSize = 0; */
37734   /* pPager->stmtJSize = 0; */
37735   /* pPager->nPage = 0; */
37736   pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
37737   /* pPager->state = PAGER_UNLOCK; */
37738   assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
37739   /* pPager->errMask = 0; */
37740   pPager->tempFile = (u8)tempFile;
37741   assert( tempFile==PAGER_LOCKINGMODE_NORMAL 
37742           || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
37743   assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
37744   pPager->exclusiveMode = (u8)tempFile; 
37745   pPager->changeCountDone = pPager->tempFile;
37746   pPager->memDb = (u8)memDb;
37747   pPager->readOnly = (u8)readOnly;
37748   /* pPager->needSync = 0; */
37749   assert( useJournal || pPager->tempFile );
37750   pPager->noSync = pPager->tempFile;
37751   pPager->fullSync = pPager->noSync ?0:1;
37752   pPager->sync_flags = SQLITE_SYNC_NORMAL;
37753   /* pPager->pFirst = 0; */
37754   /* pPager->pFirstSynced = 0; */
37755   /* pPager->pLast = 0; */
37756   pPager->nExtra = (u16)nExtra;
37757   pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
37758   assert( isOpen(pPager->fd) || tempFile );
37759   setSectorSize(pPager);
37760   if( !useJournal ){
37761     pPager->journalMode = PAGER_JOURNALMODE_OFF;
37762   }else if( memDb ){
37763     pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
37764   }
37765   /* pPager->xBusyHandler = 0; */
37766   /* pPager->pBusyHandlerArg = 0; */
37767   pPager->xReiniter = xReinit;
37768   /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
37769
37770   *ppPager = pPager;
37771   return SQLITE_OK;
37772 }
37773
37774
37775
37776 /*
37777 ** This function is called after transitioning from PAGER_UNLOCK to
37778 ** PAGER_SHARED state. It tests if there is a hot journal present in
37779 ** the file-system for the given pager. A hot journal is one that 
37780 ** needs to be played back. According to this function, a hot-journal
37781 ** file exists if the following criteria are met:
37782 **
37783 **   * The journal file exists in the file system, and
37784 **   * No process holds a RESERVED or greater lock on the database file, and
37785 **   * The database file itself is greater than 0 bytes in size, and
37786 **   * The first byte of the journal file exists and is not 0x00.
37787 **
37788 ** If the current size of the database file is 0 but a journal file
37789 ** exists, that is probably an old journal left over from a prior
37790 ** database with the same name. In this case the journal file is
37791 ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
37792 ** is returned.
37793 **
37794 ** This routine does not check if there is a master journal filename
37795 ** at the end of the file. If there is, and that master journal file
37796 ** does not exist, then the journal file is not really hot. In this
37797 ** case this routine will return a false-positive. The pager_playback()
37798 ** routine will discover that the journal file is not really hot and 
37799 ** will not roll it back. 
37800 **
37801 ** If a hot-journal file is found to exist, *pExists is set to 1 and 
37802 ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
37803 ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
37804 ** to determine whether or not a hot-journal file exists, the IO error
37805 ** code is returned and the value of *pExists is undefined.
37806 */
37807 static int hasHotJournal(Pager *pPager, int *pExists){
37808   sqlite3_vfs * const pVfs = pPager->pVfs;
37809   int rc = SQLITE_OK;           /* Return code */
37810   int exists = 1;               /* True if a journal file is present */
37811   int jrnlOpen = !!isOpen(pPager->jfd);
37812
37813   assert( pPager!=0 );
37814   assert( pPager->useJournal );
37815   assert( isOpen(pPager->fd) );
37816   assert( pPager->state <= PAGER_SHARED );
37817   assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
37818     SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
37819   ));
37820
37821   *pExists = 0;
37822   if( !jrnlOpen ){
37823     rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
37824   }
37825   if( rc==SQLITE_OK && exists ){
37826     int locked;                 /* True if some process holds a RESERVED lock */
37827
37828     /* Race condition here:  Another process might have been holding the
37829     ** the RESERVED lock and have a journal open at the sqlite3OsAccess() 
37830     ** call above, but then delete the journal and drop the lock before
37831     ** we get to the following sqlite3OsCheckReservedLock() call.  If that
37832     ** is the case, this routine might think there is a hot journal when
37833     ** in fact there is none.  This results in a false-positive which will
37834     ** be dealt with by the playback routine.  Ticket #3883.
37835     */
37836     rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
37837     if( rc==SQLITE_OK && !locked ){
37838       int nPage;
37839
37840       /* Check the size of the database file. If it consists of 0 pages,
37841       ** then delete the journal file. See the header comment above for 
37842       ** the reasoning here.  Delete the obsolete journal file under
37843       ** a RESERVED lock to avoid race conditions and to avoid violating
37844       ** [H33020].
37845       */
37846       rc = sqlite3PagerPagecount(pPager, &nPage);
37847       if( rc==SQLITE_OK ){
37848         if( nPage==0 ){
37849           sqlite3BeginBenignMalloc();
37850           if( sqlite3OsLock(pPager->fd, RESERVED_LOCK)==SQLITE_OK ){
37851             sqlite3OsDelete(pVfs, pPager->zJournal, 0);
37852             sqlite3OsUnlock(pPager->fd, SHARED_LOCK);
37853           }
37854           sqlite3EndBenignMalloc();
37855         }else{
37856           /* The journal file exists and no other connection has a reserved
37857           ** or greater lock on the database file. Now check that there is
37858           ** at least one non-zero bytes at the start of the journal file.
37859           ** If there is, then we consider this journal to be hot. If not, 
37860           ** it can be ignored.
37861           */
37862           if( !jrnlOpen ){
37863             int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
37864             rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
37865           }
37866           if( rc==SQLITE_OK ){
37867             u8 first = 0;
37868             rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
37869             if( rc==SQLITE_IOERR_SHORT_READ ){
37870               rc = SQLITE_OK;
37871             }
37872             if( !jrnlOpen ){
37873               sqlite3OsClose(pPager->jfd);
37874             }
37875             *pExists = (first!=0);
37876           }else if( rc==SQLITE_CANTOPEN ){
37877             /* If we cannot open the rollback journal file in order to see if
37878             ** its has a zero header, that might be due to an I/O error, or
37879             ** it might be due to the race condition described above and in
37880             ** ticket #3883.  Either way, assume that the journal is hot.
37881             ** This might be a false positive.  But if it is, then the
37882             ** automatic journal playback and recovery mechanism will deal
37883             ** with it under an EXCLUSIVE lock where we do not need to
37884             ** worry so much with race conditions.
37885             */
37886             *pExists = 1;
37887             rc = SQLITE_OK;
37888           }
37889         }
37890       }
37891     }
37892   }
37893
37894   return rc;
37895 }
37896
37897 /*
37898 ** This function is called to obtain a shared lock on the database file.
37899 ** It is illegal to call sqlite3PagerAcquire() until after this function
37900 ** has been successfully called. If a shared-lock is already held when
37901 ** this function is called, it is a no-op.
37902 **
37903 ** The following operations are also performed by this function.
37904 **
37905 **   1) If the pager is currently in PAGER_UNLOCK state (no lock held
37906 **      on the database file), then an attempt is made to obtain a
37907 **      SHARED lock on the database file. Immediately after obtaining
37908 **      the SHARED lock, the file-system is checked for a hot-journal,
37909 **      which is played back if present. Following any hot-journal 
37910 **      rollback, the contents of the cache are validated by checking
37911 **      the 'change-counter' field of the database file header and
37912 **      discarded if they are found to be invalid.
37913 **
37914 **   2) If the pager is running in exclusive-mode, and there are currently
37915 **      no outstanding references to any pages, and is in the error state,
37916 **      then an attempt is made to clear the error state by discarding
37917 **      the contents of the page cache and rolling back any open journal
37918 **      file.
37919 **
37920 ** If the operation described by (2) above is not attempted, and if the
37921 ** pager is in an error state other than SQLITE_FULL when this is called,
37922 ** the error state error code is returned. It is permitted to read the
37923 ** database when in SQLITE_FULL error state.
37924 **
37925 ** Otherwise, if everything is successful, SQLITE_OK is returned. If an
37926 ** IO error occurs while locking the database, checking for a hot-journal
37927 ** file or rolling back a journal file, the IO error code is returned.
37928 */
37929 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
37930   int rc = SQLITE_OK;                /* Return code */
37931   int isErrorReset = 0;              /* True if recovering from error state */
37932
37933   /* This routine is only called from b-tree and only when there are no
37934   ** outstanding pages */
37935   assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
37936   if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
37937
37938   /* If this database is in an error-state, now is a chance to clear
37939   ** the error. Discard the contents of the pager-cache and rollback
37940   ** any hot journal in the file-system.
37941   */
37942   if( pPager->errCode ){
37943     if( isOpen(pPager->jfd) || pPager->zJournal ){
37944       isErrorReset = 1;
37945     }
37946     pPager->errCode = SQLITE_OK;
37947     pager_reset(pPager);
37948   }
37949
37950   if( pagerUseWal(pPager) ){
37951     rc = pagerBeginReadTransaction(pPager);
37952   }else if( pPager->state==PAGER_UNLOCK || isErrorReset ){
37953     sqlite3_vfs * const pVfs = pPager->pVfs;
37954     int isHotJournal = 0;
37955     assert( !MEMDB );
37956     assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
37957     if( pPager->noReadlock ){
37958       assert( pPager->readOnly );
37959       pPager->state = PAGER_SHARED;
37960     }else{
37961       rc = pager_wait_on_lock(pPager, SHARED_LOCK);
37962       if( rc!=SQLITE_OK ){
37963         assert( pPager->state==PAGER_UNLOCK );
37964         return pager_error(pPager, rc);
37965       }
37966     }
37967     assert( pPager->state>=SHARED_LOCK );
37968
37969     /* If a journal file exists, and there is no RESERVED lock on the
37970     ** database file, then it either needs to be played back or deleted.
37971     */
37972     if( !isErrorReset ){
37973       assert( pPager->state <= PAGER_SHARED );
37974       rc = hasHotJournal(pPager, &isHotJournal);
37975       if( rc!=SQLITE_OK ){
37976         goto failed;
37977       }
37978     }
37979     if( isErrorReset || isHotJournal ){
37980       /* Get an EXCLUSIVE lock on the database file. At this point it is
37981       ** important that a RESERVED lock is not obtained on the way to the
37982       ** EXCLUSIVE lock. If it were, another process might open the
37983       ** database file, detect the RESERVED lock, and conclude that the
37984       ** database is safe to read while this process is still rolling the 
37985       ** hot-journal back.
37986       ** 
37987       ** Because the intermediate RESERVED lock is not requested, any
37988       ** other process attempting to access the database file will get to 
37989       ** this point in the code and fail to obtain its own EXCLUSIVE lock 
37990       ** on the database file.
37991       */
37992       if( pPager->state<EXCLUSIVE_LOCK ){
37993         rc = sqlite3OsLock(pPager->fd, EXCLUSIVE_LOCK);
37994         if( rc!=SQLITE_OK ){
37995           rc = pager_error(pPager, rc);
37996           goto failed;
37997         }
37998         pPager->state = PAGER_EXCLUSIVE;
37999       }
38000  
38001       /* Open the journal for read/write access. This is because in 
38002       ** exclusive-access mode the file descriptor will be kept open and
38003       ** possibly used for a transaction later on. On some systems, the
38004       ** OsTruncate() call used in exclusive-access mode also requires
38005       ** a read/write file handle.
38006       */
38007       if( !isOpen(pPager->jfd) ){
38008         int res;
38009         rc = sqlite3OsAccess(pVfs,pPager->zJournal,SQLITE_ACCESS_EXISTS,&res);
38010         if( rc==SQLITE_OK ){
38011           if( res ){
38012             int fout = 0;
38013             int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
38014             assert( !pPager->tempFile );
38015             rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
38016             assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
38017             if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
38018               rc = SQLITE_CANTOPEN_BKPT;
38019               sqlite3OsClose(pPager->jfd);
38020             }
38021           }else{
38022             /* If the journal does not exist, it usually means that some 
38023             ** other connection managed to get in and roll it back before 
38024             ** this connection obtained the exclusive lock above. Or, it 
38025             ** may mean that the pager was in the error-state when this
38026             ** function was called and the journal file does not exist.  */
38027             rc = pager_end_transaction(pPager, 0);
38028           }
38029         }
38030       }
38031       if( rc!=SQLITE_OK ){
38032         goto failed;
38033       }
38034
38035       /* Reset the journal status fields to indicates that we have no
38036       ** rollback journal at this time. */
38037       pPager->journalStarted = 0;
38038       pPager->journalOff = 0;
38039       pPager->setMaster = 0;
38040       pPager->journalHdr = 0;
38041  
38042       /* Make sure the journal file has been synced to disk. */
38043  
38044       /* Playback and delete the journal.  Drop the database write
38045       ** lock and reacquire the read lock. Purge the cache before
38046       ** playing back the hot-journal so that we don't end up with
38047       ** an inconsistent cache.  Sync the hot journal before playing
38048       ** it back since the process that crashed and left the hot journal
38049       ** probably did not sync it and we are required to always sync
38050       ** the journal before playing it back.
38051       */
38052       if( isOpen(pPager->jfd) ){
38053         rc = pagerSyncHotJournal(pPager);
38054         if( rc==SQLITE_OK ){
38055           rc = pager_playback(pPager, 1);
38056         }
38057         if( rc!=SQLITE_OK ){
38058           rc = pager_error(pPager, rc);
38059           goto failed;
38060         }
38061       }
38062       assert( (pPager->state==PAGER_SHARED)
38063            || (pPager->exclusiveMode && pPager->state>PAGER_SHARED)
38064       );
38065     }
38066
38067     if( pPager->pBackup || sqlite3PcachePagecount(pPager->pPCache)>0 ){
38068       /* The shared-lock has just been acquired on the database file
38069       ** and there are already pages in the cache (from a previous
38070       ** read or write transaction).  Check to see if the database
38071       ** has been modified.  If the database has changed, flush the
38072       ** cache.
38073       **
38074       ** Database changes is detected by looking at 15 bytes beginning
38075       ** at offset 24 into the file.  The first 4 of these 16 bytes are
38076       ** a 32-bit counter that is incremented with each change.  The
38077       ** other bytes change randomly with each file change when
38078       ** a codec is in use.
38079       ** 
38080       ** There is a vanishingly small chance that a change will not be 
38081       ** detected.  The chance of an undetected change is so small that
38082       ** it can be neglected.
38083       */
38084       int nPage = 0;
38085       char dbFileVers[sizeof(pPager->dbFileVers)];
38086       sqlite3PagerPagecount(pPager, &nPage);
38087
38088       if( pPager->errCode ){
38089         rc = pPager->errCode;
38090         goto failed;
38091       }
38092
38093       if( nPage>0 ){
38094         IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
38095         rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
38096         if( rc!=SQLITE_OK ){
38097           goto failed;
38098         }
38099       }else{
38100         memset(dbFileVers, 0, sizeof(dbFileVers));
38101       }
38102
38103       if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
38104         pager_reset(pPager);
38105       }
38106     }
38107     assert( pPager->exclusiveMode || pPager->state==PAGER_SHARED );
38108
38109     /* If there is a WAL file in the file-system, open this database in WAL
38110     ** mode. Otherwise, the following function call is a no-op.
38111     */
38112     rc = pagerOpenWalIfPresent(pPager);
38113   }
38114
38115  failed:
38116   if( rc!=SQLITE_OK ){
38117     /* pager_unlock() is a no-op for exclusive mode and in-memory databases. */
38118     pager_unlock(pPager);
38119   }
38120   return rc;
38121 }
38122
38123 /*
38124 ** If the reference count has reached zero, rollback any active
38125 ** transaction and unlock the pager.
38126 **
38127 ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
38128 ** the rollback journal, the unlock is not performed and there is
38129 ** nothing to rollback, so this routine is a no-op.
38130 */ 
38131 static void pagerUnlockIfUnused(Pager *pPager){
38132   if( (sqlite3PcacheRefCount(pPager->pPCache)==0)
38133    && (!pPager->exclusiveMode || pPager->journalOff>0) 
38134   ){
38135     pagerUnlockAndRollback(pPager);
38136   }
38137 }
38138
38139 /*
38140 ** Acquire a reference to page number pgno in pager pPager (a page
38141 ** reference has type DbPage*). If the requested reference is 
38142 ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
38143 **
38144 ** If the requested page is already in the cache, it is returned. 
38145 ** Otherwise, a new page object is allocated and populated with data
38146 ** read from the database file. In some cases, the pcache module may
38147 ** choose not to allocate a new page object and may reuse an existing
38148 ** object with no outstanding references.
38149 **
38150 ** The extra data appended to a page is always initialized to zeros the 
38151 ** first time a page is loaded into memory. If the page requested is 
38152 ** already in the cache when this function is called, then the extra
38153 ** data is left as it was when the page object was last used.
38154 **
38155 ** If the database image is smaller than the requested page or if a 
38156 ** non-zero value is passed as the noContent parameter and the 
38157 ** requested page is not already stored in the cache, then no 
38158 ** actual disk read occurs. In this case the memory image of the 
38159 ** page is initialized to all zeros. 
38160 **
38161 ** If noContent is true, it means that we do not care about the contents
38162 ** of the page. This occurs in two seperate scenarios:
38163 **
38164 **   a) When reading a free-list leaf page from the database, and
38165 **
38166 **   b) When a savepoint is being rolled back and we need to load
38167 **      a new page into the cache to be filled with the data read
38168 **      from the savepoint journal.
38169 **
38170 ** If noContent is true, then the data returned is zeroed instead of
38171 ** being read from the database. Additionally, the bits corresponding
38172 ** to pgno in Pager.pInJournal (bitvec of pages already written to the
38173 ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
38174 ** savepoints are set. This means if the page is made writable at any
38175 ** point in the future, using a call to sqlite3PagerWrite(), its contents
38176 ** will not be journaled. This saves IO.
38177 **
38178 ** The acquisition might fail for several reasons.  In all cases,
38179 ** an appropriate error code is returned and *ppPage is set to NULL.
38180 **
38181 ** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
38182 ** to find a page in the in-memory cache first.  If the page is not already
38183 ** in memory, this routine goes to disk to read it in whereas Lookup()
38184 ** just returns 0.  This routine acquires a read-lock the first time it
38185 ** has to go to disk, and could also playback an old journal if necessary.
38186 ** Since Lookup() never goes to disk, it never has to deal with locks
38187 ** or journal files.
38188 */
38189 SQLITE_PRIVATE int sqlite3PagerAcquire(
38190   Pager *pPager,      /* The pager open on the database file */
38191   Pgno pgno,          /* Page number to fetch */
38192   DbPage **ppPage,    /* Write a pointer to the page here */
38193   int noContent       /* Do not bother reading content from disk if true */
38194 ){
38195   int rc;
38196   PgHdr *pPg;
38197
38198   assert( assert_pager_state(pPager) );
38199   assert( pPager->state>PAGER_UNLOCK );
38200
38201   if( pgno==0 ){
38202     return SQLITE_CORRUPT_BKPT;
38203   }
38204
38205   /* If the pager is in the error state, return an error immediately. 
38206   ** Otherwise, request the page from the PCache layer. */
38207   if( pPager->errCode!=SQLITE_OK && pPager->errCode!=SQLITE_FULL ){
38208     rc = pPager->errCode;
38209   }else{
38210     rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
38211   }
38212
38213   if( rc!=SQLITE_OK ){
38214     /* Either the call to sqlite3PcacheFetch() returned an error or the
38215     ** pager was already in the error-state when this function was called.
38216     ** Set pPg to 0 and jump to the exception handler.  */
38217     pPg = 0;
38218     goto pager_acquire_err;
38219   }
38220   assert( (*ppPage)->pgno==pgno );
38221   assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
38222
38223   if( (*ppPage)->pPager && !noContent ){
38224     /* In this case the pcache already contains an initialized copy of
38225     ** the page. Return without further ado.  */
38226     assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
38227     PAGER_INCR(pPager->nHit);
38228     return SQLITE_OK;
38229
38230   }else{
38231     /* The pager cache has created a new page. Its content needs to 
38232     ** be initialized.  */
38233     int nMax;
38234
38235     PAGER_INCR(pPager->nMiss);
38236     pPg = *ppPage;
38237     pPg->pPager = pPager;
38238
38239     /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
38240     ** number greater than this, or the unused locking-page, is requested. */
38241     if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
38242       rc = SQLITE_CORRUPT_BKPT;
38243       goto pager_acquire_err;
38244     }
38245
38246     rc = sqlite3PagerPagecount(pPager, &nMax);
38247     if( rc!=SQLITE_OK ){
38248       goto pager_acquire_err;
38249     }
38250
38251     if( MEMDB || nMax<(int)pgno || noContent || !isOpen(pPager->fd) ){
38252       if( pgno>pPager->mxPgno ){
38253         rc = SQLITE_FULL;
38254         goto pager_acquire_err;
38255       }
38256       if( noContent ){
38257         /* Failure to set the bits in the InJournal bit-vectors is benign.
38258         ** It merely means that we might do some extra work to journal a 
38259         ** page that does not need to be journaled.  Nevertheless, be sure 
38260         ** to test the case where a malloc error occurs while trying to set 
38261         ** a bit in a bit vector.
38262         */
38263         sqlite3BeginBenignMalloc();
38264         if( pgno<=pPager->dbOrigSize ){
38265           TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
38266           testcase( rc==SQLITE_NOMEM );
38267         }
38268         TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
38269         testcase( rc==SQLITE_NOMEM );
38270         sqlite3EndBenignMalloc();
38271       }
38272       memset(pPg->pData, 0, pPager->pageSize);
38273       IOTRACE(("ZERO %p %d\n", pPager, pgno));
38274     }else{
38275       assert( pPg->pPager==pPager );
38276       rc = readDbPage(pPg);
38277       if( rc!=SQLITE_OK ){
38278         goto pager_acquire_err;
38279       }
38280     }
38281 #ifdef SQLITE_CHECK_PAGES
38282     pPg->pageHash = pager_pagehash(pPg);
38283 #endif
38284   }
38285
38286   return SQLITE_OK;
38287
38288 pager_acquire_err:
38289   assert( rc!=SQLITE_OK );
38290   if( pPg ){
38291     sqlite3PcacheDrop(pPg);
38292   }
38293   pagerUnlockIfUnused(pPager);
38294
38295   *ppPage = 0;
38296   return rc;
38297 }
38298
38299 /*
38300 ** Acquire a page if it is already in the in-memory cache.  Do
38301 ** not read the page from disk.  Return a pointer to the page,
38302 ** or 0 if the page is not in cache. Also, return 0 if the 
38303 ** pager is in PAGER_UNLOCK state when this function is called,
38304 ** or if the pager is in an error state other than SQLITE_FULL.
38305 **
38306 ** See also sqlite3PagerGet().  The difference between this routine
38307 ** and sqlite3PagerGet() is that _get() will go to the disk and read
38308 ** in the page if the page is not already in cache.  This routine
38309 ** returns NULL if the page is not in cache or if a disk I/O error 
38310 ** has ever happened.
38311 */
38312 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
38313   PgHdr *pPg = 0;
38314   assert( pPager!=0 );
38315   assert( pgno!=0 );
38316   assert( pPager->pPCache!=0 );
38317   assert( pPager->state > PAGER_UNLOCK );
38318   sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
38319   return pPg;
38320 }
38321
38322 /*
38323 ** Release a page reference.
38324 **
38325 ** If the number of references to the page drop to zero, then the
38326 ** page is added to the LRU list.  When all references to all pages
38327 ** are released, a rollback occurs and the lock on the database is
38328 ** removed.
38329 */
38330 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
38331   if( pPg ){
38332     Pager *pPager = pPg->pPager;
38333     sqlite3PcacheRelease(pPg);
38334     pagerUnlockIfUnused(pPager);
38335   }
38336 }
38337
38338 /*
38339 ** This function is called at the start of every write transaction.
38340 ** There must already be a RESERVED or EXCLUSIVE lock on the database 
38341 ** file when this routine is called.
38342 **
38343 ** Open the journal file for pager pPager and write a journal header
38344 ** to the start of it. If there are active savepoints, open the sub-journal
38345 ** as well. This function is only used when the journal file is being 
38346 ** opened to write a rollback log for a transaction. It is not used 
38347 ** when opening a hot journal file to roll it back.
38348 **
38349 ** If the journal file is already open (as it may be in exclusive mode),
38350 ** then this function just writes a journal header to the start of the
38351 ** already open file. 
38352 **
38353 ** Whether or not the journal file is opened by this function, the
38354 ** Pager.pInJournal bitvec structure is allocated.
38355 **
38356 ** Return SQLITE_OK if everything is successful. Otherwise, return 
38357 ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or 
38358 ** an IO error code if opening or writing the journal file fails.
38359 */
38360 static int pager_open_journal(Pager *pPager){
38361   int rc = SQLITE_OK;                        /* Return code */
38362   int nPage;                                 /* Size of database file */
38363   sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
38364
38365   assert( pPager->state>=PAGER_RESERVED );
38366   assert( pPager->useJournal );
38367   assert( pPager->journalMode!=PAGER_JOURNALMODE_OFF );
38368   assert( pPager->pInJournal==0 );
38369   
38370   /* If already in the error state, this function is a no-op.  But on
38371   ** the other hand, this routine is never called if we are already in
38372   ** an error state. */
38373   if( NEVER(pPager->errCode) ) return pPager->errCode;
38374
38375   testcase( pPager->dbSizeValid==0 );
38376   rc = sqlite3PagerPagecount(pPager, &nPage);
38377   if( rc ) return rc;
38378   pPager->pInJournal = sqlite3BitvecCreate(nPage);
38379   if( pPager->pInJournal==0 ){
38380     return SQLITE_NOMEM;
38381   }
38382
38383   /* Open the journal file if it is not already open. */
38384   if( !isOpen(pPager->jfd) ){
38385     if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
38386       sqlite3MemJournalOpen(pPager->jfd);
38387     }else{
38388       const int flags =                   /* VFS flags to open journal file */
38389         SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
38390         (pPager->tempFile ? 
38391           (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
38392           (SQLITE_OPEN_MAIN_JOURNAL)
38393         );
38394 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
38395       rc = sqlite3JournalOpen(
38396           pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
38397       );
38398 #else
38399       rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
38400 #endif
38401     }
38402     assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
38403   }
38404
38405
38406   /* Write the first journal header to the journal file and open 
38407   ** the sub-journal if necessary.
38408   */
38409   if( rc==SQLITE_OK ){
38410     /* TODO: Check if all of these are really required. */
38411     pPager->dbOrigSize = pPager->dbSize;
38412     pPager->journalStarted = 0;
38413     pPager->needSync = 0;
38414     pPager->nRec = 0;
38415     pPager->journalOff = 0;
38416     pPager->setMaster = 0;
38417     pPager->journalHdr = 0;
38418     rc = writeJournalHdr(pPager);
38419   }
38420
38421   if( rc!=SQLITE_OK ){
38422     sqlite3BitvecDestroy(pPager->pInJournal);
38423     pPager->pInJournal = 0;
38424   }
38425   return rc;
38426 }
38427
38428 /*
38429 ** Begin a write-transaction on the specified pager object. If a 
38430 ** write-transaction has already been opened, this function is a no-op.
38431 **
38432 ** If the exFlag argument is false, then acquire at least a RESERVED
38433 ** lock on the database file. If exFlag is true, then acquire at least
38434 ** an EXCLUSIVE lock. If such a lock is already held, no locking 
38435 ** functions need be called.
38436 **
38437 ** If this is not a temporary or in-memory file and, the journal file is 
38438 ** opened if it has not been already. For a temporary file, the opening 
38439 ** of the journal file is deferred until there is an actual need to 
38440 ** write to the journal. TODO: Why handle temporary files differently?
38441 **
38442 ** If the journal file is opened (or if it is already open), then a
38443 ** journal-header is written to the start of it.
38444 **
38445 ** If the subjInMemory argument is non-zero, then any sub-journal opened
38446 ** within this transaction will be opened as an in-memory file. This
38447 ** has no effect if the sub-journal is already opened (as it may be when
38448 ** running in exclusive mode) or if the transaction does not require a
38449 ** sub-journal. If the subjInMemory argument is zero, then any required
38450 ** sub-journal is implemented in-memory if pPager is an in-memory database, 
38451 ** or using a temporary file otherwise.
38452 */
38453 SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
38454   int rc = SQLITE_OK;
38455   assert( pPager->state!=PAGER_UNLOCK );
38456   pPager->subjInMemory = (u8)subjInMemory;
38457
38458   if( pPager->state==PAGER_SHARED ){
38459     assert( pPager->pInJournal==0 );
38460     assert( !MEMDB && !pPager->tempFile );
38461
38462     if( pagerUseWal(pPager) ){
38463       /* If the pager is configured to use locking_mode=exclusive, and an
38464       ** exclusive lock on the database is not already held, obtain it now.
38465       */
38466       if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
38467         rc = sqlite3OsLock(pPager->fd, EXCLUSIVE_LOCK);
38468         pPager->state = PAGER_SHARED;
38469         if( rc!=SQLITE_OK ){
38470           return rc;
38471         }
38472         sqlite3WalExclusiveMode(pPager->pWal, 1);
38473       }
38474
38475       /* Grab the write lock on the log file. If successful, upgrade to
38476       ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
38477       ** The busy-handler is not invoked if another connection already
38478       ** holds the write-lock. If possible, the upper layer will call it.
38479       **
38480       ** WAL mode sets Pager.state to PAGER_RESERVED when it has an open
38481       ** transaction, but never to PAGER_EXCLUSIVE. This is because in 
38482       ** PAGER_EXCLUSIVE state the code to roll back savepoint transactions
38483       ** may copy data from the sub-journal into the database file as well
38484       ** as into the page cache. Which would be incorrect in WAL mode.
38485       */
38486       rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
38487       if( rc==SQLITE_OK ){
38488         pPager->dbOrigSize = pPager->dbSize;
38489         pPager->state = PAGER_RESERVED;
38490         pPager->journalOff = 0;
38491       }
38492
38493       assert( rc!=SQLITE_OK || pPager->state==PAGER_RESERVED );
38494       assert( rc==SQLITE_OK || pPager->state==PAGER_SHARED );
38495     }else{
38496       /* Obtain a RESERVED lock on the database file. If the exFlag parameter
38497       ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
38498       ** busy-handler callback can be used when upgrading to the EXCLUSIVE
38499       ** lock, but not when obtaining the RESERVED lock.
38500       */
38501       rc = sqlite3OsLock(pPager->fd, RESERVED_LOCK);
38502       if( rc==SQLITE_OK ){
38503         pPager->state = PAGER_RESERVED;
38504         if( exFlag ){
38505           rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
38506         }
38507       }
38508     }
38509
38510     /* No need to open the journal file at this time.  It will be
38511     ** opened before it is written to.  If we defer opening the journal,
38512     ** we might save the work of creating a file if the transaction
38513     ** ends up being a no-op.
38514     */
38515
38516     if( rc!=SQLITE_OK ){
38517       assert( !pPager->dbModified );
38518       /* Ignore any IO error that occurs within pager_end_transaction(). The
38519       ** purpose of this call is to reset the internal state of the pager
38520       ** sub-system. It doesn't matter if the journal-file is not properly
38521       ** finalized at this point (since it is not a valid journal file anyway).
38522       */
38523       pager_end_transaction(pPager, 0);
38524     }
38525   }
38526
38527   PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
38528   return rc;
38529 }
38530
38531 /*
38532 ** Mark a single data page as writeable. The page is written into the 
38533 ** main journal or sub-journal as required. If the page is written into
38534 ** one of the journals, the corresponding bit is set in the 
38535 ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
38536 ** of any open savepoints as appropriate.
38537 */
38538 static int pager_write(PgHdr *pPg){
38539   void *pData = pPg->pData;
38540   Pager *pPager = pPg->pPager;
38541   int rc = SQLITE_OK;
38542
38543   /* This routine is not called unless a transaction has already been
38544   ** started.
38545   */
38546   assert( pPager->state>=PAGER_RESERVED );
38547
38548   /* If an error has been previously detected, report the same error
38549   ** again.
38550   */
38551   if( NEVER(pPager->errCode) )  return pPager->errCode;
38552
38553   /* Higher-level routines never call this function if database is not
38554   ** writable.  But check anyway, just for robustness. */
38555   if( NEVER(pPager->readOnly) ) return SQLITE_PERM;
38556
38557   assert( !pPager->setMaster );
38558
38559   CHECK_PAGE(pPg);
38560
38561   /* Mark the page as dirty.  If the page has already been written
38562   ** to the journal then we can return right away.
38563   */
38564   sqlite3PcacheMakeDirty(pPg);
38565   if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
38566     assert( !pagerUseWal(pPager) );
38567     pPager->dbModified = 1;
38568   }else{
38569
38570     /* If we get this far, it means that the page needs to be
38571     ** written to the transaction journal or the ckeckpoint journal
38572     ** or both.
38573     **
38574     ** Higher level routines should have already started a transaction,
38575     ** which means they have acquired the necessary locks but the rollback
38576     ** journal might not yet be open.
38577     */
38578     assert( pPager->state>=RESERVED_LOCK );
38579     if( pPager->pInJournal==0
38580      && pPager->journalMode!=PAGER_JOURNALMODE_OFF 
38581      && !pagerUseWal(pPager)
38582     ){
38583       assert( pPager->useJournal );
38584       rc = pager_open_journal(pPager);
38585       if( rc!=SQLITE_OK ) return rc;
38586     }
38587     pPager->dbModified = 1;
38588   
38589     /* The transaction journal now exists and we have a RESERVED or an
38590     ** EXCLUSIVE lock on the main database file.  Write the current page to
38591     ** the transaction journal if it is not there already.
38592     */
38593     if( !pageInJournal(pPg) && isOpen(pPager->jfd) ){
38594       assert( !pagerUseWal(pPager) );
38595       if( pPg->pgno<=pPager->dbOrigSize ){
38596         u32 cksum;
38597         char *pData2;
38598
38599         /* We should never write to the journal file the page that
38600         ** contains the database locks.  The following assert verifies
38601         ** that we do not. */
38602         assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
38603
38604         assert( pPager->journalHdr <= pPager->journalOff );
38605         CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
38606         cksum = pager_cksum(pPager, (u8*)pData2);
38607         rc = write32bits(pPager->jfd, pPager->journalOff, pPg->pgno);
38608         if( rc==SQLITE_OK ){
38609           rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize,
38610                               pPager->journalOff + 4);
38611           pPager->journalOff += pPager->pageSize+4;
38612         }
38613         if( rc==SQLITE_OK ){
38614           rc = write32bits(pPager->jfd, pPager->journalOff, cksum);
38615           pPager->journalOff += 4;
38616         }
38617         IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno, 
38618                  pPager->journalOff, pPager->pageSize));
38619         PAGER_INCR(sqlite3_pager_writej_count);
38620         PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
38621              PAGERID(pPager), pPg->pgno, 
38622              ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
38623
38624         /* Even if an IO or diskfull error occurred while journalling the
38625         ** page in the block above, set the need-sync flag for the page.
38626         ** Otherwise, when the transaction is rolled back, the logic in
38627         ** playback_one_page() will think that the page needs to be restored
38628         ** in the database file. And if an IO error occurs while doing so,
38629         ** then corruption may follow.
38630         */
38631         if( !pPager->noSync ){
38632           pPg->flags |= PGHDR_NEED_SYNC;
38633           pPager->needSync = 1;
38634         }
38635
38636         /* An error has occurred writing to the journal file. The 
38637         ** transaction will be rolled back by the layer above.
38638         */
38639         if( rc!=SQLITE_OK ){
38640           return rc;
38641         }
38642
38643         pPager->nRec++;
38644         assert( pPager->pInJournal!=0 );
38645         rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
38646         testcase( rc==SQLITE_NOMEM );
38647         assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
38648         rc |= addToSavepointBitvecs(pPager, pPg->pgno);
38649         if( rc!=SQLITE_OK ){
38650           assert( rc==SQLITE_NOMEM );
38651           return rc;
38652         }
38653       }else{
38654         if( !pPager->journalStarted && !pPager->noSync ){
38655           pPg->flags |= PGHDR_NEED_SYNC;
38656           pPager->needSync = 1;
38657         }
38658         PAGERTRACE(("APPEND %d page %d needSync=%d\n",
38659                 PAGERID(pPager), pPg->pgno,
38660                ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
38661       }
38662     }
38663   
38664     /* If the statement journal is open and the page is not in it,
38665     ** then write the current page to the statement journal.  Note that
38666     ** the statement journal format differs from the standard journal format
38667     ** in that it omits the checksums and the header.
38668     */
38669     if( subjRequiresPage(pPg) ){
38670       rc = subjournalPage(pPg);
38671     }
38672   }
38673
38674   /* Update the database size and return.
38675   */
38676   assert( pPager->state>=PAGER_SHARED );
38677   if( pPager->dbSize<pPg->pgno ){
38678     pPager->dbSize = pPg->pgno;
38679   }
38680   return rc;
38681 }
38682
38683 /*
38684 ** Mark a data page as writeable. This routine must be called before 
38685 ** making changes to a page. The caller must check the return value 
38686 ** of this function and be careful not to change any page data unless 
38687 ** this routine returns SQLITE_OK.
38688 **
38689 ** The difference between this function and pager_write() is that this
38690 ** function also deals with the special case where 2 or more pages
38691 ** fit on a single disk sector. In this case all co-resident pages
38692 ** must have been written to the journal file before returning.
38693 **
38694 ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
38695 ** as appropriate. Otherwise, SQLITE_OK.
38696 */
38697 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
38698   int rc = SQLITE_OK;
38699
38700   PgHdr *pPg = pDbPage;
38701   Pager *pPager = pPg->pPager;
38702   Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
38703
38704   if( nPagePerSector>1 ){
38705     Pgno nPageCount;          /* Total number of pages in database file */
38706     Pgno pg1;                 /* First page of the sector pPg is located on. */
38707     int nPage = 0;            /* Number of pages starting at pg1 to journal */
38708     int ii;                   /* Loop counter */
38709     int needSync = 0;         /* True if any page has PGHDR_NEED_SYNC */
38710
38711     /* Set the doNotSyncSpill flag to 1. This is because we cannot allow
38712     ** a journal header to be written between the pages journaled by
38713     ** this function.
38714     */
38715     assert( !MEMDB );
38716     assert( pPager->doNotSyncSpill==0 );
38717     pPager->doNotSyncSpill++;
38718
38719     /* This trick assumes that both the page-size and sector-size are
38720     ** an integer power of 2. It sets variable pg1 to the identifier
38721     ** of the first page of the sector pPg is located on.
38722     */
38723     pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
38724
38725     rc = sqlite3PagerPagecount(pPager, (int *)&nPageCount);
38726     if( rc==SQLITE_OK ){
38727       if( pPg->pgno>nPageCount ){
38728         nPage = (pPg->pgno - pg1)+1;
38729       }else if( (pg1+nPagePerSector-1)>nPageCount ){
38730         nPage = nPageCount+1-pg1;
38731       }else{
38732         nPage = nPagePerSector;
38733       }
38734       assert(nPage>0);
38735       assert(pg1<=pPg->pgno);
38736       assert((pg1+nPage)>pPg->pgno);
38737     }
38738
38739     for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
38740       Pgno pg = pg1+ii;
38741       PgHdr *pPage;
38742       if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
38743         if( pg!=PAGER_MJ_PGNO(pPager) ){
38744           rc = sqlite3PagerGet(pPager, pg, &pPage);
38745           if( rc==SQLITE_OK ){
38746             rc = pager_write(pPage);
38747             if( pPage->flags&PGHDR_NEED_SYNC ){
38748               needSync = 1;
38749               assert(pPager->needSync);
38750             }
38751             sqlite3PagerUnref(pPage);
38752           }
38753         }
38754       }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
38755         if( pPage->flags&PGHDR_NEED_SYNC ){
38756           needSync = 1;
38757         }
38758         sqlite3PagerUnref(pPage);
38759       }
38760     }
38761
38762     /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages 
38763     ** starting at pg1, then it needs to be set for all of them. Because
38764     ** writing to any of these nPage pages may damage the others, the
38765     ** journal file must contain sync()ed copies of all of them
38766     ** before any of them can be written out to the database file.
38767     */
38768     if( rc==SQLITE_OK && needSync ){
38769       assert( !MEMDB && pPager->noSync==0 );
38770       for(ii=0; ii<nPage; ii++){
38771         PgHdr *pPage = pager_lookup(pPager, pg1+ii);
38772         if( pPage ){
38773           pPage->flags |= PGHDR_NEED_SYNC;
38774           sqlite3PagerUnref(pPage);
38775         }
38776       }
38777       assert(pPager->needSync);
38778     }
38779
38780     assert( pPager->doNotSyncSpill==1 );
38781     pPager->doNotSyncSpill--;
38782   }else{
38783     rc = pager_write(pDbPage);
38784   }
38785   return rc;
38786 }
38787
38788 /*
38789 ** Return TRUE if the page given in the argument was previously passed
38790 ** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
38791 ** to change the content of the page.
38792 */
38793 #ifndef NDEBUG
38794 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
38795   return pPg->flags&PGHDR_DIRTY;
38796 }
38797 #endif
38798
38799 /*
38800 ** A call to this routine tells the pager that it is not necessary to
38801 ** write the information on page pPg back to the disk, even though
38802 ** that page might be marked as dirty.  This happens, for example, when
38803 ** the page has been added as a leaf of the freelist and so its
38804 ** content no longer matters.
38805 **
38806 ** The overlying software layer calls this routine when all of the data
38807 ** on the given page is unused. The pager marks the page as clean so
38808 ** that it does not get written to disk.
38809 **
38810 ** Tests show that this optimization can quadruple the speed of large 
38811 ** DELETE operations.
38812 */
38813 SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
38814   Pager *pPager = pPg->pPager;
38815   if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
38816     PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
38817     IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
38818     pPg->flags |= PGHDR_DONT_WRITE;
38819 #ifdef SQLITE_CHECK_PAGES
38820     pPg->pageHash = pager_pagehash(pPg);
38821 #endif
38822   }
38823 }
38824
38825 /*
38826 ** This routine is called to increment the value of the database file 
38827 ** change-counter, stored as a 4-byte big-endian integer starting at 
38828 ** byte offset 24 of the pager file.
38829 **
38830 ** If the isDirectMode flag is zero, then this is done by calling 
38831 ** sqlite3PagerWrite() on page 1, then modifying the contents of the
38832 ** page data. In this case the file will be updated when the current
38833 ** transaction is committed.
38834 **
38835 ** The isDirectMode flag may only be non-zero if the library was compiled
38836 ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
38837 ** if isDirect is non-zero, then the database file is updated directly
38838 ** by writing an updated version of page 1 using a call to the 
38839 ** sqlite3OsWrite() function.
38840 */
38841 static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
38842   int rc = SQLITE_OK;
38843
38844   /* Declare and initialize constant integer 'isDirect'. If the
38845   ** atomic-write optimization is enabled in this build, then isDirect
38846   ** is initialized to the value passed as the isDirectMode parameter
38847   ** to this function. Otherwise, it is always set to zero.
38848   **
38849   ** The idea is that if the atomic-write optimization is not
38850   ** enabled at compile time, the compiler can omit the tests of
38851   ** 'isDirect' below, as well as the block enclosed in the
38852   ** "if( isDirect )" condition.
38853   */
38854 #ifndef SQLITE_ENABLE_ATOMIC_WRITE
38855 # define DIRECT_MODE 0
38856   assert( isDirectMode==0 );
38857   UNUSED_PARAMETER(isDirectMode);
38858 #else
38859 # define DIRECT_MODE isDirectMode
38860 #endif
38861
38862   assert( pPager->state>=PAGER_RESERVED );
38863   if( !pPager->changeCountDone && pPager->dbSize>0 ){
38864     PgHdr *pPgHdr;                /* Reference to page 1 */
38865     u32 change_counter;           /* Initial value of change-counter field */
38866
38867     assert( !pPager->tempFile && isOpen(pPager->fd) );
38868
38869     /* Open page 1 of the file for writing. */
38870     rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
38871     assert( pPgHdr==0 || rc==SQLITE_OK );
38872
38873     /* If page one was fetched successfully, and this function is not
38874     ** operating in direct-mode, make page 1 writable.  When not in 
38875     ** direct mode, page 1 is always held in cache and hence the PagerGet()
38876     ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
38877     */
38878     if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
38879       rc = sqlite3PagerWrite(pPgHdr);
38880     }
38881
38882     if( rc==SQLITE_OK ){
38883       /* Increment the value just read and write it back to byte 24. */
38884       change_counter = sqlite3Get4byte((u8*)pPager->dbFileVers);
38885       change_counter++;
38886       put32bits(((char*)pPgHdr->pData)+24, change_counter);
38887
38888       /* Also store the SQLite version number in bytes 96..99 and in
38889       ** bytes 92..95 store the change counter for which the version number
38890       ** is valid. */
38891       put32bits(((char*)pPgHdr->pData)+92, change_counter);
38892       put32bits(((char*)pPgHdr->pData)+96, SQLITE_VERSION_NUMBER);
38893
38894       /* If running in direct mode, write the contents of page 1 to the file. */
38895       if( DIRECT_MODE ){
38896         const void *zBuf;
38897         assert( pPager->dbFileSize>0 );
38898         CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
38899         if( rc==SQLITE_OK ){
38900           rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
38901         }
38902         if( rc==SQLITE_OK ){
38903           pPager->changeCountDone = 1;
38904         }
38905       }else{
38906         pPager->changeCountDone = 1;
38907       }
38908     }
38909
38910     /* Release the page reference. */
38911     sqlite3PagerUnref(pPgHdr);
38912   }
38913   return rc;
38914 }
38915
38916 /*
38917 ** Sync the pager file to disk. This is a no-op for in-memory files
38918 ** or pages with the Pager.noSync flag set.
38919 **
38920 ** If successful, or called on a pager for which it is a no-op, this
38921 ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
38922 */
38923 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
38924   int rc;                              /* Return code */
38925   assert( !MEMDB );
38926   if( pPager->noSync ){
38927     rc = SQLITE_OK;
38928   }else{
38929     rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
38930   }
38931   return rc;
38932 }
38933
38934 /*
38935 ** Sync the database file for the pager pPager. zMaster points to the name
38936 ** of a master journal file that should be written into the individual
38937 ** journal file. zMaster may be NULL, which is interpreted as no master
38938 ** journal (a single database transaction).
38939 **
38940 ** This routine ensures that:
38941 **
38942 **   * The database file change-counter is updated,
38943 **   * the journal is synced (unless the atomic-write optimization is used),
38944 **   * all dirty pages are written to the database file, 
38945 **   * the database file is truncated (if required), and
38946 **   * the database file synced. 
38947 **
38948 ** The only thing that remains to commit the transaction is to finalize 
38949 ** (delete, truncate or zero the first part of) the journal file (or 
38950 ** delete the master journal file if specified).
38951 **
38952 ** Note that if zMaster==NULL, this does not overwrite a previous value
38953 ** passed to an sqlite3PagerCommitPhaseOne() call.
38954 **
38955 ** If the final parameter - noSync - is true, then the database file itself
38956 ** is not synced. The caller must call sqlite3PagerSync() directly to
38957 ** sync the database file before calling CommitPhaseTwo() to delete the
38958 ** journal file in this case.
38959 */
38960 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
38961   Pager *pPager,                  /* Pager object */
38962   const char *zMaster,            /* If not NULL, the master journal name */
38963   int noSync                      /* True to omit the xSync on the db file */
38964 ){
38965   int rc = SQLITE_OK;             /* Return code */
38966
38967   /* The dbOrigSize is never set if journal_mode=OFF */
38968   assert( pPager->journalMode!=PAGER_JOURNALMODE_OFF || pPager->dbOrigSize==0 );
38969
38970   /* If a prior error occurred, report that error again. */
38971   if( pPager->errCode ) return pPager->errCode;
38972
38973   PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n", 
38974       pPager->zFilename, zMaster, pPager->dbSize));
38975
38976   if( MEMDB && pPager->dbModified ){
38977     /* If this is an in-memory db, or no pages have been written to, or this
38978     ** function has already been called, it is mostly a no-op.  However, any
38979     ** backup in progress needs to be restarted.
38980     */
38981     sqlite3BackupRestart(pPager->pBackup);
38982   }else if( pPager->state!=PAGER_SYNCED && pPager->dbModified ){
38983     if( pagerUseWal(pPager) ){
38984       PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
38985       if( pList ){
38986         rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1, 
38987             (pPager->fullSync ? pPager->sync_flags : 0)
38988         );
38989       }
38990       if( rc==SQLITE_OK ){
38991         sqlite3PcacheCleanAll(pPager->pPCache);
38992       }
38993     }else{
38994       /* The following block updates the change-counter. Exactly how it
38995       ** does this depends on whether or not the atomic-update optimization
38996       ** was enabled at compile time, and if this transaction meets the 
38997       ** runtime criteria to use the operation: 
38998       **
38999       **    * The file-system supports the atomic-write property for
39000       **      blocks of size page-size, and 
39001       **    * This commit is not part of a multi-file transaction, and
39002       **    * Exactly one page has been modified and store in the journal file.
39003       **
39004       ** If the optimization was not enabled at compile time, then the
39005       ** pager_incr_changecounter() function is called to update the change
39006       ** counter in 'indirect-mode'. If the optimization is compiled in but
39007       ** is not applicable to this transaction, call sqlite3JournalCreate()
39008       ** to make sure the journal file has actually been created, then call
39009       ** pager_incr_changecounter() to update the change-counter in indirect
39010       ** mode. 
39011       **
39012       ** Otherwise, if the optimization is both enabled and applicable,
39013       ** then call pager_incr_changecounter() to update the change-counter
39014       ** in 'direct' mode. In this case the journal file will never be
39015       ** created for this transaction.
39016       */
39017   #ifdef SQLITE_ENABLE_ATOMIC_WRITE
39018       PgHdr *pPg;
39019       assert( isOpen(pPager->jfd) 
39020            || pPager->journalMode==PAGER_JOURNALMODE_OFF 
39021            || pPager->journalMode==PAGER_JOURNALMODE_WAL 
39022       );
39023       if( !zMaster && isOpen(pPager->jfd) 
39024        && pPager->journalOff==jrnlBufferSize(pPager) 
39025        && pPager->dbSize>=pPager->dbFileSize
39026        && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
39027       ){
39028         /* Update the db file change counter via the direct-write method. The 
39029         ** following call will modify the in-memory representation of page 1 
39030         ** to include the updated change counter and then write page 1 
39031         ** directly to the database file. Because of the atomic-write 
39032         ** property of the host file-system, this is safe.
39033         */
39034         rc = pager_incr_changecounter(pPager, 1);
39035       }else{
39036         rc = sqlite3JournalCreate(pPager->jfd);
39037         if( rc==SQLITE_OK ){
39038           rc = pager_incr_changecounter(pPager, 0);
39039         }
39040       }
39041   #else
39042       rc = pager_incr_changecounter(pPager, 0);
39043   #endif
39044       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
39045   
39046       /* If this transaction has made the database smaller, then all pages
39047       ** being discarded by the truncation must be written to the journal
39048       ** file. This can only happen in auto-vacuum mode.
39049       **
39050       ** Before reading the pages with page numbers larger than the 
39051       ** current value of Pager.dbSize, set dbSize back to the value
39052       ** that it took at the start of the transaction. Otherwise, the
39053       ** calls to sqlite3PagerGet() return zeroed pages instead of 
39054       ** reading data from the database file.
39055       **
39056       ** When journal_mode==OFF the dbOrigSize is always zero, so this
39057       ** block never runs if journal_mode=OFF.
39058       */
39059   #ifndef SQLITE_OMIT_AUTOVACUUM
39060       if( pPager->dbSize<pPager->dbOrigSize 
39061        && ALWAYS(pPager->journalMode!=PAGER_JOURNALMODE_OFF)
39062       ){
39063         Pgno i;                                   /* Iterator variable */
39064         const Pgno iSkip = PAGER_MJ_PGNO(pPager); /* Pending lock page */
39065         const Pgno dbSize = pPager->dbSize;       /* Database image size */ 
39066         pPager->dbSize = pPager->dbOrigSize;
39067         for( i=dbSize+1; i<=pPager->dbOrigSize; i++ ){
39068           if( !sqlite3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){
39069             PgHdr *pPage;             /* Page to journal */
39070             rc = sqlite3PagerGet(pPager, i, &pPage);
39071             if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
39072             rc = sqlite3PagerWrite(pPage);
39073             sqlite3PagerUnref(pPage);
39074             if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
39075           }
39076         }
39077         pPager->dbSize = dbSize;
39078       } 
39079   #endif
39080   
39081       /* Write the master journal name into the journal file. If a master 
39082       ** journal file name has already been written to the journal file, 
39083       ** or if zMaster is NULL (no master journal), then this call is a no-op.
39084       */
39085       rc = writeMasterJournal(pPager, zMaster);
39086       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
39087   
39088       /* Sync the journal file. If the atomic-update optimization is being
39089       ** used, this call will not create the journal file or perform any
39090       ** real IO.
39091       */
39092       rc = syncJournal(pPager);
39093       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
39094   
39095       /* Write all dirty pages to the database file. */
39096       rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
39097       if( rc!=SQLITE_OK ){
39098         assert( rc!=SQLITE_IOERR_BLOCKED );
39099         goto commit_phase_one_exit;
39100       }
39101       sqlite3PcacheCleanAll(pPager->pPCache);
39102   
39103       /* If the file on disk is not the same size as the database image,
39104       ** then use pager_truncate to grow or shrink the file here.
39105       */
39106       if( pPager->dbSize!=pPager->dbFileSize ){
39107         Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
39108         assert( pPager->state>=PAGER_EXCLUSIVE );
39109         rc = pager_truncate(pPager, nNew);
39110         if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
39111       }
39112   
39113       /* Finally, sync the database file. */
39114       if( !pPager->noSync && !noSync ){
39115         rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
39116       }
39117       IOTRACE(("DBSYNC %p\n", pPager))
39118     }
39119
39120     pPager->state = PAGER_SYNCED;
39121   }
39122
39123 commit_phase_one_exit:
39124   return rc;
39125 }
39126
39127
39128 /*
39129 ** When this function is called, the database file has been completely
39130 ** updated to reflect the changes made by the current transaction and
39131 ** synced to disk. The journal file still exists in the file-system 
39132 ** though, and if a failure occurs at this point it will eventually
39133 ** be used as a hot-journal and the current transaction rolled back.
39134 **
39135 ** This function finalizes the journal file, either by deleting, 
39136 ** truncating or partially zeroing it, so that it cannot be used 
39137 ** for hot-journal rollback. Once this is done the transaction is
39138 ** irrevocably committed.
39139 **
39140 ** If an error occurs, an IO error code is returned and the pager
39141 ** moves into the error state. Otherwise, SQLITE_OK is returned.
39142 */
39143 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
39144   int rc = SQLITE_OK;                  /* Return code */
39145
39146   /* This routine should not be called if a prior error has occurred.
39147   ** But if (due to a coding error elsewhere in the system) it does get
39148   ** called, just return the same error code without doing anything. */
39149   if( NEVER(pPager->errCode) ) return pPager->errCode;
39150
39151   /* This function should not be called if the pager is not in at least
39152   ** PAGER_RESERVED state. **FIXME**: Make it so that this test always
39153   ** fails - make it so that we never reach this point if we do not hold
39154   ** all necessary locks.
39155   */
39156   if( NEVER(pPager->state<PAGER_RESERVED) ) return SQLITE_ERROR;
39157
39158   /* An optimization. If the database was not actually modified during
39159   ** this transaction, the pager is running in exclusive-mode and is
39160   ** using persistent journals, then this function is a no-op.
39161   **
39162   ** The start of the journal file currently contains a single journal 
39163   ** header with the nRec field set to 0. If such a journal is used as
39164   ** a hot-journal during hot-journal rollback, 0 changes will be made
39165   ** to the database file. So there is no need to zero the journal 
39166   ** header. Since the pager is in exclusive mode, there is no need
39167   ** to drop any locks either.
39168   */
39169   if( pPager->dbModified==0 && pPager->exclusiveMode 
39170    && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
39171   ){
39172     assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
39173     return SQLITE_OK;
39174   }
39175
39176   PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
39177   assert( pPager->state==PAGER_SYNCED || MEMDB || !pPager->dbModified );
39178   rc = pager_end_transaction(pPager, pPager->setMaster);
39179   return pager_error(pPager, rc);
39180 }
39181
39182 /*
39183 ** Rollback all changes. The database falls back to PAGER_SHARED mode.
39184 **
39185 ** This function performs two tasks:
39186 **
39187 **   1) It rolls back the journal file, restoring all database file and 
39188 **      in-memory cache pages to the state they were in when the transaction
39189 **      was opened, and
39190 **   2) It finalizes the journal file, so that it is not used for hot
39191 **      rollback at any point in the future.
39192 **
39193 ** subject to the following qualifications:
39194 **
39195 ** * If the journal file is not yet open when this function is called,
39196 **   then only (2) is performed. In this case there is no journal file
39197 **   to roll back.
39198 **
39199 ** * If in an error state other than SQLITE_FULL, then task (1) is 
39200 **   performed. If successful, task (2). Regardless of the outcome
39201 **   of either, the error state error code is returned to the caller
39202 **   (i.e. either SQLITE_IOERR or SQLITE_CORRUPT).
39203 **
39204 ** * If the pager is in PAGER_RESERVED state, then attempt (1). Whether
39205 **   or not (1) is successful, also attempt (2). If successful, return
39206 **   SQLITE_OK. Otherwise, enter the error state and return the first 
39207 **   error code encountered. 
39208 **
39209 **   In this case there is no chance that the database was written to. 
39210 **   So is safe to finalize the journal file even if the playback 
39211 **   (operation 1) failed. However the pager must enter the error state
39212 **   as the contents of the in-memory cache are now suspect.
39213 **
39214 ** * Finally, if in PAGER_EXCLUSIVE state, then attempt (1). Only
39215 **   attempt (2) if (1) is successful. Return SQLITE_OK if successful,
39216 **   otherwise enter the error state and return the error code from the 
39217 **   failing operation.
39218 **
39219 **   In this case the database file may have been written to. So if the
39220 **   playback operation did not succeed it would not be safe to finalize
39221 **   the journal file. It needs to be left in the file-system so that
39222 **   some other process can use it to restore the database state (by
39223 **   hot-journal rollback).
39224 */
39225 SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
39226   int rc = SQLITE_OK;                  /* Return code */
39227   PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
39228   if( pagerUseWal(pPager) ){
39229     int rc2;
39230
39231     rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
39232     rc2 = pager_end_transaction(pPager, pPager->setMaster);
39233     if( rc==SQLITE_OK ) rc = rc2;
39234     rc = pager_error(pPager, rc);
39235   }else if( !pPager->dbModified || !isOpen(pPager->jfd) ){
39236     rc = pager_end_transaction(pPager, pPager->setMaster);
39237   }else if( pPager->errCode && pPager->errCode!=SQLITE_FULL ){
39238     if( pPager->state>=PAGER_EXCLUSIVE ){
39239       pager_playback(pPager, 0);
39240     }
39241     rc = pPager->errCode;
39242   }else{
39243     if( pPager->state==PAGER_RESERVED ){
39244       int rc2;
39245       rc = pager_playback(pPager, 0);
39246       rc2 = pager_end_transaction(pPager, pPager->setMaster);
39247       if( rc==SQLITE_OK ){
39248         rc = rc2;
39249       }
39250     }else{
39251       rc = pager_playback(pPager, 0);
39252     }
39253
39254     if( !MEMDB ){
39255       pPager->dbSizeValid = 0;
39256     }
39257
39258     /* If an error occurs during a ROLLBACK, we can no longer trust the pager
39259     ** cache. So call pager_error() on the way out to make any error 
39260     ** persistent.
39261     */
39262     rc = pager_error(pPager, rc);
39263   }
39264   return rc;
39265 }
39266
39267 /*
39268 ** Return TRUE if the database file is opened read-only.  Return FALSE
39269 ** if the database is (in theory) writable.
39270 */
39271 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
39272   return pPager->readOnly;
39273 }
39274
39275 /*
39276 ** Return the number of references to the pager.
39277 */
39278 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
39279   return sqlite3PcacheRefCount(pPager->pPCache);
39280 }
39281
39282 /*
39283 ** Return the approximate number of bytes of memory currently
39284 ** used by the pager and its associated cache.
39285 */
39286 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
39287   int perPageSize = pPager->pageSize + pPager->nExtra + 20;
39288   return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
39289            + sqlite3MallocSize(pPager);
39290 }
39291
39292 /*
39293 ** Return the number of references to the specified page.
39294 */
39295 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
39296   return sqlite3PcachePageRefcount(pPage);
39297 }
39298
39299 #ifdef SQLITE_TEST
39300 /*
39301 ** This routine is used for testing and analysis only.
39302 */
39303 SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
39304   static int a[11];
39305   a[0] = sqlite3PcacheRefCount(pPager->pPCache);
39306   a[1] = sqlite3PcachePagecount(pPager->pPCache);
39307   a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
39308   a[3] = pPager->dbSizeValid ? (int) pPager->dbSize : -1;
39309   a[4] = pPager->state;
39310   a[5] = pPager->errCode;
39311   a[6] = pPager->nHit;
39312   a[7] = pPager->nMiss;
39313   a[8] = 0;  /* Used to be pPager->nOvfl */
39314   a[9] = pPager->nRead;
39315   a[10] = pPager->nWrite;
39316   return a;
39317 }
39318 #endif
39319
39320 /*
39321 ** Return true if this is an in-memory pager.
39322 */
39323 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
39324   return MEMDB;
39325 }
39326
39327 /*
39328 ** Check that there are at least nSavepoint savepoints open. If there are
39329 ** currently less than nSavepoints open, then open one or more savepoints
39330 ** to make up the difference. If the number of savepoints is already
39331 ** equal to nSavepoint, then this function is a no-op.
39332 **
39333 ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error 
39334 ** occurs while opening the sub-journal file, then an IO error code is
39335 ** returned. Otherwise, SQLITE_OK.
39336 */
39337 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
39338   int rc = SQLITE_OK;                       /* Return code */
39339   int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
39340
39341   if( nSavepoint>nCurrent && pPager->useJournal ){
39342     int ii;                                 /* Iterator variable */
39343     PagerSavepoint *aNew;                   /* New Pager.aSavepoint array */
39344     int nPage;                              /* Size of database file */
39345
39346     rc = sqlite3PagerPagecount(pPager, &nPage);
39347     if( rc ) return rc;
39348
39349     /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
39350     ** if the allocation fails. Otherwise, zero the new portion in case a 
39351     ** malloc failure occurs while populating it in the for(...) loop below.
39352     */
39353     aNew = (PagerSavepoint *)sqlite3Realloc(
39354         pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
39355     );
39356     if( !aNew ){
39357       return SQLITE_NOMEM;
39358     }
39359     memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
39360     pPager->aSavepoint = aNew;
39361
39362     /* Populate the PagerSavepoint structures just allocated. */
39363     for(ii=nCurrent; ii<nSavepoint; ii++){
39364       aNew[ii].nOrig = nPage;
39365       if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
39366         aNew[ii].iOffset = pPager->journalOff;
39367       }else{
39368         aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
39369       }
39370       aNew[ii].iSubRec = pPager->nSubRec;
39371       aNew[ii].pInSavepoint = sqlite3BitvecCreate(nPage);
39372       if( !aNew[ii].pInSavepoint ){
39373         return SQLITE_NOMEM;
39374       }
39375       if( pagerUseWal(pPager) ){
39376         sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
39377       }
39378       pPager->nSavepoint = ii+1;
39379     }
39380     assert( pPager->nSavepoint==nSavepoint );
39381     assertTruncateConstraint(pPager);
39382   }
39383
39384   return rc;
39385 }
39386
39387 /*
39388 ** This function is called to rollback or release (commit) a savepoint.
39389 ** The savepoint to release or rollback need not be the most recently 
39390 ** created savepoint.
39391 **
39392 ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
39393 ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
39394 ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
39395 ** that have occurred since the specified savepoint was created.
39396 **
39397 ** The savepoint to rollback or release is identified by parameter 
39398 ** iSavepoint. A value of 0 means to operate on the outermost savepoint
39399 ** (the first created). A value of (Pager.nSavepoint-1) means operate
39400 ** on the most recently created savepoint. If iSavepoint is greater than
39401 ** (Pager.nSavepoint-1), then this function is a no-op.
39402 **
39403 ** If a negative value is passed to this function, then the current
39404 ** transaction is rolled back. This is different to calling 
39405 ** sqlite3PagerRollback() because this function does not terminate
39406 ** the transaction or unlock the database, it just restores the 
39407 ** contents of the database to its original state. 
39408 **
39409 ** In any case, all savepoints with an index greater than iSavepoint 
39410 ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
39411 ** then savepoint iSavepoint is also destroyed.
39412 **
39413 ** This function may return SQLITE_NOMEM if a memory allocation fails,
39414 ** or an IO error code if an IO error occurs while rolling back a 
39415 ** savepoint. If no errors occur, SQLITE_OK is returned.
39416 */ 
39417 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
39418   int rc = SQLITE_OK;
39419
39420   assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
39421   assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
39422
39423   if( iSavepoint<pPager->nSavepoint ){
39424     int ii;            /* Iterator variable */
39425     int nNew;          /* Number of remaining savepoints after this op. */
39426
39427     /* Figure out how many savepoints will still be active after this
39428     ** operation. Store this value in nNew. Then free resources associated 
39429     ** with any savepoints that are destroyed by this operation.
39430     */
39431     nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
39432     for(ii=nNew; ii<pPager->nSavepoint; ii++){
39433       sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
39434     }
39435     pPager->nSavepoint = nNew;
39436
39437     /* If this is a release of the outermost savepoint, truncate 
39438     ** the sub-journal to zero bytes in size. */
39439     if( op==SAVEPOINT_RELEASE ){
39440       if( nNew==0 && isOpen(pPager->sjfd) ){
39441         /* Only truncate if it is an in-memory sub-journal. */
39442         if( sqlite3IsMemJournal(pPager->sjfd) ){
39443           rc = sqlite3OsTruncate(pPager->sjfd, 0);
39444           assert( rc==SQLITE_OK );
39445         }
39446         pPager->nSubRec = 0;
39447       }
39448     }
39449     /* Else this is a rollback operation, playback the specified savepoint.
39450     ** If this is a temp-file, it is possible that the journal file has
39451     ** not yet been opened. In this case there have been no changes to
39452     ** the database file, so the playback operation can be skipped.
39453     */
39454     else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
39455       PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
39456       rc = pagerPlaybackSavepoint(pPager, pSavepoint);
39457       assert(rc!=SQLITE_DONE);
39458     }
39459   
39460   }
39461   return rc;
39462 }
39463
39464 /*
39465 ** Return the full pathname of the database file.
39466 */
39467 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager){
39468   return pPager->zFilename;
39469 }
39470
39471 /*
39472 ** Return the VFS structure for the pager.
39473 */
39474 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
39475   return pPager->pVfs;
39476 }
39477
39478 /*
39479 ** Return the file handle for the database file associated
39480 ** with the pager.  This might return NULL if the file has
39481 ** not yet been opened.
39482 */
39483 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
39484   return pPager->fd;
39485 }
39486
39487 /*
39488 ** Return the full pathname of the journal file.
39489 */
39490 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
39491   return pPager->zJournal;
39492 }
39493
39494 /*
39495 ** Return true if fsync() calls are disabled for this pager.  Return FALSE
39496 ** if fsync()s are executed normally.
39497 */
39498 SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
39499   return pPager->noSync;
39500 }
39501
39502 #ifdef SQLITE_HAS_CODEC
39503 /*
39504 ** Set or retrieve the codec for this pager
39505 */
39506 SQLITE_PRIVATE void sqlite3PagerSetCodec(
39507   Pager *pPager,
39508   void *(*xCodec)(void*,void*,Pgno,int),
39509   void (*xCodecSizeChng)(void*,int,int),
39510   void (*xCodecFree)(void*),
39511   void *pCodec
39512 ){
39513   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
39514   pPager->xCodec = pPager->memDb ? 0 : xCodec;
39515   pPager->xCodecSizeChng = xCodecSizeChng;
39516   pPager->xCodecFree = xCodecFree;
39517   pPager->pCodec = pCodec;
39518   pagerReportSize(pPager);
39519 }
39520 SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
39521   return pPager->pCodec;
39522 }
39523 #endif
39524
39525 #ifndef SQLITE_OMIT_AUTOVACUUM
39526 /*
39527 ** Move the page pPg to location pgno in the file.
39528 **
39529 ** There must be no references to the page previously located at
39530 ** pgno (which we call pPgOld) though that page is allowed to be
39531 ** in cache.  If the page previously located at pgno is not already
39532 ** in the rollback journal, it is not put there by by this routine.
39533 **
39534 ** References to the page pPg remain valid. Updating any
39535 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
39536 ** allocated along with the page) is the responsibility of the caller.
39537 **
39538 ** A transaction must be active when this routine is called. It used to be
39539 ** required that a statement transaction was not active, but this restriction
39540 ** has been removed (CREATE INDEX needs to move a page when a statement
39541 ** transaction is active).
39542 **
39543 ** If the fourth argument, isCommit, is non-zero, then this page is being
39544 ** moved as part of a database reorganization just before the transaction 
39545 ** is being committed. In this case, it is guaranteed that the database page 
39546 ** pPg refers to will not be written to again within this transaction.
39547 **
39548 ** This function may return SQLITE_NOMEM or an IO error code if an error
39549 ** occurs. Otherwise, it returns SQLITE_OK.
39550 */
39551 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
39552   PgHdr *pPgOld;               /* The page being overwritten. */
39553   Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
39554   int rc;                      /* Return code */
39555   Pgno origPgno;               /* The original page number */
39556
39557   assert( pPg->nRef>0 );
39558
39559   /* In order to be able to rollback, an in-memory database must journal
39560   ** the page we are moving from.
39561   */
39562   if( MEMDB ){
39563     rc = sqlite3PagerWrite(pPg);
39564     if( rc ) return rc;
39565   }
39566
39567   /* If the page being moved is dirty and has not been saved by the latest
39568   ** savepoint, then save the current contents of the page into the 
39569   ** sub-journal now. This is required to handle the following scenario:
39570   **
39571   **   BEGIN;
39572   **     <journal page X, then modify it in memory>
39573   **     SAVEPOINT one;
39574   **       <Move page X to location Y>
39575   **     ROLLBACK TO one;
39576   **
39577   ** If page X were not written to the sub-journal here, it would not
39578   ** be possible to restore its contents when the "ROLLBACK TO one"
39579   ** statement were is processed.
39580   **
39581   ** subjournalPage() may need to allocate space to store pPg->pgno into
39582   ** one or more savepoint bitvecs. This is the reason this function
39583   ** may return SQLITE_NOMEM.
39584   */
39585   if( pPg->flags&PGHDR_DIRTY
39586    && subjRequiresPage(pPg)
39587    && SQLITE_OK!=(rc = subjournalPage(pPg))
39588   ){
39589     return rc;
39590   }
39591
39592   PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n", 
39593       PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
39594   IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
39595
39596   /* If the journal needs to be sync()ed before page pPg->pgno can
39597   ** be written to, store pPg->pgno in local variable needSyncPgno.
39598   **
39599   ** If the isCommit flag is set, there is no need to remember that
39600   ** the journal needs to be sync()ed before database page pPg->pgno 
39601   ** can be written to. The caller has already promised not to write to it.
39602   */
39603   if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
39604     needSyncPgno = pPg->pgno;
39605     assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
39606     assert( pPg->flags&PGHDR_DIRTY );
39607     assert( pPager->needSync );
39608   }
39609
39610   /* If the cache contains a page with page-number pgno, remove it
39611   ** from its hash chain. Also, if the PgHdr.needSync was set for 
39612   ** page pgno before the 'move' operation, it needs to be retained 
39613   ** for the page moved there.
39614   */
39615   pPg->flags &= ~PGHDR_NEED_SYNC;
39616   pPgOld = pager_lookup(pPager, pgno);
39617   assert( !pPgOld || pPgOld->nRef==1 );
39618   if( pPgOld ){
39619     pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
39620     if( MEMDB ){
39621       /* Do not discard pages from an in-memory database since we might
39622       ** need to rollback later.  Just move the page out of the way. */
39623       assert( pPager->dbSizeValid );
39624       sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
39625     }else{
39626       sqlite3PcacheDrop(pPgOld);
39627     }
39628   }
39629
39630   origPgno = pPg->pgno;
39631   sqlite3PcacheMove(pPg, pgno);
39632   sqlite3PcacheMakeDirty(pPg);
39633   pPager->dbModified = 1;
39634
39635   if( needSyncPgno ){
39636     /* If needSyncPgno is non-zero, then the journal file needs to be 
39637     ** sync()ed before any data is written to database file page needSyncPgno.
39638     ** Currently, no such page exists in the page-cache and the 
39639     ** "is journaled" bitvec flag has been set. This needs to be remedied by
39640     ** loading the page into the pager-cache and setting the PgHdr.needSync 
39641     ** flag.
39642     **
39643     ** If the attempt to load the page into the page-cache fails, (due
39644     ** to a malloc() or IO failure), clear the bit in the pInJournal[]
39645     ** array. Otherwise, if the page is loaded and written again in
39646     ** this transaction, it may be written to the database file before
39647     ** it is synced into the journal file. This way, it may end up in
39648     ** the journal file twice, but that is not a problem.
39649     **
39650     ** The sqlite3PagerGet() call may cause the journal to sync. So make
39651     ** sure the Pager.needSync flag is set too.
39652     */
39653     PgHdr *pPgHdr;
39654     assert( pPager->needSync );
39655     rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
39656     if( rc!=SQLITE_OK ){
39657       if( needSyncPgno<=pPager->dbOrigSize ){
39658         assert( pPager->pTmpSpace!=0 );
39659         sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
39660       }
39661       return rc;
39662     }
39663     pPager->needSync = 1;
39664     assert( pPager->noSync==0 && !MEMDB );
39665     pPgHdr->flags |= PGHDR_NEED_SYNC;
39666     sqlite3PcacheMakeDirty(pPgHdr);
39667     sqlite3PagerUnref(pPgHdr);
39668   }
39669
39670   /*
39671   ** For an in-memory database, make sure the original page continues
39672   ** to exist, in case the transaction needs to roll back.  Use pPgOld
39673   ** as the original page since it has already been allocated.
39674   */
39675   if( MEMDB ){
39676     sqlite3PcacheMove(pPgOld, origPgno);
39677     sqlite3PagerUnref(pPgOld);
39678   }
39679
39680   return SQLITE_OK;
39681 }
39682 #endif
39683
39684 /*
39685 ** Return a pointer to the data for the specified page.
39686 */
39687 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
39688   assert( pPg->nRef>0 || pPg->pPager->memDb );
39689   return pPg->pData;
39690 }
39691
39692 /*
39693 ** Return a pointer to the Pager.nExtra bytes of "extra" space 
39694 ** allocated along with the specified page.
39695 */
39696 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
39697   return pPg->pExtra;
39698 }
39699
39700 /*
39701 ** Get/set the locking-mode for this pager. Parameter eMode must be one
39702 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or 
39703 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
39704 ** the locking-mode is set to the value specified.
39705 **
39706 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
39707 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
39708 ** locking-mode.
39709 */
39710 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
39711   assert( eMode==PAGER_LOCKINGMODE_QUERY
39712             || eMode==PAGER_LOCKINGMODE_NORMAL
39713             || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
39714   assert( PAGER_LOCKINGMODE_QUERY<0 );
39715   assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
39716   if( eMode>=0 && !pPager->tempFile ){
39717     pPager->exclusiveMode = (u8)eMode;
39718   }
39719   return (int)pPager->exclusiveMode;
39720 }
39721
39722 /*
39723 ** Set the journal-mode for this pager. Parameter eMode must be one of:
39724 **
39725 **    PAGER_JOURNALMODE_DELETE
39726 **    PAGER_JOURNALMODE_TRUNCATE
39727 **    PAGER_JOURNALMODE_PERSIST
39728 **    PAGER_JOURNALMODE_OFF
39729 **    PAGER_JOURNALMODE_MEMORY
39730 **    PAGER_JOURNALMODE_WAL
39731 **
39732 ** The journalmode is set to the value specified if the change is allowed.
39733 ** The change may be disallowed for the following reasons:
39734 **
39735 **   *  An in-memory database can only have its journal_mode set to _OFF
39736 **      or _MEMORY.
39737 **
39738 **   *  Temporary databases cannot have _WAL journalmode.
39739 **
39740 ** The returned indicate the current (possibly updated) journal-mode.
39741 */
39742 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
39743   u8 eOld = pPager->journalMode;    /* Prior journalmode */
39744
39745   /* The eMode parameter is always valid */
39746   assert(      eMode==PAGER_JOURNALMODE_DELETE
39747             || eMode==PAGER_JOURNALMODE_TRUNCATE
39748             || eMode==PAGER_JOURNALMODE_PERSIST
39749             || eMode==PAGER_JOURNALMODE_OFF 
39750             || eMode==PAGER_JOURNALMODE_WAL 
39751             || eMode==PAGER_JOURNALMODE_MEMORY );
39752
39753   /* This routine is only called from the OP_JournalMode opcode, and
39754   ** the logic there will never allow a temporary file to be changed
39755   ** to WAL mode.
39756   */
39757   assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
39758
39759   /* Do allow the journalmode of an in-memory database to be set to
39760   ** anything other than MEMORY or OFF
39761   */
39762   if( MEMDB ){
39763     assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
39764     if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
39765       eMode = eOld;
39766     }
39767   }
39768
39769   if( eMode!=eOld ){
39770     /* When changing between rollback modes, close the journal file prior
39771     ** to the change.  But when changing from a rollback mode to WAL, keep
39772     ** the journal open since there is a rollback-style transaction in play
39773     ** used to convert the version numbers in the btree header.
39774     */
39775     if( isOpen(pPager->jfd) && eMode!=PAGER_JOURNALMODE_WAL ){
39776       sqlite3OsClose(pPager->jfd);
39777     }
39778
39779     /* Change the journal mode. */
39780     pPager->journalMode = (u8)eMode;
39781
39782     /* When transistioning from TRUNCATE or PERSIST to any other journal
39783     ** mode except WAL (and we are not in locking_mode=EXCLUSIVE) then 
39784     ** delete the journal file.
39785     */
39786     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
39787     assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
39788     assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
39789     assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
39790     assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
39791     assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
39792
39793     assert( isOpen(pPager->fd) || pPager->exclusiveMode );
39794     if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
39795
39796       /* In this case we would like to delete the journal file. If it is
39797       ** not possible, then that is not a problem. Deleting the journal file
39798       ** here is an optimization only.
39799       **
39800       ** Before deleting the journal file, obtain a RESERVED lock on the
39801       ** database file. This ensures that the journal file is not deleted
39802       ** while it is in use by some other client.
39803       */
39804       int rc = SQLITE_OK;
39805       int state = pPager->state;
39806       if( state<PAGER_SHARED ){
39807         rc = sqlite3PagerSharedLock(pPager);
39808       }
39809       if( pPager->state==PAGER_SHARED ){
39810         assert( rc==SQLITE_OK );
39811         rc = sqlite3OsLock(pPager->fd, RESERVED_LOCK);
39812       }
39813       if( rc==SQLITE_OK ){
39814         sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
39815       }
39816       if( rc==SQLITE_OK && state==PAGER_SHARED ){
39817         sqlite3OsUnlock(pPager->fd, SHARED_LOCK);
39818       }else if( state==PAGER_UNLOCK ){
39819         pager_unlock(pPager);
39820       }
39821       assert( state==pPager->state );
39822     }
39823   }
39824
39825   /* Return the new journal mode */
39826   return (int)pPager->journalMode;
39827 }
39828
39829 /*
39830 ** Return the current journal mode.
39831 */
39832 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
39833   return (int)pPager->journalMode;
39834 }
39835
39836 /*
39837 ** Return TRUE if the pager is in a state where it is OK to change the
39838 ** journalmode.  Journalmode changes can only happen when the database
39839 ** is unmodified.
39840 */
39841 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
39842   if( pPager->dbModified ) return 0;
39843   if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
39844   return 1;
39845 }
39846
39847 /*
39848 ** Get/set the size-limit used for persistent journal files.
39849 **
39850 ** Setting the size limit to -1 means no limit is enforced.
39851 ** An attempt to set a limit smaller than -1 is a no-op.
39852 */
39853 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
39854   if( iLimit>=-1 ){
39855     pPager->journalSizeLimit = iLimit;
39856   }
39857   return pPager->journalSizeLimit;
39858 }
39859
39860 /*
39861 ** Return a pointer to the pPager->pBackup variable. The backup module
39862 ** in backup.c maintains the content of this variable. This module
39863 ** uses it opaquely as an argument to sqlite3BackupRestart() and
39864 ** sqlite3BackupUpdate() only.
39865 */
39866 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
39867   return &pPager->pBackup;
39868 }
39869
39870 #ifndef SQLITE_OMIT_WAL
39871 /*
39872 ** This function is called when the user invokes "PRAGMA checkpoint".
39873 */
39874 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager){
39875   int rc = SQLITE_OK;
39876   if( pPager->pWal ){
39877     u8 *zBuf = (u8 *)pPager->pTmpSpace;
39878     rc = sqlite3WalCheckpoint(pPager->pWal,
39879         (pPager->noSync ? 0 : pPager->sync_flags),
39880         pPager->pageSize, zBuf
39881     );
39882   }
39883   return rc;
39884 }
39885
39886 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
39887   return sqlite3WalCallback(pPager->pWal);
39888 }
39889
39890 /*
39891 ** Return true if the underlying VFS for the given pager supports the
39892 ** primitives necessary for write-ahead logging.
39893 */
39894 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
39895   const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
39896   return pMethods->iVersion>=2 && pMethods->xShmMap!=0;
39897 }
39898
39899 /*
39900 ** The caller must be holding a SHARED lock on the database file to call
39901 ** this function.
39902 **
39903 ** If the pager passed as the first argument is open on a real database
39904 ** file (not a temp file or an in-memory database), and the WAL file
39905 ** is not already open, make an attempt to open it now. If successful,
39906 ** return SQLITE_OK. If an error occurs or the VFS used by the pager does 
39907 ** not support the xShmXXX() methods, return an error code. *pisOpen is
39908 ** not modified in either case.
39909 **
39910 ** If the pager is open on a temp-file (or in-memory database), or if
39911 ** the WAL file is already open, set *pisOpen to 1 and return SQLITE_OK
39912 ** without doing anything.
39913 */
39914 SQLITE_PRIVATE int sqlite3PagerOpenWal(
39915   Pager *pPager,                  /* Pager object */
39916   int *pisOpen                    /* OUT: Set to true if call is a no-op */
39917 ){
39918   int rc = SQLITE_OK;             /* Return code */
39919
39920   assert( pPager->state>=PAGER_SHARED );
39921   assert( (pisOpen==0 && !pPager->tempFile && !pPager->pWal) || *pisOpen==0 );
39922
39923   if( !pPager->tempFile && !pPager->pWal ){
39924     if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
39925
39926     /* Open the connection to the log file. If this operation fails, 
39927     ** (e.g. due to malloc() failure), unlock the database file and 
39928     ** return an error code.
39929     */
39930     rc = sqlite3WalOpen(pPager->pVfs, pPager->fd, pPager->zWal, &pPager->pWal);
39931     if( rc==SQLITE_OK ){
39932       pPager->journalMode = PAGER_JOURNALMODE_WAL;
39933     }
39934   }else{
39935     *pisOpen = 1;
39936   }
39937
39938   return rc;
39939 }
39940
39941 /*
39942 ** This function is called to close the connection to the log file prior
39943 ** to switching from WAL to rollback mode.
39944 **
39945 ** Before closing the log file, this function attempts to take an 
39946 ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
39947 ** error (SQLITE_BUSY) is returned and the log connection is not closed.
39948 ** If successful, the EXCLUSIVE lock is not released before returning.
39949 */
39950 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
39951   int rc = SQLITE_OK;
39952
39953   assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
39954
39955   /* If the log file is not already open, but does exist in the file-system,
39956   ** it may need to be checkpointed before the connection can switch to
39957   ** rollback mode. Open it now so this can happen.
39958   */
39959   if( !pPager->pWal ){
39960     int logexists = 0;
39961     rc = sqlite3OsLock(pPager->fd, SQLITE_LOCK_SHARED);
39962     if( rc==SQLITE_OK ){
39963       rc = sqlite3OsAccess(
39964           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
39965       );
39966     }
39967     if( rc==SQLITE_OK && logexists ){
39968       rc = sqlite3WalOpen(pPager->pVfs, pPager->fd,
39969                           pPager->zWal, &pPager->pWal);
39970     }
39971   }
39972     
39973   /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
39974   ** the database file, the log and log-summary files will be deleted.
39975   */
39976   if( rc==SQLITE_OK && pPager->pWal ){
39977     rc = sqlite3OsLock(pPager->fd, SQLITE_LOCK_EXCLUSIVE);
39978     if( rc==SQLITE_OK ){
39979       rc = sqlite3WalClose(pPager->pWal,
39980                            (pPager->noSync ? 0 : pPager->sync_flags), 
39981         pPager->pageSize, (u8*)pPager->pTmpSpace
39982       );
39983       pPager->pWal = 0;
39984     }else{
39985       /* If we cannot get an EXCLUSIVE lock, downgrade the PENDING lock
39986       ** that we did get back to SHARED. */
39987       sqlite3OsUnlock(pPager->fd, SQLITE_LOCK_SHARED);
39988     }
39989   }
39990   return rc;
39991 }
39992
39993 #ifdef SQLITE_HAS_CODEC
39994 /*
39995 ** This function is called by the wal module when writing page content
39996 ** into the log file.
39997 **
39998 ** This function returns a pointer to a buffer containing the encrypted
39999 ** page content. If a malloc fails, this function may return NULL.
40000 */
40001 SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
40002   void *aData = 0;
40003   CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
40004   return aData;
40005 }
40006 #endif /* SQLITE_HAS_CODEC */
40007
40008 #endif /* !SQLITE_OMIT_WAL */
40009
40010 #endif /* SQLITE_OMIT_DISKIO */
40011
40012 /************** End of pager.c ***********************************************/
40013 /************** Begin file wal.c *********************************************/
40014 /*
40015 ** 2010 February 1
40016 **
40017 ** The author disclaims copyright to this source code.  In place of
40018 ** a legal notice, here is a blessing:
40019 **
40020 **    May you do good and not evil.
40021 **    May you find forgiveness for yourself and forgive others.
40022 **    May you share freely, never taking more than you give.
40023 **
40024 *************************************************************************
40025 **
40026 ** This file contains the implementation of a write-ahead log (WAL) used in 
40027 ** "journal_mode=WAL" mode.
40028 **
40029 ** WRITE-AHEAD LOG (WAL) FILE FORMAT
40030 **
40031 ** A WAL file consists of a header followed by zero or more "frames".
40032 ** Each frame records the revised content of a single page from the
40033 ** database file.  All changes to the database are recorded by writing
40034 ** frames into the WAL.  Transactions commit when a frame is written that
40035 ** contains a commit marker.  A single WAL can and usually does record 
40036 ** multiple transactions.  Periodically, the content of the WAL is
40037 ** transferred back into the database file in an operation called a
40038 ** "checkpoint".
40039 **
40040 ** A single WAL file can be used multiple times.  In other words, the
40041 ** WAL can fill up with frames and then be checkpointed and then new
40042 ** frames can overwrite the old ones.  A WAL always grows from beginning
40043 ** toward the end.  Checksums and counters attached to each frame are
40044 ** used to determine which frames within the WAL are valid and which
40045 ** are leftovers from prior checkpoints.
40046 **
40047 ** The WAL header is 32 bytes in size and consists of the following eight
40048 ** big-endian 32-bit unsigned integer values:
40049 **
40050 **     0: Magic number.  0x377f0682 or 0x377f0683
40051 **     4: File format version.  Currently 3007000
40052 **     8: Database page size.  Example: 1024
40053 **    12: Checkpoint sequence number
40054 **    16: Salt-1, random integer incremented with each checkpoint
40055 **    20: Salt-2, a different random integer changing with each ckpt
40056 **    24: Checksum-1 (first part of checksum for first 24 bytes of header).
40057 **    28: Checksum-2 (second part of checksum for first 24 bytes of header).
40058 **
40059 ** Immediately following the wal-header are zero or more frames. Each
40060 ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
40061 ** of page data. The frame-header is six big-endian 32-bit unsigned 
40062 ** integer values, as follows:
40063 **
40064 **     0: Page number.
40065 **     4: For commit records, the size of the database image in pages 
40066 **        after the commit. For all other records, zero.
40067 **     8: Salt-1 (copied from the header)
40068 **    12: Salt-2 (copied from the header)
40069 **    16: Checksum-1.
40070 **    20: Checksum-2.
40071 **
40072 ** A frame is considered valid if and only if the following conditions are
40073 ** true:
40074 **
40075 **    (1) The salt-1 and salt-2 values in the frame-header match
40076 **        salt values in the wal-header
40077 **
40078 **    (2) The checksum values in the final 8 bytes of the frame-header
40079 **        exactly match the checksum computed consecutively on the
40080 **        WAL header and the first 8 bytes and the content of all frames
40081 **        up to and including the current frame.
40082 **
40083 ** The checksum is computed using 32-bit big-endian integers if the
40084 ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
40085 ** is computed using little-endian if the magic number is 0x377f0682.
40086 ** The checksum values are always stored in the frame header in a
40087 ** big-endian format regardless of which byte order is used to compute
40088 ** the checksum.  The checksum is computed by interpreting the input as
40089 ** an even number of unsigned 32-bit integers: x[0] through x[N].  The
40090 ** algorithm used for the checksum is as follows:
40091 ** 
40092 **   for i from 0 to n-1 step 2:
40093 **     s0 += x[i] + s1;
40094 **     s1 += x[i+1] + s0;
40095 **   endfor
40096 **
40097 ** Note that s0 and s1 are both weighted checksums using fibonacci weights
40098 ** in reverse order (the largest fibonacci weight occurs on the first element
40099 ** of the sequence being summed.)  The s1 value spans all 32-bit 
40100 ** terms of the sequence whereas s0 omits the final term.
40101 **
40102 ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
40103 ** WAL is transferred into the database, then the database is VFS.xSync-ed.
40104 ** The VFS.xSync operations serve as write barriers - all writes launched
40105 ** before the xSync must complete before any write that launches after the
40106 ** xSync begins.
40107 **
40108 ** After each checkpoint, the salt-1 value is incremented and the salt-2
40109 ** value is randomized.  This prevents old and new frames in the WAL from
40110 ** being considered valid at the same time and being checkpointing together
40111 ** following a crash.
40112 **
40113 ** READER ALGORITHM
40114 **
40115 ** To read a page from the database (call it page number P), a reader
40116 ** first checks the WAL to see if it contains page P.  If so, then the
40117 ** last valid instance of page P that is a followed by a commit frame
40118 ** or is a commit frame itself becomes the value read.  If the WAL
40119 ** contains no copies of page P that are valid and which are a commit
40120 ** frame or are followed by a commit frame, then page P is read from
40121 ** the database file.
40122 **
40123 ** To start a read transaction, the reader records the index of the last
40124 ** valid frame in the WAL.  The reader uses this recorded "mxFrame" value
40125 ** for all subsequent read operations.  New transactions can be appended
40126 ** to the WAL, but as long as the reader uses its original mxFrame value
40127 ** and ignores the newly appended content, it will see a consistent snapshot
40128 ** of the database from a single point in time.  This technique allows
40129 ** multiple concurrent readers to view different versions of the database
40130 ** content simultaneously.
40131 **
40132 ** The reader algorithm in the previous paragraphs works correctly, but 
40133 ** because frames for page P can appear anywhere within the WAL, the
40134 ** reader has to scan the entire WAL looking for page P frames.  If the
40135 ** WAL is large (multiple megabytes is typical) that scan can be slow,
40136 ** and read performance suffers.  To overcome this problem, a separate
40137 ** data structure called the wal-index is maintained to expedite the
40138 ** search for frames of a particular page.
40139 ** 
40140 ** WAL-INDEX FORMAT
40141 **
40142 ** Conceptually, the wal-index is shared memory, though VFS implementations
40143 ** might choose to implement the wal-index using a mmapped file.  Because
40144 ** the wal-index is shared memory, SQLite does not support journal_mode=WAL 
40145 ** on a network filesystem.  All users of the database must be able to
40146 ** share memory.
40147 **
40148 ** The wal-index is transient.  After a crash, the wal-index can (and should
40149 ** be) reconstructed from the original WAL file.  In fact, the VFS is required
40150 ** to either truncate or zero the header of the wal-index when the last
40151 ** connection to it closes.  Because the wal-index is transient, it can
40152 ** use an architecture-specific format; it does not have to be cross-platform.
40153 ** Hence, unlike the database and WAL file formats which store all values
40154 ** as big endian, the wal-index can store multi-byte values in the native
40155 ** byte order of the host computer.
40156 **
40157 ** The purpose of the wal-index is to answer this question quickly:  Given
40158 ** a page number P, return the index of the last frame for page P in the WAL,
40159 ** or return NULL if there are no frames for page P in the WAL.
40160 **
40161 ** The wal-index consists of a header region, followed by an one or
40162 ** more index blocks.  
40163 **
40164 ** The wal-index header contains the total number of frames within the WAL
40165 ** in the the mxFrame field.  
40166 **
40167 ** Each index block except for the first contains information on 
40168 ** HASHTABLE_NPAGE frames. The first index block contains information on
40169 ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and 
40170 ** HASHTABLE_NPAGE are selected so that together the wal-index header and
40171 ** first index block are the same size as all other index blocks in the
40172 ** wal-index.
40173 **
40174 ** Each index block contains two sections, a page-mapping that contains the
40175 ** database page number associated with each wal frame, and a hash-table 
40176 ** that allows readers to query an index block for a specific page number.
40177 ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
40178 ** for the first index block) 32-bit page numbers. The first entry in the 
40179 ** first index-block contains the database page number corresponding to the
40180 ** first frame in the WAL file. The first entry in the second index block
40181 ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
40182 ** the log, and so on.
40183 **
40184 ** The last index block in a wal-index usually contains less than the full
40185 ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
40186 ** depending on the contents of the WAL file. This does not change the
40187 ** allocated size of the page-mapping array - the page-mapping array merely
40188 ** contains unused entries.
40189 **
40190 ** Even without using the hash table, the last frame for page P
40191 ** can be found by scanning the page-mapping sections of each index block
40192 ** starting with the last index block and moving toward the first, and
40193 ** within each index block, starting at the end and moving toward the
40194 ** beginning.  The first entry that equals P corresponds to the frame
40195 ** holding the content for that page.
40196 **
40197 ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
40198 ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
40199 ** hash table for each page number in the mapping section, so the hash 
40200 ** table is never more than half full.  The expected number of collisions 
40201 ** prior to finding a match is 1.  Each entry of the hash table is an
40202 ** 1-based index of an entry in the mapping section of the same
40203 ** index block.   Let K be the 1-based index of the largest entry in
40204 ** the mapping section.  (For index blocks other than the last, K will
40205 ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
40206 ** K will be (mxFrame%HASHTABLE_NPAGE).)  Unused slots of the hash table
40207 ** contain a value of 0.
40208 **
40209 ** To look for page P in the hash table, first compute a hash iKey on
40210 ** P as follows:
40211 **
40212 **      iKey = (P * 383) % HASHTABLE_NSLOT
40213 **
40214 ** Then start scanning entries of the hash table, starting with iKey
40215 ** (wrapping around to the beginning when the end of the hash table is
40216 ** reached) until an unused hash slot is found. Let the first unused slot
40217 ** be at index iUnused.  (iUnused might be less than iKey if there was
40218 ** wrap-around.) Because the hash table is never more than half full,
40219 ** the search is guaranteed to eventually hit an unused entry.  Let 
40220 ** iMax be the value between iKey and iUnused, closest to iUnused,
40221 ** where aHash[iMax]==P.  If there is no iMax entry (if there exists
40222 ** no hash slot such that aHash[i]==p) then page P is not in the
40223 ** current index block.  Otherwise the iMax-th mapping entry of the
40224 ** current index block corresponds to the last entry that references 
40225 ** page P.
40226 **
40227 ** A hash search begins with the last index block and moves toward the
40228 ** first index block, looking for entries corresponding to page P.  On
40229 ** average, only two or three slots in each index block need to be
40230 ** examined in order to either find the last entry for page P, or to
40231 ** establish that no such entry exists in the block.  Each index block
40232 ** holds over 4000 entries.  So two or three index blocks are sufficient
40233 ** to cover a typical 10 megabyte WAL file, assuming 1K pages.  8 or 10
40234 ** comparisons (on average) suffice to either locate a frame in the
40235 ** WAL or to establish that the frame does not exist in the WAL.  This
40236 ** is much faster than scanning the entire 10MB WAL.
40237 **
40238 ** Note that entries are added in order of increasing K.  Hence, one
40239 ** reader might be using some value K0 and a second reader that started
40240 ** at a later time (after additional transactions were added to the WAL
40241 ** and to the wal-index) might be using a different value K1, where K1>K0.
40242 ** Both readers can use the same hash table and mapping section to get
40243 ** the correct result.  There may be entries in the hash table with
40244 ** K>K0 but to the first reader, those entries will appear to be unused
40245 ** slots in the hash table and so the first reader will get an answer as
40246 ** if no values greater than K0 had ever been inserted into the hash table
40247 ** in the first place - which is what reader one wants.  Meanwhile, the
40248 ** second reader using K1 will see additional values that were inserted
40249 ** later, which is exactly what reader two wants.  
40250 **
40251 ** When a rollback occurs, the value of K is decreased. Hash table entries
40252 ** that correspond to frames greater than the new K value are removed
40253 ** from the hash table at this point.
40254 */
40255 #ifndef SQLITE_OMIT_WAL
40256
40257
40258 /*
40259 ** Trace output macros
40260 */
40261 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
40262 SQLITE_PRIVATE int sqlite3WalTrace = 0;
40263 # define WALTRACE(X)  if(sqlite3WalTrace) sqlite3DebugPrintf X
40264 #else
40265 # define WALTRACE(X)
40266 #endif
40267
40268 /*
40269 ** The maximum (and only) versions of the wal and wal-index formats
40270 ** that may be interpreted by this version of SQLite.
40271 **
40272 ** If a client begins recovering a WAL file and finds that (a) the checksum
40273 ** values in the wal-header are correct and (b) the version field is not
40274 ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
40275 **
40276 ** Similarly, if a client successfully reads a wal-index header (i.e. the 
40277 ** checksum test is successful) and finds that the version field is not
40278 ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
40279 ** returns SQLITE_CANTOPEN.
40280 */
40281 #define WAL_MAX_VERSION      3007000
40282 #define WALINDEX_MAX_VERSION 3007000
40283
40284 /*
40285 ** Indices of various locking bytes.   WAL_NREADER is the number
40286 ** of available reader locks and should be at least 3.
40287 */
40288 #define WAL_WRITE_LOCK         0
40289 #define WAL_ALL_BUT_WRITE      1
40290 #define WAL_CKPT_LOCK          1
40291 #define WAL_RECOVER_LOCK       2
40292 #define WAL_READ_LOCK(I)       (3+(I))
40293 #define WAL_NREADER            (SQLITE_SHM_NLOCK-3)
40294
40295
40296 /* Object declarations */
40297 typedef struct WalIndexHdr WalIndexHdr;
40298 typedef struct WalIterator WalIterator;
40299 typedef struct WalCkptInfo WalCkptInfo;
40300
40301
40302 /*
40303 ** The following object holds a copy of the wal-index header content.
40304 **
40305 ** The actual header in the wal-index consists of two copies of this
40306 ** object.
40307 */
40308 struct WalIndexHdr {
40309   u32 iVersion;                   /* Wal-index version */
40310   u32 unused;                     /* Unused (padding) field */
40311   u32 iChange;                    /* Counter incremented each transaction */
40312   u8 isInit;                      /* 1 when initialized */
40313   u8 bigEndCksum;                 /* True if checksums in WAL are big-endian */
40314   u16 szPage;                     /* Database page size in bytes */
40315   u32 mxFrame;                    /* Index of last valid frame in the WAL */
40316   u32 nPage;                      /* Size of database in pages */
40317   u32 aFrameCksum[2];             /* Checksum of last frame in log */
40318   u32 aSalt[2];                   /* Two salt values copied from WAL header */
40319   u32 aCksum[2];                  /* Checksum over all prior fields */
40320 };
40321
40322 /*
40323 ** A copy of the following object occurs in the wal-index immediately
40324 ** following the second copy of the WalIndexHdr.  This object stores
40325 ** information used by checkpoint.
40326 **
40327 ** nBackfill is the number of frames in the WAL that have been written
40328 ** back into the database. (We call the act of moving content from WAL to
40329 ** database "backfilling".)  The nBackfill number is never greater than
40330 ** WalIndexHdr.mxFrame.  nBackfill can only be increased by threads
40331 ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
40332 ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
40333 ** mxFrame back to zero when the WAL is reset.
40334 **
40335 ** There is one entry in aReadMark[] for each reader lock.  If a reader
40336 ** holds read-lock K, then the value in aReadMark[K] is no greater than
40337 ** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)
40338 ** for any aReadMark[] means that entry is unused.  aReadMark[0] is 
40339 ** a special case; its value is never used and it exists as a place-holder
40340 ** to avoid having to offset aReadMark[] indexs by one.  Readers holding
40341 ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
40342 ** directly from the database.
40343 **
40344 ** The value of aReadMark[K] may only be changed by a thread that
40345 ** is holding an exclusive lock on WAL_READ_LOCK(K).  Thus, the value of
40346 ** aReadMark[K] cannot changed while there is a reader is using that mark
40347 ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
40348 **
40349 ** The checkpointer may only transfer frames from WAL to database where
40350 ** the frame numbers are less than or equal to every aReadMark[] that is
40351 ** in use (that is, every aReadMark[j] for which there is a corresponding
40352 ** WAL_READ_LOCK(j)).  New readers (usually) pick the aReadMark[] with the
40353 ** largest value and will increase an unused aReadMark[] to mxFrame if there
40354 ** is not already an aReadMark[] equal to mxFrame.  The exception to the
40355 ** previous sentence is when nBackfill equals mxFrame (meaning that everything
40356 ** in the WAL has been backfilled into the database) then new readers
40357 ** will choose aReadMark[0] which has value 0 and hence such reader will
40358 ** get all their all content directly from the database file and ignore 
40359 ** the WAL.
40360 **
40361 ** Writers normally append new frames to the end of the WAL.  However,
40362 ** if nBackfill equals mxFrame (meaning that all WAL content has been
40363 ** written back into the database) and if no readers are using the WAL
40364 ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
40365 ** the writer will first "reset" the WAL back to the beginning and start
40366 ** writing new content beginning at frame 1.
40367 **
40368 ** We assume that 32-bit loads are atomic and so no locks are needed in
40369 ** order to read from any aReadMark[] entries.
40370 */
40371 struct WalCkptInfo {
40372   u32 nBackfill;                  /* Number of WAL frames backfilled into DB */
40373   u32 aReadMark[WAL_NREADER];     /* Reader marks */
40374 };
40375 #define READMARK_NOT_USED  0xffffffff
40376
40377
40378 /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
40379 ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
40380 ** only support mandatory file-locks, we do not read or write data
40381 ** from the region of the file on which locks are applied.
40382 */
40383 #define WALINDEX_LOCK_OFFSET   (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
40384 #define WALINDEX_LOCK_RESERVED 16
40385 #define WALINDEX_HDR_SIZE      (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
40386
40387 /* Size of header before each frame in wal */
40388 #define WAL_FRAME_HDRSIZE 24
40389
40390 /* Size of write ahead log header, including checksum. */
40391 /* #define WAL_HDRSIZE 24 */
40392 #define WAL_HDRSIZE 32
40393
40394 /* WAL magic value. Either this value, or the same value with the least
40395 ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
40396 ** big-endian format in the first 4 bytes of a WAL file.
40397 **
40398 ** If the LSB is set, then the checksums for each frame within the WAL
40399 ** file are calculated by treating all data as an array of 32-bit 
40400 ** big-endian words. Otherwise, they are calculated by interpreting 
40401 ** all data as 32-bit little-endian words.
40402 */
40403 #define WAL_MAGIC 0x377f0682
40404
40405 /*
40406 ** Return the offset of frame iFrame in the write-ahead log file, 
40407 ** assuming a database page size of szPage bytes. The offset returned
40408 ** is to the start of the write-ahead log frame-header.
40409 */
40410 #define walFrameOffset(iFrame, szPage) (                               \
40411   WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE)         \
40412 )
40413
40414 /*
40415 ** An open write-ahead log file is represented by an instance of the
40416 ** following object.
40417 */
40418 struct Wal {
40419   sqlite3_vfs *pVfs;         /* The VFS used to create pDbFd */
40420   sqlite3_file *pDbFd;       /* File handle for the database file */
40421   sqlite3_file *pWalFd;      /* File handle for WAL file */
40422   u32 iCallback;             /* Value to pass to log callback (or 0) */
40423   int nWiData;               /* Size of array apWiData */
40424   volatile u32 **apWiData;   /* Pointer to wal-index content in memory */
40425   u16 szPage;                /* Database page size */
40426   i16 readLock;              /* Which read lock is being held.  -1 for none */
40427   u8 exclusiveMode;          /* Non-zero if connection is in exclusive mode */
40428   u8 writeLock;              /* True if in a write transaction */
40429   u8 ckptLock;               /* True if holding a checkpoint lock */
40430   u8 readOnly;               /* True if the WAL file is open read-only */
40431   WalIndexHdr hdr;           /* Wal-index header for current transaction */
40432   const char *zWalName;      /* Name of WAL file */
40433   u32 nCkpt;                 /* Checkpoint sequence counter in the wal-header */
40434 #ifdef SQLITE_DEBUG
40435   u8 lockError;              /* True if a locking error has occurred */
40436 #endif
40437 };
40438
40439 /*
40440 ** Each page of the wal-index mapping contains a hash-table made up of
40441 ** an array of HASHTABLE_NSLOT elements of the following type.
40442 */
40443 typedef u16 ht_slot;
40444
40445 /*
40446 ** This structure is used to implement an iterator that loops through
40447 ** all frames in the WAL in database page order. Where two or more frames
40448 ** correspond to the same database page, the iterator visits only the 
40449 ** frame most recently written to the WAL (in other words, the frame with
40450 ** the largest index).
40451 **
40452 ** The internals of this structure are only accessed by:
40453 **
40454 **   walIteratorInit() - Create a new iterator,
40455 **   walIteratorNext() - Step an iterator,
40456 **   walIteratorFree() - Free an iterator.
40457 **
40458 ** This functionality is used by the checkpoint code (see walCheckpoint()).
40459 */
40460 struct WalIterator {
40461   int iPrior;                     /* Last result returned from the iterator */
40462   int nSegment;                   /* Size of the aSegment[] array */
40463   struct WalSegment {
40464     int iNext;                    /* Next slot in aIndex[] not yet returned */
40465     ht_slot *aIndex;              /* i0, i1, i2... such that aPgno[iN] ascend */
40466     u32 *aPgno;                   /* Array of page numbers. */
40467     int nEntry;                   /* Max size of aPgno[] and aIndex[] arrays */
40468     int iZero;                    /* Frame number associated with aPgno[0] */
40469   } aSegment[1];                  /* One for every 32KB page in the WAL */
40470 };
40471
40472 /*
40473 ** Define the parameters of the hash tables in the wal-index file. There
40474 ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
40475 ** wal-index.
40476 **
40477 ** Changing any of these constants will alter the wal-index format and
40478 ** create incompatibilities.
40479 */
40480 #define HASHTABLE_NPAGE      4096                 /* Must be power of 2 */
40481 #define HASHTABLE_HASH_1     383                  /* Should be prime */
40482 #define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */
40483
40484 /* 
40485 ** The block of page numbers associated with the first hash-table in a
40486 ** wal-index is smaller than usual. This is so that there is a complete
40487 ** hash-table on each aligned 32KB page of the wal-index.
40488 */
40489 #define HASHTABLE_NPAGE_ONE  (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
40490
40491 /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
40492 #define WALINDEX_PGSZ   (                                         \
40493     sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
40494 )
40495
40496 /*
40497 ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
40498 ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
40499 ** numbered from zero.
40500 **
40501 ** If this call is successful, *ppPage is set to point to the wal-index
40502 ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
40503 ** then an SQLite error code is returned and *ppPage is set to 0.
40504 */
40505 static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
40506   int rc = SQLITE_OK;
40507
40508   /* Enlarge the pWal->apWiData[] array if required */
40509   if( pWal->nWiData<=iPage ){
40510     int nByte = sizeof(u32*)*(iPage+1);
40511     volatile u32 **apNew;
40512     apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte);
40513     if( !apNew ){
40514       *ppPage = 0;
40515       return SQLITE_NOMEM;
40516     }
40517     memset((void*)&apNew[pWal->nWiData], 0,
40518            sizeof(u32*)*(iPage+1-pWal->nWiData));
40519     pWal->apWiData = apNew;
40520     pWal->nWiData = iPage+1;
40521   }
40522
40523   /* Request a pointer to the required page from the VFS */
40524   if( pWal->apWiData[iPage]==0 ){
40525     rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ, 
40526         pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
40527     );
40528   }
40529
40530   *ppPage = pWal->apWiData[iPage];
40531   assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
40532   return rc;
40533 }
40534
40535 /*
40536 ** Return a pointer to the WalCkptInfo structure in the wal-index.
40537 */
40538 static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
40539   assert( pWal->nWiData>0 && pWal->apWiData[0] );
40540   return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
40541 }
40542
40543 /*
40544 ** Return a pointer to the WalIndexHdr structure in the wal-index.
40545 */
40546 static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
40547   assert( pWal->nWiData>0 && pWal->apWiData[0] );
40548   return (volatile WalIndexHdr*)pWal->apWiData[0];
40549 }
40550
40551 /*
40552 ** The argument to this macro must be of type u32. On a little-endian
40553 ** architecture, it returns the u32 value that results from interpreting
40554 ** the 4 bytes as a big-endian value. On a big-endian architecture, it
40555 ** returns the value that would be produced by intepreting the 4 bytes
40556 ** of the input value as a little-endian integer.
40557 */
40558 #define BYTESWAP32(x) ( \
40559     (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8)  \
40560   + (((x)&0x00FF0000)>>8)  + (((x)&0xFF000000)>>24) \
40561 )
40562
40563 /*
40564 ** Generate or extend an 8 byte checksum based on the data in 
40565 ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
40566 ** initial values of 0 and 0 if aIn==NULL).
40567 **
40568 ** The checksum is written back into aOut[] before returning.
40569 **
40570 ** nByte must be a positive multiple of 8.
40571 */
40572 static void walChecksumBytes(
40573   int nativeCksum, /* True for native byte-order, false for non-native */
40574   u8 *a,           /* Content to be checksummed */
40575   int nByte,       /* Bytes of content in a[].  Must be a multiple of 8. */
40576   const u32 *aIn,  /* Initial checksum value input */
40577   u32 *aOut        /* OUT: Final checksum value output */
40578 ){
40579   u32 s1, s2;
40580   u32 *aData = (u32 *)a;
40581   u32 *aEnd = (u32 *)&a[nByte];
40582
40583   if( aIn ){
40584     s1 = aIn[0];
40585     s2 = aIn[1];
40586   }else{
40587     s1 = s2 = 0;
40588   }
40589
40590   assert( nByte>=8 );
40591   assert( (nByte&0x00000007)==0 );
40592
40593   if( nativeCksum ){
40594     do {
40595       s1 += *aData++ + s2;
40596       s2 += *aData++ + s1;
40597     }while( aData<aEnd );
40598   }else{
40599     do {
40600       s1 += BYTESWAP32(aData[0]) + s2;
40601       s2 += BYTESWAP32(aData[1]) + s1;
40602       aData += 2;
40603     }while( aData<aEnd );
40604   }
40605
40606   aOut[0] = s1;
40607   aOut[1] = s2;
40608 }
40609
40610 /*
40611 ** Write the header information in pWal->hdr into the wal-index.
40612 **
40613 ** The checksum on pWal->hdr is updated before it is written.
40614 */
40615 static void walIndexWriteHdr(Wal *pWal){
40616   volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
40617   const int nCksum = offsetof(WalIndexHdr, aCksum);
40618
40619   assert( pWal->writeLock );
40620   pWal->hdr.isInit = 1;
40621   pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
40622   walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
40623   memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
40624   sqlite3OsShmBarrier(pWal->pDbFd);
40625   memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
40626 }
40627
40628 /*
40629 ** This function encodes a single frame header and writes it to a buffer
40630 ** supplied by the caller. A frame-header is made up of a series of 
40631 ** 4-byte big-endian integers, as follows:
40632 **
40633 **     0: Page number.
40634 **     4: For commit records, the size of the database image in pages 
40635 **        after the commit. For all other records, zero.
40636 **     8: Salt-1 (copied from the wal-header)
40637 **    12: Salt-2 (copied from the wal-header)
40638 **    16: Checksum-1.
40639 **    20: Checksum-2.
40640 */
40641 static void walEncodeFrame(
40642   Wal *pWal,                      /* The write-ahead log */
40643   u32 iPage,                      /* Database page number for frame */
40644   u32 nTruncate,                  /* New db size (or 0 for non-commit frames) */
40645   u8 *aData,                      /* Pointer to page data */
40646   u8 *aFrame                      /* OUT: Write encoded frame here */
40647 ){
40648   int nativeCksum;                /* True for native byte-order checksums */
40649   u32 *aCksum = pWal->hdr.aFrameCksum;
40650   assert( WAL_FRAME_HDRSIZE==24 );
40651   sqlite3Put4byte(&aFrame[0], iPage);
40652   sqlite3Put4byte(&aFrame[4], nTruncate);
40653   memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
40654
40655   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
40656   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
40657   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
40658
40659   sqlite3Put4byte(&aFrame[16], aCksum[0]);
40660   sqlite3Put4byte(&aFrame[20], aCksum[1]);
40661 }
40662
40663 /*
40664 ** Check to see if the frame with header in aFrame[] and content
40665 ** in aData[] is valid.  If it is a valid frame, fill *piPage and
40666 ** *pnTruncate and return true.  Return if the frame is not valid.
40667 */
40668 static int walDecodeFrame(
40669   Wal *pWal,                      /* The write-ahead log */
40670   u32 *piPage,                    /* OUT: Database page number for frame */
40671   u32 *pnTruncate,                /* OUT: New db size (or 0 if not commit) */
40672   u8 *aData,                      /* Pointer to page data (for checksum) */
40673   u8 *aFrame                      /* Frame data */
40674 ){
40675   int nativeCksum;                /* True for native byte-order checksums */
40676   u32 *aCksum = pWal->hdr.aFrameCksum;
40677   u32 pgno;                       /* Page number of the frame */
40678   assert( WAL_FRAME_HDRSIZE==24 );
40679
40680   /* A frame is only valid if the salt values in the frame-header
40681   ** match the salt values in the wal-header. 
40682   */
40683   if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
40684     return 0;
40685   }
40686
40687   /* A frame is only valid if the page number is creater than zero.
40688   */
40689   pgno = sqlite3Get4byte(&aFrame[0]);
40690   if( pgno==0 ){
40691     return 0;
40692   }
40693
40694   /* A frame is only valid if a checksum of the WAL header,
40695   ** all prior frams, the first 16 bytes of this frame-header, 
40696   ** and the frame-data matches the checksum in the last 8 
40697   ** bytes of this frame-header.
40698   */
40699   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
40700   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
40701   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
40702   if( aCksum[0]!=sqlite3Get4byte(&aFrame[16]) 
40703    || aCksum[1]!=sqlite3Get4byte(&aFrame[20]) 
40704   ){
40705     /* Checksum failed. */
40706     return 0;
40707   }
40708
40709   /* If we reach this point, the frame is valid.  Return the page number
40710   ** and the new database size.
40711   */
40712   *piPage = pgno;
40713   *pnTruncate = sqlite3Get4byte(&aFrame[4]);
40714   return 1;
40715 }
40716
40717
40718 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
40719 /*
40720 ** Names of locks.  This routine is used to provide debugging output and is not
40721 ** a part of an ordinary build.
40722 */
40723 static const char *walLockName(int lockIdx){
40724   if( lockIdx==WAL_WRITE_LOCK ){
40725     return "WRITE-LOCK";
40726   }else if( lockIdx==WAL_CKPT_LOCK ){
40727     return "CKPT-LOCK";
40728   }else if( lockIdx==WAL_RECOVER_LOCK ){
40729     return "RECOVER-LOCK";
40730   }else{
40731     static char zName[15];
40732     sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
40733                      lockIdx-WAL_READ_LOCK(0));
40734     return zName;
40735   }
40736 }
40737 #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
40738     
40739
40740 /*
40741 ** Set or release locks on the WAL.  Locks are either shared or exclusive.
40742 ** A lock cannot be moved directly between shared and exclusive - it must go
40743 ** through the unlocked state first.
40744 **
40745 ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
40746 */
40747 static int walLockShared(Wal *pWal, int lockIdx){
40748   int rc;
40749   if( pWal->exclusiveMode ) return SQLITE_OK;
40750   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
40751                         SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
40752   WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
40753             walLockName(lockIdx), rc ? "failed" : "ok"));
40754   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
40755   return rc;
40756 }
40757 static void walUnlockShared(Wal *pWal, int lockIdx){
40758   if( pWal->exclusiveMode ) return;
40759   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
40760                          SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
40761   WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
40762 }
40763 static int walLockExclusive(Wal *pWal, int lockIdx, int n){
40764   int rc;
40765   if( pWal->exclusiveMode ) return SQLITE_OK;
40766   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
40767                         SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
40768   WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
40769             walLockName(lockIdx), n, rc ? "failed" : "ok"));
40770   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
40771   return rc;
40772 }
40773 static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
40774   if( pWal->exclusiveMode ) return;
40775   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
40776                          SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
40777   WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
40778              walLockName(lockIdx), n));
40779 }
40780
40781 /*
40782 ** Compute a hash on a page number.  The resulting hash value must land
40783 ** between 0 and (HASHTABLE_NSLOT-1).  The walHashNext() function advances
40784 ** the hash to the next value in the event of a collision.
40785 */
40786 static int walHash(u32 iPage){
40787   assert( iPage>0 );
40788   assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
40789   return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
40790 }
40791 static int walNextHash(int iPriorHash){
40792   return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
40793 }
40794
40795 /* 
40796 ** Return pointers to the hash table and page number array stored on
40797 ** page iHash of the wal-index. The wal-index is broken into 32KB pages
40798 ** numbered starting from 0.
40799 **
40800 ** Set output variable *paHash to point to the start of the hash table
40801 ** in the wal-index file. Set *piZero to one less than the frame 
40802 ** number of the first frame indexed by this hash table. If a
40803 ** slot in the hash table is set to N, it refers to frame number 
40804 ** (*piZero+N) in the log.
40805 **
40806 ** Finally, set *paPgno so that *paPgno[1] is the page number of the
40807 ** first frame indexed by the hash table, frame (*piZero+1).
40808 */
40809 static int walHashGet(
40810   Wal *pWal,                      /* WAL handle */
40811   int iHash,                      /* Find the iHash'th table */
40812   volatile ht_slot **paHash,      /* OUT: Pointer to hash index */
40813   volatile u32 **paPgno,          /* OUT: Pointer to page number array */
40814   u32 *piZero                     /* OUT: Frame associated with *paPgno[0] */
40815 ){
40816   int rc;                         /* Return code */
40817   volatile u32 *aPgno;
40818
40819   rc = walIndexPage(pWal, iHash, &aPgno);
40820   assert( rc==SQLITE_OK || iHash>0 );
40821
40822   if( rc==SQLITE_OK ){
40823     u32 iZero;
40824     volatile ht_slot *aHash;
40825
40826     aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
40827     if( iHash==0 ){
40828       aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
40829       iZero = 0;
40830     }else{
40831       iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
40832     }
40833   
40834     *paPgno = &aPgno[-1];
40835     *paHash = aHash;
40836     *piZero = iZero;
40837   }
40838   return rc;
40839 }
40840
40841 /*
40842 ** Return the number of the wal-index page that contains the hash-table
40843 ** and page-number array that contain entries corresponding to WAL frame
40844 ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages 
40845 ** are numbered starting from 0.
40846 */
40847 static int walFramePage(u32 iFrame){
40848   int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
40849   assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
40850        && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
40851        && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
40852        && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
40853        && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
40854   );
40855   return iHash;
40856 }
40857
40858 /*
40859 ** Return the page number associated with frame iFrame in this WAL.
40860 */
40861 static u32 walFramePgno(Wal *pWal, u32 iFrame){
40862   int iHash = walFramePage(iFrame);
40863   if( iHash==0 ){
40864     return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
40865   }
40866   return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
40867 }
40868
40869 /*
40870 ** Remove entries from the hash table that point to WAL slots greater
40871 ** than pWal->hdr.mxFrame.
40872 **
40873 ** This function is called whenever pWal->hdr.mxFrame is decreased due
40874 ** to a rollback or savepoint.
40875 **
40876 ** At most only the hash table containing pWal->hdr.mxFrame needs to be
40877 ** updated.  Any later hash tables will be automatically cleared when
40878 ** pWal->hdr.mxFrame advances to the point where those hash tables are
40879 ** actually needed.
40880 */
40881 static void walCleanupHash(Wal *pWal){
40882   volatile ht_slot *aHash = 0;    /* Pointer to hash table to clear */
40883   volatile u32 *aPgno = 0;        /* Page number array for hash table */
40884   u32 iZero = 0;                  /* frame == (aHash[x]+iZero) */
40885   int iLimit = 0;                 /* Zero values greater than this */
40886   int nByte;                      /* Number of bytes to zero in aPgno[] */
40887   int i;                          /* Used to iterate through aHash[] */
40888
40889   assert( pWal->writeLock );
40890   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
40891   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
40892   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
40893
40894   if( pWal->hdr.mxFrame==0 ) return;
40895
40896   /* Obtain pointers to the hash-table and page-number array containing 
40897   ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
40898   ** that the page said hash-table and array reside on is already mapped.
40899   */
40900   assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
40901   assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
40902   walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
40903
40904   /* Zero all hash-table entries that correspond to frame numbers greater
40905   ** than pWal->hdr.mxFrame.
40906   */
40907   iLimit = pWal->hdr.mxFrame - iZero;
40908   assert( iLimit>0 );
40909   for(i=0; i<HASHTABLE_NSLOT; i++){
40910     if( aHash[i]>iLimit ){
40911       aHash[i] = 0;
40912     }
40913   }
40914   
40915   /* Zero the entries in the aPgno array that correspond to frames with
40916   ** frame numbers greater than pWal->hdr.mxFrame. 
40917   */
40918   nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
40919   memset((void *)&aPgno[iLimit+1], 0, nByte);
40920
40921 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
40922   /* Verify that the every entry in the mapping region is still reachable
40923   ** via the hash table even after the cleanup.
40924   */
40925   if( iLimit ){
40926     int i;           /* Loop counter */
40927     int iKey;        /* Hash key */
40928     for(i=1; i<=iLimit; i++){
40929       for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
40930         if( aHash[iKey]==i ) break;
40931       }
40932       assert( aHash[iKey]==i );
40933     }
40934   }
40935 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
40936 }
40937
40938
40939 /*
40940 ** Set an entry in the wal-index that will map database page number
40941 ** pPage into WAL frame iFrame.
40942 */
40943 static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
40944   int rc;                         /* Return code */
40945   u32 iZero = 0;                  /* One less than frame number of aPgno[1] */
40946   volatile u32 *aPgno = 0;        /* Page number array */
40947   volatile ht_slot *aHash = 0;    /* Hash table */
40948
40949   rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
40950
40951   /* Assuming the wal-index file was successfully mapped, populate the
40952   ** page number array and hash table entry.
40953   */
40954   if( rc==SQLITE_OK ){
40955     int iKey;                     /* Hash table key */
40956     int idx;                      /* Value to write to hash-table slot */
40957     int nCollide;                 /* Number of hash collisions */
40958
40959     idx = iFrame - iZero;
40960     assert( idx <= HASHTABLE_NSLOT/2 + 1 );
40961     
40962     /* If this is the first entry to be added to this hash-table, zero the
40963     ** entire hash table and aPgno[] array before proceding. 
40964     */
40965     if( idx==1 ){
40966       int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
40967       memset((void*)&aPgno[1], 0, nByte);
40968     }
40969
40970     /* If the entry in aPgno[] is already set, then the previous writer
40971     ** must have exited unexpectedly in the middle of a transaction (after
40972     ** writing one or more dirty pages to the WAL to free up memory). 
40973     ** Remove the remnants of that writers uncommitted transaction from 
40974     ** the hash-table before writing any new entries.
40975     */
40976     if( aPgno[idx] ){
40977       walCleanupHash(pWal);
40978       assert( !aPgno[idx] );
40979     }
40980
40981     /* Write the aPgno[] array entry and the hash-table slot. */
40982     nCollide = idx;
40983     for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
40984       if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
40985     }
40986     aPgno[idx] = iPage;
40987     aHash[iKey] = (ht_slot)idx;
40988
40989 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
40990     /* Verify that the number of entries in the hash table exactly equals
40991     ** the number of entries in the mapping region.
40992     */
40993     {
40994       int i;           /* Loop counter */
40995       int nEntry = 0;  /* Number of entries in the hash table */
40996       for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
40997       assert( nEntry==idx );
40998     }
40999
41000     /* Verify that the every entry in the mapping region is reachable
41001     ** via the hash table.  This turns out to be a really, really expensive
41002     ** thing to check, so only do this occasionally - not on every
41003     ** iteration.
41004     */
41005     if( (idx&0x3ff)==0 ){
41006       int i;           /* Loop counter */
41007       for(i=1; i<=idx; i++){
41008         for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
41009           if( aHash[iKey]==i ) break;
41010         }
41011         assert( aHash[iKey]==i );
41012       }
41013     }
41014 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
41015   }
41016
41017
41018   return rc;
41019 }
41020
41021
41022 /*
41023 ** Recover the wal-index by reading the write-ahead log file. 
41024 **
41025 ** This routine first tries to establish an exclusive lock on the
41026 ** wal-index to prevent other threads/processes from doing anything
41027 ** with the WAL or wal-index while recovery is running.  The
41028 ** WAL_RECOVER_LOCK is also held so that other threads will know
41029 ** that this thread is running recovery.  If unable to establish
41030 ** the necessary locks, this routine returns SQLITE_BUSY.
41031 */
41032 static int walIndexRecover(Wal *pWal){
41033   int rc;                         /* Return Code */
41034   i64 nSize;                      /* Size of log file */
41035   u32 aFrameCksum[2] = {0, 0};
41036   int iLock;                      /* Lock offset to lock for checkpoint */
41037   int nLock;                      /* Number of locks to hold */
41038
41039   /* Obtain an exclusive lock on all byte in the locking range not already
41040   ** locked by the caller. The caller is guaranteed to have locked the
41041   ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
41042   ** If successful, the same bytes that are locked here are unlocked before
41043   ** this function returns.
41044   */
41045   assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
41046   assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
41047   assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
41048   assert( pWal->writeLock );
41049   iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
41050   nLock = SQLITE_SHM_NLOCK - iLock;
41051   rc = walLockExclusive(pWal, iLock, nLock);
41052   if( rc ){
41053     return rc;
41054   }
41055   WALTRACE(("WAL%p: recovery begin...\n", pWal));
41056
41057   memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
41058
41059   rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
41060   if( rc!=SQLITE_OK ){
41061     goto recovery_error;
41062   }
41063
41064   if( nSize>WAL_HDRSIZE ){
41065     u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
41066     u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
41067     int szFrame;                  /* Number of bytes in buffer aFrame[] */
41068     u8 *aData;                    /* Pointer to data part of aFrame buffer */
41069     int iFrame;                   /* Index of last frame read */
41070     i64 iOffset;                  /* Next offset to read from log file */
41071     int szPage;                   /* Page size according to the log */
41072     u32 magic;                    /* Magic value read from WAL header */
41073     u32 version;                  /* Magic value read from WAL header */
41074
41075     /* Read in the WAL header. */
41076     rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
41077     if( rc!=SQLITE_OK ){
41078       goto recovery_error;
41079     }
41080
41081     /* If the database page size is not a power of two, or is greater than
41082     ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid 
41083     ** data. Similarly, if the 'magic' value is invalid, ignore the whole
41084     ** WAL file.
41085     */
41086     magic = sqlite3Get4byte(&aBuf[0]);
41087     szPage = sqlite3Get4byte(&aBuf[8]);
41088     if( (magic&0xFFFFFFFE)!=WAL_MAGIC 
41089      || szPage&(szPage-1) 
41090      || szPage>SQLITE_MAX_PAGE_SIZE 
41091      || szPage<512 
41092     ){
41093       goto finished;
41094     }
41095     pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
41096     pWal->szPage = (u16)szPage;
41097     pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
41098     memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
41099
41100     /* Verify that the WAL header checksum is correct */
41101     walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN, 
41102         aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
41103     );
41104     if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
41105      || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
41106     ){
41107       goto finished;
41108     }
41109
41110     /* Verify that the version number on the WAL format is one that
41111     ** are able to understand */
41112     version = sqlite3Get4byte(&aBuf[4]);
41113     if( version!=WAL_MAX_VERSION ){
41114       rc = SQLITE_CANTOPEN_BKPT;
41115       goto finished;
41116     }
41117
41118     /* Malloc a buffer to read frames into. */
41119     szFrame = szPage + WAL_FRAME_HDRSIZE;
41120     aFrame = (u8 *)sqlite3_malloc(szFrame);
41121     if( !aFrame ){
41122       rc = SQLITE_NOMEM;
41123       goto recovery_error;
41124     }
41125     aData = &aFrame[WAL_FRAME_HDRSIZE];
41126
41127     /* Read all frames from the log file. */
41128     iFrame = 0;
41129     for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
41130       u32 pgno;                   /* Database page number for frame */
41131       u32 nTruncate;              /* dbsize field from frame header */
41132       int isValid;                /* True if this frame is valid */
41133
41134       /* Read and decode the next log frame. */
41135       rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
41136       if( rc!=SQLITE_OK ) break;
41137       isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
41138       if( !isValid ) break;
41139       rc = walIndexAppend(pWal, ++iFrame, pgno);
41140       if( rc!=SQLITE_OK ) break;
41141
41142       /* If nTruncate is non-zero, this is a commit record. */
41143       if( nTruncate ){
41144         pWal->hdr.mxFrame = iFrame;
41145         pWal->hdr.nPage = nTruncate;
41146         pWal->hdr.szPage = (u16)szPage;
41147         aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
41148         aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
41149       }
41150     }
41151
41152     sqlite3_free(aFrame);
41153   }
41154
41155 finished:
41156   if( rc==SQLITE_OK ){
41157     volatile WalCkptInfo *pInfo;
41158     int i;
41159     pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
41160     pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
41161     walIndexWriteHdr(pWal);
41162
41163     /* Reset the checkpoint-header. This is safe because this thread is 
41164     ** currently holding locks that exclude all other readers, writers and
41165     ** checkpointers.
41166     */
41167     pInfo = walCkptInfo(pWal);
41168     pInfo->nBackfill = 0;
41169     pInfo->aReadMark[0] = 0;
41170     for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
41171   }
41172
41173 recovery_error:
41174   WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
41175   walUnlockExclusive(pWal, iLock, nLock);
41176   return rc;
41177 }
41178
41179 /*
41180 ** Close an open wal-index.
41181 */
41182 static void walIndexClose(Wal *pWal, int isDelete){
41183   sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
41184 }
41185
41186 /* 
41187 ** Open a connection to the WAL file zWalName. The database file must 
41188 ** already be opened on connection pDbFd. The buffer that zWalName points
41189 ** to must remain valid for the lifetime of the returned Wal* handle.
41190 **
41191 ** A SHARED lock should be held on the database file when this function
41192 ** is called. The purpose of this SHARED lock is to prevent any other
41193 ** client from unlinking the WAL or wal-index file. If another process
41194 ** were to do this just after this client opened one of these files, the
41195 ** system would be badly broken.
41196 **
41197 ** If the log file is successfully opened, SQLITE_OK is returned and 
41198 ** *ppWal is set to point to a new WAL handle. If an error occurs,
41199 ** an SQLite error code is returned and *ppWal is left unmodified.
41200 */
41201 SQLITE_PRIVATE int sqlite3WalOpen(
41202   sqlite3_vfs *pVfs,              /* vfs module to open wal and wal-index */
41203   sqlite3_file *pDbFd,            /* The open database file */
41204   const char *zWalName,           /* Name of the WAL file */
41205   Wal **ppWal                     /* OUT: Allocated Wal handle */
41206 ){
41207   int rc;                         /* Return Code */
41208   Wal *pRet;                      /* Object to allocate and return */
41209   int flags;                      /* Flags passed to OsOpen() */
41210
41211   assert( zWalName && zWalName[0] );
41212   assert( pDbFd );
41213
41214   /* In the amalgamation, the os_unix.c and os_win.c source files come before
41215   ** this source file.  Verify that the #defines of the locking byte offsets
41216   ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
41217   */
41218 #ifdef WIN_SHM_BASE
41219   assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
41220 #endif
41221 #ifdef UNIX_SHM_BASE
41222   assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
41223 #endif
41224
41225
41226   /* Allocate an instance of struct Wal to return. */
41227   *ppWal = 0;
41228   pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
41229   if( !pRet ){
41230     return SQLITE_NOMEM;
41231   }
41232
41233   pRet->pVfs = pVfs;
41234   pRet->pWalFd = (sqlite3_file *)&pRet[1];
41235   pRet->pDbFd = pDbFd;
41236   pRet->readLock = -1;
41237   pRet->zWalName = zWalName;
41238
41239   /* Open file handle on the write-ahead log file. */
41240   flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
41241   rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
41242   if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
41243     pRet->readOnly = 1;
41244   }
41245
41246   if( rc!=SQLITE_OK ){
41247     walIndexClose(pRet, 0);
41248     sqlite3OsClose(pRet->pWalFd);
41249     sqlite3_free(pRet);
41250   }else{
41251     *ppWal = pRet;
41252     WALTRACE(("WAL%d: opened\n", pRet));
41253   }
41254   return rc;
41255 }
41256
41257 /*
41258 ** Find the smallest page number out of all pages held in the WAL that
41259 ** has not been returned by any prior invocation of this method on the
41260 ** same WalIterator object.   Write into *piFrame the frame index where
41261 ** that page was last written into the WAL.  Write into *piPage the page
41262 ** number.
41263 **
41264 ** Return 0 on success.  If there are no pages in the WAL with a page
41265 ** number larger than *piPage, then return 1.
41266 */
41267 static int walIteratorNext(
41268   WalIterator *p,               /* Iterator */
41269   u32 *piPage,                  /* OUT: The page number of the next page */
41270   u32 *piFrame                  /* OUT: Wal frame index of next page */
41271 ){
41272   u32 iMin;                     /* Result pgno must be greater than iMin */
41273   u32 iRet = 0xFFFFFFFF;        /* 0xffffffff is never a valid page number */
41274   int i;                        /* For looping through segments */
41275
41276   iMin = p->iPrior;
41277   assert( iMin<0xffffffff );
41278   for(i=p->nSegment-1; i>=0; i--){
41279     struct WalSegment *pSegment = &p->aSegment[i];
41280     while( pSegment->iNext<pSegment->nEntry ){
41281       u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
41282       if( iPg>iMin ){
41283         if( iPg<iRet ){
41284           iRet = iPg;
41285           *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
41286         }
41287         break;
41288       }
41289       pSegment->iNext++;
41290     }
41291   }
41292
41293   *piPage = p->iPrior = iRet;
41294   return (iRet==0xFFFFFFFF);
41295 }
41296
41297 /*
41298 ** This function merges two sorted lists into a single sorted list.
41299 */
41300 static void walMerge(
41301   u32 *aContent,                  /* Pages in wal */
41302   ht_slot *aLeft,                 /* IN: Left hand input list */
41303   int nLeft,                      /* IN: Elements in array *paLeft */
41304   ht_slot **paRight,              /* IN/OUT: Right hand input list */
41305   int *pnRight,                   /* IN/OUT: Elements in *paRight */
41306   ht_slot *aTmp                   /* Temporary buffer */
41307 ){
41308   int iLeft = 0;                  /* Current index in aLeft */
41309   int iRight = 0;                 /* Current index in aRight */
41310   int iOut = 0;                   /* Current index in output buffer */
41311   int nRight = *pnRight;
41312   ht_slot *aRight = *paRight;
41313
41314   assert( nLeft>0 && nRight>0 );
41315   while( iRight<nRight || iLeft<nLeft ){
41316     ht_slot logpage;
41317     Pgno dbpage;
41318
41319     if( (iLeft<nLeft) 
41320      && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
41321     ){
41322       logpage = aLeft[iLeft++];
41323     }else{
41324       logpage = aRight[iRight++];
41325     }
41326     dbpage = aContent[logpage];
41327
41328     aTmp[iOut++] = logpage;
41329     if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
41330
41331     assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
41332     assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
41333   }
41334
41335   *paRight = aLeft;
41336   *pnRight = iOut;
41337   memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
41338 }
41339
41340 /*
41341 ** Sort the elements in list aList, removing any duplicates.
41342 */
41343 static void walMergesort(
41344   u32 *aContent,                  /* Pages in wal */
41345   ht_slot *aBuffer,               /* Buffer of at least *pnList items to use */
41346   ht_slot *aList,                 /* IN/OUT: List to sort */
41347   int *pnList                     /* IN/OUT: Number of elements in aList[] */
41348 ){
41349   struct Sublist {
41350     int nList;                    /* Number of elements in aList */
41351     ht_slot *aList;               /* Pointer to sub-list content */
41352   };
41353
41354   const int nList = *pnList;      /* Size of input list */
41355   int nMerge = 0;                 /* Number of elements in list aMerge */
41356   ht_slot *aMerge = 0;            /* List to be merged */
41357   int iList;                      /* Index into input list */
41358   int iSub = 0;                   /* Index into aSub array */
41359   struct Sublist aSub[13];        /* Array of sub-lists */
41360
41361   memset(aSub, 0, sizeof(aSub));
41362   assert( nList<=HASHTABLE_NPAGE && nList>0 );
41363   assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
41364
41365   for(iList=0; iList<nList; iList++){
41366     nMerge = 1;
41367     aMerge = &aList[iList];
41368     for(iSub=0; iList & (1<<iSub); iSub++){
41369       struct Sublist *p = &aSub[iSub];
41370       assert( p->aList && p->nList<=(1<<iSub) );
41371       assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
41372       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
41373     }
41374     aSub[iSub].aList = aMerge;
41375     aSub[iSub].nList = nMerge;
41376   }
41377
41378   for(iSub++; iSub<ArraySize(aSub); iSub++){
41379     if( nList & (1<<iSub) ){
41380       struct Sublist *p = &aSub[iSub];
41381       assert( p->nList<=(1<<iSub) );
41382       assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
41383       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
41384     }
41385   }
41386   assert( aMerge==aList );
41387   *pnList = nMerge;
41388
41389 #ifdef SQLITE_DEBUG
41390   {
41391     int i;
41392     for(i=1; i<*pnList; i++){
41393       assert( aContent[aList[i]] > aContent[aList[i-1]] );
41394     }
41395   }
41396 #endif
41397 }
41398
41399 /* 
41400 ** Free an iterator allocated by walIteratorInit().
41401 */
41402 static void walIteratorFree(WalIterator *p){
41403   sqlite3ScratchFree(p);
41404 }
41405
41406 /*
41407 ** Construct a WalInterator object that can be used to loop over all 
41408 ** pages in the WAL in ascending order. The caller must hold the checkpoint
41409 **
41410 ** On success, make *pp point to the newly allocated WalInterator object
41411 ** return SQLITE_OK. Otherwise, return an error code. If this routine
41412 ** returns an error, the value of *pp is undefined.
41413 **
41414 ** The calling routine should invoke walIteratorFree() to destroy the
41415 ** WalIterator object when it has finished with it.
41416 */
41417 static int walIteratorInit(Wal *pWal, WalIterator **pp){
41418   WalIterator *p;                 /* Return value */
41419   int nSegment;                   /* Number of segments to merge */
41420   u32 iLast;                      /* Last frame in log */
41421   int nByte;                      /* Number of bytes to allocate */
41422   int i;                          /* Iterator variable */
41423   ht_slot *aTmp;                  /* Temp space used by merge-sort */
41424   int rc = SQLITE_OK;             /* Return Code */
41425
41426   /* This routine only runs while holding the checkpoint lock. And
41427   ** it only runs if there is actually content in the log (mxFrame>0).
41428   */
41429   assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
41430   iLast = pWal->hdr.mxFrame;
41431
41432   /* Allocate space for the WalIterator object. */
41433   nSegment = walFramePage(iLast) + 1;
41434   nByte = sizeof(WalIterator) 
41435         + (nSegment-1)*sizeof(struct WalSegment)
41436         + iLast*sizeof(ht_slot);
41437   p = (WalIterator *)sqlite3ScratchMalloc(nByte);
41438   if( !p ){
41439     return SQLITE_NOMEM;
41440   }
41441   memset(p, 0, nByte);
41442   p->nSegment = nSegment;
41443
41444   /* Allocate temporary space used by the merge-sort routine. This block
41445   ** of memory will be freed before this function returns.
41446   */
41447   aTmp = (ht_slot *)sqlite3ScratchMalloc(
41448       sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
41449   );
41450   if( !aTmp ){
41451     rc = SQLITE_NOMEM;
41452   }
41453
41454   for(i=0; rc==SQLITE_OK && i<nSegment; i++){
41455     volatile ht_slot *aHash;
41456     u32 iZero;
41457     volatile u32 *aPgno;
41458
41459     rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
41460     if( rc==SQLITE_OK ){
41461       int j;                      /* Counter variable */
41462       int nEntry;                 /* Number of entries in this segment */
41463       ht_slot *aIndex;            /* Sorted index for this segment */
41464
41465       aPgno++;
41466       if( (i+1)==nSegment ){
41467         nEntry = (int)(iLast - iZero);
41468       }else{
41469         nEntry = (int)((u32*)aHash - (u32*)aPgno);
41470       }
41471       aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
41472       iZero++;
41473   
41474       for(j=0; j<nEntry; j++){
41475         aIndex[j] = (ht_slot)j;
41476       }
41477       walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
41478       p->aSegment[i].iZero = iZero;
41479       p->aSegment[i].nEntry = nEntry;
41480       p->aSegment[i].aIndex = aIndex;
41481       p->aSegment[i].aPgno = (u32 *)aPgno;
41482     }
41483   }
41484   sqlite3ScratchFree(aTmp);
41485
41486   if( rc!=SQLITE_OK ){
41487     walIteratorFree(p);
41488   }
41489   *pp = p;
41490   return rc;
41491 }
41492
41493 /*
41494 ** Copy as much content as we can from the WAL back into the database file
41495 ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
41496 **
41497 ** The amount of information copies from WAL to database might be limited
41498 ** by active readers.  This routine will never overwrite a database page
41499 ** that a concurrent reader might be using.
41500 **
41501 ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
41502 ** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if 
41503 ** checkpoints are always run by a background thread or background 
41504 ** process, foreground threads will never block on a lengthy fsync call.
41505 **
41506 ** Fsync is called on the WAL before writing content out of the WAL and
41507 ** into the database.  This ensures that if the new content is persistent
41508 ** in the WAL and can be recovered following a power-loss or hard reset.
41509 **
41510 ** Fsync is also called on the database file if (and only if) the entire
41511 ** WAL content is copied into the database file.  This second fsync makes
41512 ** it safe to delete the WAL since the new content will persist in the
41513 ** database file.
41514 **
41515 ** This routine uses and updates the nBackfill field of the wal-index header.
41516 ** This is the only routine tha will increase the value of nBackfill.  
41517 ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
41518 ** its value.)
41519 **
41520 ** The caller must be holding sufficient locks to ensure that no other
41521 ** checkpoint is running (in any other thread or process) at the same
41522 ** time.
41523 */
41524 static int walCheckpoint(
41525   Wal *pWal,                      /* Wal connection */
41526   int sync_flags,                 /* Flags for OsSync() (or 0) */
41527   int nBuf,                       /* Size of zBuf in bytes */
41528   u8 *zBuf                        /* Temporary buffer to use */
41529 ){
41530   int rc;                         /* Return code */
41531   int szPage = pWal->hdr.szPage;  /* Database page-size */
41532   WalIterator *pIter = 0;         /* Wal iterator context */
41533   u32 iDbpage = 0;                /* Next database page to write */
41534   u32 iFrame = 0;                 /* Wal frame containing data for iDbpage */
41535   u32 mxSafeFrame;                /* Max frame that can be backfilled */
41536   int i;                          /* Loop counter */
41537   volatile WalCkptInfo *pInfo;    /* The checkpoint status information */
41538
41539   if( pWal->hdr.mxFrame==0 ) return SQLITE_OK;
41540
41541   /* Allocate the iterator */
41542   rc = walIteratorInit(pWal, &pIter);
41543   if( rc!=SQLITE_OK ){
41544     return rc;
41545   }
41546   assert( pIter );
41547
41548   /*** TODO:  Move this test out to the caller.  Make it an assert() here ***/
41549   if( pWal->hdr.szPage!=nBuf ){
41550     rc = SQLITE_CORRUPT_BKPT;
41551     goto walcheckpoint_out;
41552   }
41553
41554   /* Compute in mxSafeFrame the index of the last frame of the WAL that is
41555   ** safe to write into the database.  Frames beyond mxSafeFrame might
41556   ** overwrite database pages that are in use by active readers and thus
41557   ** cannot be backfilled from the WAL.
41558   */
41559   mxSafeFrame = pWal->hdr.mxFrame;
41560   pInfo = walCkptInfo(pWal);
41561   for(i=1; i<WAL_NREADER; i++){
41562     u32 y = pInfo->aReadMark[i];
41563     if( mxSafeFrame>=y ){
41564       assert( y<=pWal->hdr.mxFrame );
41565       rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
41566       if( rc==SQLITE_OK ){
41567         pInfo->aReadMark[i] = READMARK_NOT_USED;
41568         walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
41569       }else if( rc==SQLITE_BUSY ){
41570         mxSafeFrame = y;
41571       }else{
41572         goto walcheckpoint_out;
41573       }
41574     }
41575   }
41576
41577   if( pInfo->nBackfill<mxSafeFrame
41578    && (rc = walLockExclusive(pWal, WAL_READ_LOCK(0), 1))==SQLITE_OK
41579   ){
41580     u32 nBackfill = pInfo->nBackfill;
41581
41582     /* Sync the WAL to disk */
41583     if( sync_flags ){
41584       rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
41585     }
41586
41587     /* Iterate through the contents of the WAL, copying data to the db file. */
41588     while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
41589       i64 iOffset;
41590       assert( walFramePgno(pWal, iFrame)==iDbpage );
41591       if( iFrame<=nBackfill || iFrame>mxSafeFrame ) continue;
41592       iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
41593       /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
41594       rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
41595       if( rc!=SQLITE_OK ) break;
41596       iOffset = (iDbpage-1)*(i64)szPage;
41597       testcase( IS_BIG_INT(iOffset) );
41598       rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
41599       if( rc!=SQLITE_OK ) break;
41600     }
41601
41602     /* If work was actually accomplished... */
41603     if( rc==SQLITE_OK ){
41604       if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
41605         i64 szDb = pWal->hdr.nPage*(i64)szPage;
41606         testcase( IS_BIG_INT(szDb) );
41607         rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
41608         if( rc==SQLITE_OK && sync_flags ){
41609           rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
41610         }
41611       }
41612       if( rc==SQLITE_OK ){
41613         pInfo->nBackfill = mxSafeFrame;
41614       }
41615     }
41616
41617     /* Release the reader lock held while backfilling */
41618     walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
41619   }else if( rc==SQLITE_BUSY ){
41620     /* Reset the return code so as not to report a checkpoint failure
41621     ** just because active readers prevent any backfill.
41622     */
41623     rc = SQLITE_OK;
41624   }
41625
41626  walcheckpoint_out:
41627   walIteratorFree(pIter);
41628   return rc;
41629 }
41630
41631 /*
41632 ** Close a connection to a log file.
41633 */
41634 SQLITE_PRIVATE int sqlite3WalClose(
41635   Wal *pWal,                      /* Wal to close */
41636   int sync_flags,                 /* Flags to pass to OsSync() (or 0) */
41637   int nBuf,
41638   u8 *zBuf                        /* Buffer of at least nBuf bytes */
41639 ){
41640   int rc = SQLITE_OK;
41641   if( pWal ){
41642     int isDelete = 0;             /* True to unlink wal and wal-index files */
41643
41644     /* If an EXCLUSIVE lock can be obtained on the database file (using the
41645     ** ordinary, rollback-mode locking methods, this guarantees that the
41646     ** connection associated with this log file is the only connection to
41647     ** the database. In this case checkpoint the database and unlink both
41648     ** the wal and wal-index files.
41649     **
41650     ** The EXCLUSIVE lock is not released before returning.
41651     */
41652     rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
41653     if( rc==SQLITE_OK ){
41654       pWal->exclusiveMode = 1;
41655       rc = sqlite3WalCheckpoint(pWal, sync_flags, nBuf, zBuf);
41656       if( rc==SQLITE_OK ){
41657         isDelete = 1;
41658       }
41659     }
41660
41661     walIndexClose(pWal, isDelete);
41662     sqlite3OsClose(pWal->pWalFd);
41663     if( isDelete ){
41664       sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
41665     }
41666     WALTRACE(("WAL%p: closed\n", pWal));
41667     sqlite3_free((void *)pWal->apWiData);
41668     sqlite3_free(pWal);
41669   }
41670   return rc;
41671 }
41672
41673 /*
41674 ** Try to read the wal-index header.  Return 0 on success and 1 if
41675 ** there is a problem.
41676 **
41677 ** The wal-index is in shared memory.  Another thread or process might
41678 ** be writing the header at the same time this procedure is trying to
41679 ** read it, which might result in inconsistency.  A dirty read is detected
41680 ** by verifying that both copies of the header are the same and also by
41681 ** a checksum on the header.
41682 **
41683 ** If and only if the read is consistent and the header is different from
41684 ** pWal->hdr, then pWal->hdr is updated to the content of the new header
41685 ** and *pChanged is set to 1.
41686 **
41687 ** If the checksum cannot be verified return non-zero. If the header
41688 ** is read successfully and the checksum verified, return zero.
41689 */
41690 static int walIndexTryHdr(Wal *pWal, int *pChanged){
41691   u32 aCksum[2];                  /* Checksum on the header content */
41692   WalIndexHdr h1, h2;             /* Two copies of the header content */
41693   WalIndexHdr volatile *aHdr;     /* Header in shared memory */
41694
41695   /* The first page of the wal-index must be mapped at this point. */
41696   assert( pWal->nWiData>0 && pWal->apWiData[0] );
41697
41698   /* Read the header. This might happen currently with a write to the
41699   ** same area of shared memory on a different CPU in a SMP,
41700   ** meaning it is possible that an inconsistent snapshot is read
41701   ** from the file. If this happens, return non-zero.
41702   **
41703   ** There are two copies of the header at the beginning of the wal-index.
41704   ** When reading, read [0] first then [1].  Writes are in the reverse order.
41705   ** Memory barriers are used to prevent the compiler or the hardware from
41706   ** reordering the reads and writes.
41707   */
41708   aHdr = walIndexHdr(pWal);
41709   memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
41710   sqlite3OsShmBarrier(pWal->pDbFd);
41711   memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
41712
41713   if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
41714     return 1;   /* Dirty read */
41715   }  
41716   if( h1.isInit==0 ){
41717     return 1;   /* Malformed header - probably all zeros */
41718   }
41719   walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
41720   if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
41721     return 1;   /* Checksum does not match */
41722   }
41723
41724   if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
41725     *pChanged = 1;
41726     memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
41727     pWal->szPage = pWal->hdr.szPage;
41728   }
41729
41730   /* The header was successfully read. Return zero. */
41731   return 0;
41732 }
41733
41734 /*
41735 ** Read the wal-index header from the wal-index and into pWal->hdr.
41736 ** If the wal-header appears to be corrupt, try to reconstruct the
41737 ** wal-index from the WAL before returning.
41738 **
41739 ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
41740 ** changed by this opertion.  If pWal->hdr is unchanged, set *pChanged
41741 ** to 0.
41742 **
41743 ** If the wal-index header is successfully read, return SQLITE_OK. 
41744 ** Otherwise an SQLite error code.
41745 */
41746 static int walIndexReadHdr(Wal *pWal, int *pChanged){
41747   int rc;                         /* Return code */
41748   int badHdr;                     /* True if a header read failed */
41749   volatile u32 *page0;            /* Chunk of wal-index containing header */
41750
41751   /* Ensure that page 0 of the wal-index (the page that contains the 
41752   ** wal-index header) is mapped. Return early if an error occurs here.
41753   */
41754   assert( pChanged );
41755   rc = walIndexPage(pWal, 0, &page0);
41756   if( rc!=SQLITE_OK ){
41757     return rc;
41758   };
41759   assert( page0 || pWal->writeLock==0 );
41760
41761   /* If the first page of the wal-index has been mapped, try to read the
41762   ** wal-index header immediately, without holding any lock. This usually
41763   ** works, but may fail if the wal-index header is corrupt or currently 
41764   ** being modified by another thread or process.
41765   */
41766   badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
41767
41768   /* If the first attempt failed, it might have been due to a race
41769   ** with a writer.  So get a WRITE lock and try again.
41770   */
41771   assert( badHdr==0 || pWal->writeLock==0 );
41772   if( badHdr && SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
41773     pWal->writeLock = 1;
41774     if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
41775       badHdr = walIndexTryHdr(pWal, pChanged);
41776       if( badHdr ){
41777         /* If the wal-index header is still malformed even while holding
41778         ** a WRITE lock, it can only mean that the header is corrupted and
41779         ** needs to be reconstructed.  So run recovery to do exactly that.
41780         */
41781         rc = walIndexRecover(pWal);
41782         *pChanged = 1;
41783       }
41784     }
41785     pWal->writeLock = 0;
41786     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
41787   }
41788
41789   /* If the header is read successfully, check the version number to make
41790   ** sure the wal-index was not constructed with some future format that
41791   ** this version of SQLite cannot understand.
41792   */
41793   if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
41794     rc = SQLITE_CANTOPEN_BKPT;
41795   }
41796
41797   return rc;
41798 }
41799
41800 /*
41801 ** This is the value that walTryBeginRead returns when it needs to
41802 ** be retried.
41803 */
41804 #define WAL_RETRY  (-1)
41805
41806 /*
41807 ** Attempt to start a read transaction.  This might fail due to a race or
41808 ** other transient condition.  When that happens, it returns WAL_RETRY to
41809 ** indicate to the caller that it is safe to retry immediately.
41810 **
41811 ** On success return SQLITE_OK.  On a permanent failure (such an
41812 ** I/O error or an SQLITE_BUSY because another process is running
41813 ** recovery) return a positive error code.
41814 **
41815 ** The useWal parameter is true to force the use of the WAL and disable
41816 ** the case where the WAL is bypassed because it has been completely
41817 ** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr() 
41818 ** to make a copy of the wal-index header into pWal->hdr.  If the 
41819 ** wal-index header has changed, *pChanged is set to 1 (as an indication 
41820 ** to the caller that the local paget cache is obsolete and needs to be 
41821 ** flushed.)  When useWal==1, the wal-index header is assumed to already
41822 ** be loaded and the pChanged parameter is unused.
41823 **
41824 ** The caller must set the cnt parameter to the number of prior calls to
41825 ** this routine during the current read attempt that returned WAL_RETRY.
41826 ** This routine will start taking more aggressive measures to clear the
41827 ** race conditions after multiple WAL_RETRY returns, and after an excessive
41828 ** number of errors will ultimately return SQLITE_PROTOCOL.  The
41829 ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
41830 ** and is not honoring the locking protocol.  There is a vanishingly small
41831 ** chance that SQLITE_PROTOCOL could be returned because of a run of really
41832 ** bad luck when there is lots of contention for the wal-index, but that
41833 ** possibility is so small that it can be safely neglected, we believe.
41834 **
41835 ** On success, this routine obtains a read lock on 
41836 ** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is
41837 ** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)
41838 ** that means the Wal does not hold any read lock.  The reader must not
41839 ** access any database page that is modified by a WAL frame up to and
41840 ** including frame number aReadMark[pWal->readLock].  The reader will
41841 ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
41842 ** Or if pWal->readLock==0, then the reader will ignore the WAL
41843 ** completely and get all content directly from the database file.
41844 ** If the useWal parameter is 1 then the WAL will never be ignored and
41845 ** this routine will always set pWal->readLock>0 on success.
41846 ** When the read transaction is completed, the caller must release the
41847 ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
41848 **
41849 ** This routine uses the nBackfill and aReadMark[] fields of the header
41850 ** to select a particular WAL_READ_LOCK() that strives to let the
41851 ** checkpoint process do as much work as possible.  This routine might
41852 ** update values of the aReadMark[] array in the header, but if it does
41853 ** so it takes care to hold an exclusive lock on the corresponding
41854 ** WAL_READ_LOCK() while changing values.
41855 */
41856 static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
41857   volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */
41858   u32 mxReadMark;                 /* Largest aReadMark[] value */
41859   int mxI;                        /* Index of largest aReadMark[] value */
41860   int i;                          /* Loop counter */
41861   int rc = SQLITE_OK;             /* Return code  */
41862
41863   assert( pWal->readLock<0 );     /* Not currently locked */
41864
41865   /* Take steps to avoid spinning forever if there is a protocol error. */
41866   if( cnt>5 ){
41867     if( cnt>100 ) return SQLITE_PROTOCOL;
41868     sqlite3OsSleep(pWal->pVfs, 1);
41869   }
41870
41871   if( !useWal ){
41872     rc = walIndexReadHdr(pWal, pChanged);
41873     if( rc==SQLITE_BUSY ){
41874       /* If there is not a recovery running in another thread or process
41875       ** then convert BUSY errors to WAL_RETRY.  If recovery is known to
41876       ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here
41877       ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
41878       ** would be technically correct.  But the race is benign since with
41879       ** WAL_RETRY this routine will be called again and will probably be
41880       ** right on the second iteration.
41881       */
41882       if( pWal->apWiData[0]==0 ){
41883         /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
41884         ** We assume this is a transient condition, so return WAL_RETRY. The
41885         ** xShmMap() implementation used by the default unix and win32 VFS 
41886         ** modules may return SQLITE_BUSY due to a race condition in the 
41887         ** code that determines whether or not the shared-memory region 
41888         ** must be zeroed before the requested page is returned.
41889         */
41890         rc = WAL_RETRY;
41891       }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
41892         walUnlockShared(pWal, WAL_RECOVER_LOCK);
41893         rc = WAL_RETRY;
41894       }else if( rc==SQLITE_BUSY ){
41895         rc = SQLITE_BUSY_RECOVERY;
41896       }
41897     }
41898     if( rc!=SQLITE_OK ){
41899       return rc;
41900     }
41901   }
41902
41903   pInfo = walCkptInfo(pWal);
41904   if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
41905     /* The WAL has been completely backfilled (or it is empty).
41906     ** and can be safely ignored.
41907     */
41908     rc = walLockShared(pWal, WAL_READ_LOCK(0));
41909     sqlite3OsShmBarrier(pWal->pDbFd);
41910     if( rc==SQLITE_OK ){
41911       if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
41912         /* It is not safe to allow the reader to continue here if frames
41913         ** may have been appended to the log before READ_LOCK(0) was obtained.
41914         ** When holding READ_LOCK(0), the reader ignores the entire log file,
41915         ** which implies that the database file contains a trustworthy
41916         ** snapshoT. Since holding READ_LOCK(0) prevents a checkpoint from
41917         ** happening, this is usually correct.
41918         **
41919         ** However, if frames have been appended to the log (or if the log 
41920         ** is wrapped and written for that matter) before the READ_LOCK(0)
41921         ** is obtained, that is not necessarily true. A checkpointer may
41922         ** have started to backfill the appended frames but crashed before
41923         ** it finished. Leaving a corrupt image in the database file.
41924         */
41925         walUnlockShared(pWal, WAL_READ_LOCK(0));
41926         return WAL_RETRY;
41927       }
41928       pWal->readLock = 0;
41929       return SQLITE_OK;
41930     }else if( rc!=SQLITE_BUSY ){
41931       return rc;
41932     }
41933   }
41934
41935   /* If we get this far, it means that the reader will want to use
41936   ** the WAL to get at content from recent commits.  The job now is
41937   ** to select one of the aReadMark[] entries that is closest to
41938   ** but not exceeding pWal->hdr.mxFrame and lock that entry.
41939   */
41940   mxReadMark = 0;
41941   mxI = 0;
41942   for(i=1; i<WAL_NREADER; i++){
41943     u32 thisMark = pInfo->aReadMark[i];
41944     if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
41945       assert( thisMark!=READMARK_NOT_USED );
41946       mxReadMark = thisMark;
41947       mxI = i;
41948     }
41949   }
41950   if( mxI==0 ){
41951     /* If we get here, it means that all of the aReadMark[] entries between
41952     ** 1 and WAL_NREADER-1 are zero.  Try to initialize aReadMark[1] to
41953     ** be mxFrame, then retry.
41954     */
41955     rc = walLockExclusive(pWal, WAL_READ_LOCK(1), 1);
41956     if( rc==SQLITE_OK ){
41957       pInfo->aReadMark[1] = pWal->hdr.mxFrame;
41958       walUnlockExclusive(pWal, WAL_READ_LOCK(1), 1);
41959       rc = WAL_RETRY;
41960     }else if( rc==SQLITE_BUSY ){
41961       rc = WAL_RETRY;
41962     }
41963     return rc;
41964   }else{
41965     if( mxReadMark < pWal->hdr.mxFrame ){
41966       for(i=1; i<WAL_NREADER; i++){
41967         rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
41968         if( rc==SQLITE_OK ){
41969           mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
41970           mxI = i;
41971           walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
41972           break;
41973         }else if( rc!=SQLITE_BUSY ){
41974           return rc;
41975         }
41976       }
41977     }
41978
41979     rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
41980     if( rc ){
41981       return rc==SQLITE_BUSY ? WAL_RETRY : rc;
41982     }
41983     /* Now that the read-lock has been obtained, check that neither the
41984     ** value in the aReadMark[] array or the contents of the wal-index
41985     ** header have changed.
41986     **
41987     ** It is necessary to check that the wal-index header did not change
41988     ** between the time it was read and when the shared-lock was obtained
41989     ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
41990     ** that the log file may have been wrapped by a writer, or that frames
41991     ** that occur later in the log than pWal->hdr.mxFrame may have been
41992     ** copied into the database by a checkpointer. If either of these things
41993     ** happened, then reading the database with the current value of
41994     ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
41995     ** instead.
41996     **
41997     ** This does not guarantee that the copy of the wal-index header is up to
41998     ** date before proceeding. That would not be possible without somehow
41999     ** blocking writers. It only guarantees that a dangerous checkpoint or 
42000     ** log-wrap (either of which would require an exclusive lock on
42001     ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
42002     */
42003     sqlite3OsShmBarrier(pWal->pDbFd);
42004     if( pInfo->aReadMark[mxI]!=mxReadMark
42005      || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
42006     ){
42007       walUnlockShared(pWal, WAL_READ_LOCK(mxI));
42008       return WAL_RETRY;
42009     }else{
42010       assert( mxReadMark<=pWal->hdr.mxFrame );
42011       pWal->readLock = (i16)mxI;
42012     }
42013   }
42014   return rc;
42015 }
42016
42017 /*
42018 ** Begin a read transaction on the database.
42019 **
42020 ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
42021 ** it takes a snapshot of the state of the WAL and wal-index for the current
42022 ** instant in time.  The current thread will continue to use this snapshot.
42023 ** Other threads might append new content to the WAL and wal-index but
42024 ** that extra content is ignored by the current thread.
42025 **
42026 ** If the database contents have changes since the previous read
42027 ** transaction, then *pChanged is set to 1 before returning.  The
42028 ** Pager layer will use this to know that is cache is stale and
42029 ** needs to be flushed.
42030 */
42031 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
42032   int rc;                         /* Return code */
42033   int cnt = 0;                    /* Number of TryBeginRead attempts */
42034
42035   do{
42036     rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
42037   }while( rc==WAL_RETRY );
42038   return rc;
42039 }
42040
42041 /*
42042 ** Finish with a read transaction.  All this does is release the
42043 ** read-lock.
42044 */
42045 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
42046   if( pWal->readLock>=0 ){
42047     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
42048     pWal->readLock = -1;
42049   }
42050 }
42051
42052 /*
42053 ** Read a page from the WAL, if it is present in the WAL and if the 
42054 ** current read transaction is configured to use the WAL.  
42055 **
42056 ** The *pInWal is set to 1 if the requested page is in the WAL and
42057 ** has been loaded.  Or *pInWal is set to 0 if the page was not in 
42058 ** the WAL and needs to be read out of the database.
42059 */
42060 SQLITE_PRIVATE int sqlite3WalRead(
42061   Wal *pWal,                      /* WAL handle */
42062   Pgno pgno,                      /* Database page number to read data for */
42063   int *pInWal,                    /* OUT: True if data is read from WAL */
42064   int nOut,                       /* Size of buffer pOut in bytes */
42065   u8 *pOut                        /* Buffer to write page data to */
42066 ){
42067   u32 iRead = 0;                  /* If !=0, WAL frame to return data from */
42068   u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */
42069   int iHash;                      /* Used to loop through N hash tables */
42070
42071   /* This routine is only be called from within a read transaction. */
42072   assert( pWal->readLock>=0 || pWal->lockError );
42073
42074   /* If the "last page" field of the wal-index header snapshot is 0, then
42075   ** no data will be read from the wal under any circumstances. Return early
42076   ** in this case as an optimization.  Likewise, if pWal->readLock==0, 
42077   ** then the WAL is ignored by the reader so return early, as if the 
42078   ** WAL were empty.
42079   */
42080   if( iLast==0 || pWal->readLock==0 ){
42081     *pInWal = 0;
42082     return SQLITE_OK;
42083   }
42084
42085   /* Search the hash table or tables for an entry matching page number
42086   ** pgno. Each iteration of the following for() loop searches one
42087   ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
42088   **
42089   ** This code might run concurrently to the code in walIndexAppend()
42090   ** that adds entries to the wal-index (and possibly to this hash 
42091   ** table). This means the value just read from the hash 
42092   ** slot (aHash[iKey]) may have been added before or after the 
42093   ** current read transaction was opened. Values added after the
42094   ** read transaction was opened may have been written incorrectly -
42095   ** i.e. these slots may contain garbage data. However, we assume
42096   ** that any slots written before the current read transaction was
42097   ** opened remain unmodified.
42098   **
42099   ** For the reasons above, the if(...) condition featured in the inner
42100   ** loop of the following block is more stringent that would be required 
42101   ** if we had exclusive access to the hash-table:
42102   **
42103   **   (aPgno[iFrame]==pgno): 
42104   **     This condition filters out normal hash-table collisions.
42105   **
42106   **   (iFrame<=iLast): 
42107   **     This condition filters out entries that were added to the hash
42108   **     table after the current read-transaction had started.
42109   */
42110   for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
42111     volatile ht_slot *aHash;      /* Pointer to hash table */
42112     volatile u32 *aPgno;          /* Pointer to array of page numbers */
42113     u32 iZero;                    /* Frame number corresponding to aPgno[0] */
42114     int iKey;                     /* Hash slot index */
42115     int nCollide;                 /* Number of hash collisions remaining */
42116     int rc;                       /* Error code */
42117
42118     rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
42119     if( rc!=SQLITE_OK ){
42120       return rc;
42121     }
42122     nCollide = HASHTABLE_NSLOT;
42123     for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
42124       u32 iFrame = aHash[iKey] + iZero;
42125       if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
42126         assert( iFrame>iRead );
42127         iRead = iFrame;
42128       }
42129       if( (nCollide--)==0 ){
42130         return SQLITE_CORRUPT_BKPT;
42131       }
42132     }
42133   }
42134
42135 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
42136   /* If expensive assert() statements are available, do a linear search
42137   ** of the wal-index file content. Make sure the results agree with the
42138   ** result obtained using the hash indexes above.  */
42139   {
42140     u32 iRead2 = 0;
42141     u32 iTest;
42142     for(iTest=iLast; iTest>0; iTest--){
42143       if( walFramePgno(pWal, iTest)==pgno ){
42144         iRead2 = iTest;
42145         break;
42146       }
42147     }
42148     assert( iRead==iRead2 );
42149   }
42150 #endif
42151
42152   /* If iRead is non-zero, then it is the log frame number that contains the
42153   ** required page. Read and return data from the log file.
42154   */
42155   if( iRead ){
42156     i64 iOffset = walFrameOffset(iRead, pWal->hdr.szPage) + WAL_FRAME_HDRSIZE;
42157     *pInWal = 1;
42158     /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
42159     return sqlite3OsRead(pWal->pWalFd, pOut, nOut, iOffset);
42160   }
42161
42162   *pInWal = 0;
42163   return SQLITE_OK;
42164 }
42165
42166
42167 /* 
42168 ** Set *pPgno to the size of the database file (or zero, if unknown).
42169 */
42170 SQLITE_PRIVATE void sqlite3WalDbsize(Wal *pWal, Pgno *pPgno){
42171   assert( pWal->readLock>=0 || pWal->lockError );
42172   *pPgno = pWal->hdr.nPage;
42173 }
42174
42175
42176 /* 
42177 ** This function starts a write transaction on the WAL.
42178 **
42179 ** A read transaction must have already been started by a prior call
42180 ** to sqlite3WalBeginReadTransaction().
42181 **
42182 ** If another thread or process has written into the database since
42183 ** the read transaction was started, then it is not possible for this
42184 ** thread to write as doing so would cause a fork.  So this routine
42185 ** returns SQLITE_BUSY in that case and no write transaction is started.
42186 **
42187 ** There can only be a single writer active at a time.
42188 */
42189 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
42190   int rc;
42191
42192   /* Cannot start a write transaction without first holding a read
42193   ** transaction. */
42194   assert( pWal->readLock>=0 );
42195
42196   if( pWal->readOnly ){
42197     return SQLITE_READONLY;
42198   }
42199
42200   /* Only one writer allowed at a time.  Get the write lock.  Return
42201   ** SQLITE_BUSY if unable.
42202   */
42203   rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
42204   if( rc ){
42205     return rc;
42206   }
42207   pWal->writeLock = 1;
42208
42209   /* If another connection has written to the database file since the
42210   ** time the read transaction on this connection was started, then
42211   ** the write is disallowed.
42212   */
42213   if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
42214     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
42215     pWal->writeLock = 0;
42216     rc = SQLITE_BUSY;
42217   }
42218
42219   return rc;
42220 }
42221
42222 /*
42223 ** End a write transaction.  The commit has already been done.  This
42224 ** routine merely releases the lock.
42225 */
42226 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
42227   if( pWal->writeLock ){
42228     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
42229     pWal->writeLock = 0;
42230   }
42231   return SQLITE_OK;
42232 }
42233
42234 /*
42235 ** If any data has been written (but not committed) to the log file, this
42236 ** function moves the write-pointer back to the start of the transaction.
42237 **
42238 ** Additionally, the callback function is invoked for each frame written
42239 ** to the WAL since the start of the transaction. If the callback returns
42240 ** other than SQLITE_OK, it is not invoked again and the error code is
42241 ** returned to the caller.
42242 **
42243 ** Otherwise, if the callback function does not return an error, this
42244 ** function returns SQLITE_OK.
42245 */
42246 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
42247   int rc = SQLITE_OK;
42248   if( pWal->writeLock ){
42249     Pgno iMax = pWal->hdr.mxFrame;
42250     Pgno iFrame;
42251   
42252     /* Restore the clients cache of the wal-index header to the state it
42253     ** was in before the client began writing to the database. 
42254     */
42255     memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
42256
42257     for(iFrame=pWal->hdr.mxFrame+1; 
42258         ALWAYS(rc==SQLITE_OK) && iFrame<=iMax; 
42259         iFrame++
42260     ){
42261       /* This call cannot fail. Unless the page for which the page number
42262       ** is passed as the second argument is (a) in the cache and 
42263       ** (b) has an outstanding reference, then xUndo is either a no-op
42264       ** (if (a) is false) or simply expels the page from the cache (if (b)
42265       ** is false).
42266       **
42267       ** If the upper layer is doing a rollback, it is guaranteed that there
42268       ** are no outstanding references to any page other than page 1. And
42269       ** page 1 is never written to the log until the transaction is
42270       ** committed. As a result, the call to xUndo may not fail.
42271       */
42272       assert( walFramePgno(pWal, iFrame)!=1 );
42273       rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
42274     }
42275     walCleanupHash(pWal);
42276   }
42277   assert( rc==SQLITE_OK );
42278   return rc;
42279 }
42280
42281 /* 
42282 ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32 
42283 ** values. This function populates the array with values required to 
42284 ** "rollback" the write position of the WAL handle back to the current 
42285 ** point in the event of a savepoint rollback (via WalSavepointUndo()).
42286 */
42287 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
42288   assert( pWal->writeLock );
42289   aWalData[0] = pWal->hdr.mxFrame;
42290   aWalData[1] = pWal->hdr.aFrameCksum[0];
42291   aWalData[2] = pWal->hdr.aFrameCksum[1];
42292   aWalData[3] = pWal->nCkpt;
42293 }
42294
42295 /* 
42296 ** Move the write position of the WAL back to the point identified by
42297 ** the values in the aWalData[] array. aWalData must point to an array
42298 ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
42299 ** by a call to WalSavepoint().
42300 */
42301 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
42302   int rc = SQLITE_OK;
42303
42304   assert( pWal->writeLock );
42305   assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
42306
42307   if( aWalData[3]!=pWal->nCkpt ){
42308     /* This savepoint was opened immediately after the write-transaction
42309     ** was started. Right after that, the writer decided to wrap around
42310     ** to the start of the log. Update the savepoint values to match.
42311     */
42312     aWalData[0] = 0;
42313     aWalData[3] = pWal->nCkpt;
42314   }
42315
42316   if( aWalData[0]<pWal->hdr.mxFrame ){
42317     pWal->hdr.mxFrame = aWalData[0];
42318     pWal->hdr.aFrameCksum[0] = aWalData[1];
42319     pWal->hdr.aFrameCksum[1] = aWalData[2];
42320     walCleanupHash(pWal);
42321   }
42322
42323   return rc;
42324 }
42325
42326 /*
42327 ** This function is called just before writing a set of frames to the log
42328 ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
42329 ** to the current log file, it is possible to overwrite the start of the
42330 ** existing log file with the new frames (i.e. "reset" the log). If so,
42331 ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
42332 ** unchanged.
42333 **
42334 ** SQLITE_OK is returned if no error is encountered (regardless of whether
42335 ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
42336 ** if some error 
42337 */
42338 static int walRestartLog(Wal *pWal){
42339   int rc = SQLITE_OK;
42340   int cnt;
42341
42342   if( pWal->readLock==0 ){
42343     volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
42344     assert( pInfo->nBackfill==pWal->hdr.mxFrame );
42345     if( pInfo->nBackfill>0 ){
42346       rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
42347       if( rc==SQLITE_OK ){
42348         /* If all readers are using WAL_READ_LOCK(0) (in other words if no
42349         ** readers are currently using the WAL), then the transactions
42350         ** frames will overwrite the start of the existing log. Update the
42351         ** wal-index header to reflect this.
42352         **
42353         ** In theory it would be Ok to update the cache of the header only
42354         ** at this point. But updating the actual wal-index header is also
42355         ** safe and means there is no special case for sqlite3WalUndo()
42356         ** to handle if this transaction is rolled back.
42357         */
42358         int i;                    /* Loop counter */
42359         u32 *aSalt = pWal->hdr.aSalt;       /* Big-endian salt values */
42360         pWal->nCkpt++;
42361         pWal->hdr.mxFrame = 0;
42362         sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
42363         sqlite3_randomness(4, &aSalt[1]);
42364         walIndexWriteHdr(pWal);
42365         pInfo->nBackfill = 0;
42366         for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
42367         assert( pInfo->aReadMark[0]==0 );
42368         walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
42369       }
42370     }
42371     walUnlockShared(pWal, WAL_READ_LOCK(0));
42372     pWal->readLock = -1;
42373     cnt = 0;
42374     do{
42375       int notUsed;
42376       rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
42377     }while( rc==WAL_RETRY );
42378   }
42379   return rc;
42380 }
42381
42382 /* 
42383 ** Write a set of frames to the log. The caller must hold the write-lock
42384 ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
42385 */
42386 SQLITE_PRIVATE int sqlite3WalFrames(
42387   Wal *pWal,                      /* Wal handle to write to */
42388   int szPage,                     /* Database page-size in bytes */
42389   PgHdr *pList,                   /* List of dirty pages to write */
42390   Pgno nTruncate,                 /* Database size after this commit */
42391   int isCommit,                   /* True if this is a commit */
42392   int sync_flags                  /* Flags to pass to OsSync() (or 0) */
42393 ){
42394   int rc;                         /* Used to catch return codes */
42395   u32 iFrame;                     /* Next frame address */
42396   u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */
42397   PgHdr *p;                       /* Iterator to run through pList with. */
42398   PgHdr *pLast = 0;               /* Last frame in list */
42399   int nLast = 0;                  /* Number of extra copies of last page */
42400
42401   assert( pList );
42402   assert( pWal->writeLock );
42403
42404 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
42405   { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
42406     WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
42407               pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
42408   }
42409 #endif
42410
42411   /* See if it is possible to write these frames into the start of the
42412   ** log file, instead of appending to it at pWal->hdr.mxFrame.
42413   */
42414   if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
42415     return rc;
42416   }
42417
42418   /* If this is the first frame written into the log, write the WAL
42419   ** header to the start of the WAL file. See comments at the top of
42420   ** this source file for a description of the WAL header format.
42421   */
42422   iFrame = pWal->hdr.mxFrame;
42423   if( iFrame==0 ){
42424     u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */
42425     u32 aCksum[2];                /* Checksum for wal-header */
42426
42427     sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
42428     sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
42429     sqlite3Put4byte(&aWalHdr[8], szPage);
42430     sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
42431     sqlite3_randomness(8, pWal->hdr.aSalt);
42432     memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
42433     walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
42434     sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
42435     sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
42436     
42437     pWal->szPage = (u16)szPage;
42438     pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
42439     pWal->hdr.aFrameCksum[0] = aCksum[0];
42440     pWal->hdr.aFrameCksum[1] = aCksum[1];
42441
42442     rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
42443     WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
42444     if( rc!=SQLITE_OK ){
42445       return rc;
42446     }
42447   }
42448   assert( pWal->szPage==szPage );
42449
42450   /* Write the log file. */
42451   for(p=pList; p; p=p->pDirty){
42452     u32 nDbsize;                  /* Db-size field for frame header */
42453     i64 iOffset;                  /* Write offset in log file */
42454     void *pData;
42455    
42456     iOffset = walFrameOffset(++iFrame, szPage);
42457     /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
42458     
42459     /* Populate and write the frame header */
42460     nDbsize = (isCommit && p->pDirty==0) ? nTruncate : 0;
42461 #if defined(SQLITE_HAS_CODEC)
42462     if( (pData = sqlite3PagerCodec(p))==0 ) return SQLITE_NOMEM;
42463 #else
42464     pData = p->pData;
42465 #endif
42466     walEncodeFrame(pWal, p->pgno, nDbsize, pData, aFrame);
42467     rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOffset);
42468     if( rc!=SQLITE_OK ){
42469       return rc;
42470     }
42471
42472     /* Write the page data */
42473     rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOffset+sizeof(aFrame));
42474     if( rc!=SQLITE_OK ){
42475       return rc;
42476     }
42477     pLast = p;
42478   }
42479
42480   /* Sync the log file if the 'isSync' flag was specified. */
42481   if( sync_flags ){
42482     i64 iSegment = sqlite3OsSectorSize(pWal->pWalFd);
42483     i64 iOffset = walFrameOffset(iFrame+1, szPage);
42484
42485     assert( isCommit );
42486     assert( iSegment>0 );
42487
42488     iSegment = (((iOffset+iSegment-1)/iSegment) * iSegment);
42489     while( iOffset<iSegment ){
42490       void *pData;
42491 #if defined(SQLITE_HAS_CODEC)
42492       if( (pData = sqlite3PagerCodec(pLast))==0 ) return SQLITE_NOMEM;
42493 #else
42494       pData = pLast->pData;
42495 #endif
42496       walEncodeFrame(pWal, pLast->pgno, nTruncate, pData, aFrame);
42497       /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
42498       rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOffset);
42499       if( rc!=SQLITE_OK ){
42500         return rc;
42501       }
42502       iOffset += WAL_FRAME_HDRSIZE;
42503       rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOffset); 
42504       if( rc!=SQLITE_OK ){
42505         return rc;
42506       }
42507       nLast++;
42508       iOffset += szPage;
42509     }
42510
42511     rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
42512   }
42513
42514   /* Append data to the wal-index. It is not necessary to lock the 
42515   ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
42516   ** guarantees that there are no other writers, and no data that may
42517   ** be in use by existing readers is being overwritten.
42518   */
42519   iFrame = pWal->hdr.mxFrame;
42520   for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
42521     iFrame++;
42522     rc = walIndexAppend(pWal, iFrame, p->pgno);
42523   }
42524   while( nLast>0 && rc==SQLITE_OK ){
42525     iFrame++;
42526     nLast--;
42527     rc = walIndexAppend(pWal, iFrame, pLast->pgno);
42528   }
42529
42530   if( rc==SQLITE_OK ){
42531     /* Update the private copy of the header. */
42532     pWal->hdr.szPage = (u16)szPage;
42533     pWal->hdr.mxFrame = iFrame;
42534     if( isCommit ){
42535       pWal->hdr.iChange++;
42536       pWal->hdr.nPage = nTruncate;
42537     }
42538     /* If this is a commit, update the wal-index header too. */
42539     if( isCommit ){
42540       walIndexWriteHdr(pWal);
42541       pWal->iCallback = iFrame;
42542     }
42543   }
42544
42545   WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
42546   return rc;
42547 }
42548
42549 /* 
42550 ** This routine is called to implement sqlite3_wal_checkpoint() and
42551 ** related interfaces.
42552 **
42553 ** Obtain a CHECKPOINT lock and then backfill as much information as
42554 ** we can from WAL into the database.
42555 */
42556 SQLITE_PRIVATE int sqlite3WalCheckpoint(
42557   Wal *pWal,                      /* Wal connection */
42558   int sync_flags,                 /* Flags to sync db file with (or 0) */
42559   int nBuf,                       /* Size of temporary buffer */
42560   u8 *zBuf                        /* Temporary buffer to use */
42561 ){
42562   int rc;                         /* Return code */
42563   int isChanged = 0;              /* True if a new wal-index header is loaded */
42564
42565   assert( pWal->ckptLock==0 );
42566
42567   WALTRACE(("WAL%p: checkpoint begins\n", pWal));
42568   rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
42569   if( rc ){
42570     /* Usually this is SQLITE_BUSY meaning that another thread or process
42571     ** is already running a checkpoint, or maybe a recovery.  But it might
42572     ** also be SQLITE_IOERR. */
42573     return rc;
42574   }
42575   pWal->ckptLock = 1;
42576
42577   /* Copy data from the log to the database file. */
42578   rc = walIndexReadHdr(pWal, &isChanged);
42579   if( rc==SQLITE_OK ){
42580     rc = walCheckpoint(pWal, sync_flags, nBuf, zBuf);
42581   }
42582   if( isChanged ){
42583     /* If a new wal-index header was loaded before the checkpoint was 
42584     ** performed, then the pager-cache associated with pWal is now
42585     ** out of date. So zero the cached wal-index header to ensure that
42586     ** next time the pager opens a snapshot on this database it knows that
42587     ** the cache needs to be reset.
42588     */
42589     memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
42590   }
42591
42592   /* Release the locks. */
42593   walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
42594   pWal->ckptLock = 0;
42595   WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
42596   return rc;
42597 }
42598
42599 /* Return the value to pass to a sqlite3_wal_hook callback, the
42600 ** number of frames in the WAL at the point of the last commit since
42601 ** sqlite3WalCallback() was called.  If no commits have occurred since
42602 ** the last call, then return 0.
42603 */
42604 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
42605   u32 ret = 0;
42606   if( pWal ){
42607     ret = pWal->iCallback;
42608     pWal->iCallback = 0;
42609   }
42610   return (int)ret;
42611 }
42612
42613 /*
42614 ** This function is called to change the WAL subsystem into or out
42615 ** of locking_mode=EXCLUSIVE.
42616 **
42617 ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
42618 ** into locking_mode=NORMAL.  This means that we must acquire a lock
42619 ** on the pWal->readLock byte.  If the WAL is already in locking_mode=NORMAL
42620 ** or if the acquisition of the lock fails, then return 0.  If the
42621 ** transition out of exclusive-mode is successful, return 1.  This
42622 ** operation must occur while the pager is still holding the exclusive
42623 ** lock on the main database file.
42624 **
42625 ** If op is one, then change from locking_mode=NORMAL into 
42626 ** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must
42627 ** be released.  Return 1 if the transition is made and 0 if the
42628 ** WAL is already in exclusive-locking mode - meaning that this
42629 ** routine is a no-op.  The pager must already hold the exclusive lock
42630 ** on the main database file before invoking this operation.
42631 **
42632 ** If op is negative, then do a dry-run of the op==1 case but do
42633 ** not actually change anything.  The pager uses this to see if it
42634 ** should acquire the database exclusive lock prior to invoking
42635 ** the op==1 case.
42636 */
42637 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
42638   int rc;
42639   assert( pWal->writeLock==0 );
42640
42641   /* pWal->readLock is usually set, but might be -1 if there was a 
42642   ** prior error while attempting to acquire are read-lock. This cannot 
42643   ** happen if the connection is actually in exclusive mode (as no xShmLock
42644   ** locks are taken in this case). Nor should the pager attempt to
42645   ** upgrade to exclusive-mode following such an error.
42646   */
42647   assert( pWal->readLock>=0 || pWal->lockError );
42648   assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
42649
42650   if( op==0 ){
42651     if( pWal->exclusiveMode ){
42652       pWal->exclusiveMode = 0;
42653       if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
42654         pWal->exclusiveMode = 1;
42655       }
42656       rc = pWal->exclusiveMode==0;
42657     }else{
42658       /* Already in locking_mode=NORMAL */
42659       rc = 0;
42660     }
42661   }else if( op>0 ){
42662     assert( pWal->exclusiveMode==0 );
42663     assert( pWal->readLock>=0 );
42664     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
42665     pWal->exclusiveMode = 1;
42666     rc = 1;
42667   }else{
42668     rc = pWal->exclusiveMode==0;
42669   }
42670   return rc;
42671 }
42672
42673 #endif /* #ifndef SQLITE_OMIT_WAL */
42674
42675 /************** End of wal.c *************************************************/
42676 /************** Begin file btmutex.c *****************************************/
42677 /*
42678 ** 2007 August 27
42679 **
42680 ** The author disclaims copyright to this source code.  In place of
42681 ** a legal notice, here is a blessing:
42682 **
42683 **    May you do good and not evil.
42684 **    May you find forgiveness for yourself and forgive others.
42685 **    May you share freely, never taking more than you give.
42686 **
42687 *************************************************************************
42688 **
42689 ** This file contains code used to implement mutexes on Btree objects.
42690 ** This code really belongs in btree.c.  But btree.c is getting too
42691 ** big and we want to break it down some.  This packaged seemed like
42692 ** a good breakout.
42693 */
42694 /************** Include btreeInt.h in the middle of btmutex.c ****************/
42695 /************** Begin file btreeInt.h ****************************************/
42696 /*
42697 ** 2004 April 6
42698 **
42699 ** The author disclaims copyright to this source code.  In place of
42700 ** a legal notice, here is a blessing:
42701 **
42702 **    May you do good and not evil.
42703 **    May you find forgiveness for yourself and forgive others.
42704 **    May you share freely, never taking more than you give.
42705 **
42706 *************************************************************************
42707 ** This file implements a external (disk-based) database using BTrees.
42708 ** For a detailed discussion of BTrees, refer to
42709 **
42710 **     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
42711 **     "Sorting And Searching", pages 473-480. Addison-Wesley
42712 **     Publishing Company, Reading, Massachusetts.
42713 **
42714 ** The basic idea is that each page of the file contains N database
42715 ** entries and N+1 pointers to subpages.
42716 **
42717 **   ----------------------------------------------------------------
42718 **   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
42719 **   ----------------------------------------------------------------
42720 **
42721 ** All of the keys on the page that Ptr(0) points to have values less
42722 ** than Key(0).  All of the keys on page Ptr(1) and its subpages have
42723 ** values greater than Key(0) and less than Key(1).  All of the keys
42724 ** on Ptr(N) and its subpages have values greater than Key(N-1).  And
42725 ** so forth.
42726 **
42727 ** Finding a particular key requires reading O(log(M)) pages from the 
42728 ** disk where M is the number of entries in the tree.
42729 **
42730 ** In this implementation, a single file can hold one or more separate 
42731 ** BTrees.  Each BTree is identified by the index of its root page.  The
42732 ** key and data for any entry are combined to form the "payload".  A
42733 ** fixed amount of payload can be carried directly on the database
42734 ** page.  If the payload is larger than the preset amount then surplus
42735 ** bytes are stored on overflow pages.  The payload for an entry
42736 ** and the preceding pointer are combined to form a "Cell".  Each 
42737 ** page has a small header which contains the Ptr(N) pointer and other
42738 ** information such as the size of key and data.
42739 **
42740 ** FORMAT DETAILS
42741 **
42742 ** The file is divided into pages.  The first page is called page 1,
42743 ** the second is page 2, and so forth.  A page number of zero indicates
42744 ** "no such page".  The page size can be any power of 2 between 512 and 32768.
42745 ** Each page can be either a btree page, a freelist page, an overflow
42746 ** page, or a pointer-map page.
42747 **
42748 ** The first page is always a btree page.  The first 100 bytes of the first
42749 ** page contain a special header (the "file header") that describes the file.
42750 ** The format of the file header is as follows:
42751 **
42752 **   OFFSET   SIZE    DESCRIPTION
42753 **      0      16     Header string: "SQLite format 3\000"
42754 **     16       2     Page size in bytes.  
42755 **     18       1     File format write version
42756 **     19       1     File format read version
42757 **     20       1     Bytes of unused space at the end of each page
42758 **     21       1     Max embedded payload fraction
42759 **     22       1     Min embedded payload fraction
42760 **     23       1     Min leaf payload fraction
42761 **     24       4     File change counter
42762 **     28       4     Reserved for future use
42763 **     32       4     First freelist page
42764 **     36       4     Number of freelist pages in the file
42765 **     40      60     15 4-byte meta values passed to higher layers
42766 **
42767 **     40       4     Schema cookie
42768 **     44       4     File format of schema layer
42769 **     48       4     Size of page cache
42770 **     52       4     Largest root-page (auto/incr_vacuum)
42771 **     56       4     1=UTF-8 2=UTF16le 3=UTF16be
42772 **     60       4     User version
42773 **     64       4     Incremental vacuum mode
42774 **     68       4     unused
42775 **     72       4     unused
42776 **     76       4     unused
42777 **
42778 ** All of the integer values are big-endian (most significant byte first).
42779 **
42780 ** The file change counter is incremented when the database is changed
42781 ** This counter allows other processes to know when the file has changed
42782 ** and thus when they need to flush their cache.
42783 **
42784 ** The max embedded payload fraction is the amount of the total usable
42785 ** space in a page that can be consumed by a single cell for standard
42786 ** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
42787 ** is to limit the maximum cell size so that at least 4 cells will fit
42788 ** on one page.  Thus the default max embedded payload fraction is 64.
42789 **
42790 ** If the payload for a cell is larger than the max payload, then extra
42791 ** payload is spilled to overflow pages.  Once an overflow page is allocated,
42792 ** as many bytes as possible are moved into the overflow pages without letting
42793 ** the cell size drop below the min embedded payload fraction.
42794 **
42795 ** The min leaf payload fraction is like the min embedded payload fraction
42796 ** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
42797 ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
42798 ** not specified in the header.
42799 **
42800 ** Each btree pages is divided into three sections:  The header, the
42801 ** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
42802 ** file header that occurs before the page header.
42803 **
42804 **      |----------------|
42805 **      | file header    |   100 bytes.  Page 1 only.
42806 **      |----------------|
42807 **      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
42808 **      |----------------|
42809 **      | cell pointer   |   |  2 bytes per cell.  Sorted order.
42810 **      | array          |   |  Grows downward
42811 **      |                |   v
42812 **      |----------------|
42813 **      | unallocated    |
42814 **      | space          |
42815 **      |----------------|   ^  Grows upwards
42816 **      | cell content   |   |  Arbitrary order interspersed with freeblocks.
42817 **      | area           |   |  and free space fragments.
42818 **      |----------------|
42819 **
42820 ** The page headers looks like this:
42821 **
42822 **   OFFSET   SIZE     DESCRIPTION
42823 **      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
42824 **      1       2      byte offset to the first freeblock
42825 **      3       2      number of cells on this page
42826 **      5       2      first byte of the cell content area
42827 **      7       1      number of fragmented free bytes
42828 **      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
42829 **
42830 ** The flags define the format of this btree page.  The leaf flag means that
42831 ** this page has no children.  The zerodata flag means that this page carries
42832 ** only keys and no data.  The intkey flag means that the key is a integer
42833 ** which is stored in the key size entry of the cell header rather than in
42834 ** the payload area.
42835 **
42836 ** The cell pointer array begins on the first byte after the page header.
42837 ** The cell pointer array contains zero or more 2-byte numbers which are
42838 ** offsets from the beginning of the page to the cell content in the cell
42839 ** content area.  The cell pointers occur in sorted order.  The system strives
42840 ** to keep free space after the last cell pointer so that new cells can
42841 ** be easily added without having to defragment the page.
42842 **
42843 ** Cell content is stored at the very end of the page and grows toward the
42844 ** beginning of the page.
42845 **
42846 ** Unused space within the cell content area is collected into a linked list of
42847 ** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
42848 ** to the first freeblock is given in the header.  Freeblocks occur in
42849 ** increasing order.  Because a freeblock must be at least 4 bytes in size,
42850 ** any group of 3 or fewer unused bytes in the cell content area cannot
42851 ** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
42852 ** a fragment.  The total number of bytes in all fragments is recorded.
42853 ** in the page header at offset 7.
42854 **
42855 **    SIZE    DESCRIPTION
42856 **      2     Byte offset of the next freeblock
42857 **      2     Bytes in this freeblock
42858 **
42859 ** Cells are of variable length.  Cells are stored in the cell content area at
42860 ** the end of the page.  Pointers to the cells are in the cell pointer array
42861 ** that immediately follows the page header.  Cells is not necessarily
42862 ** contiguous or in order, but cell pointers are contiguous and in order.
42863 **
42864 ** Cell content makes use of variable length integers.  A variable
42865 ** length integer is 1 to 9 bytes where the lower 7 bits of each 
42866 ** byte are used.  The integer consists of all bytes that have bit 8 set and
42867 ** the first byte with bit 8 clear.  The most significant byte of the integer
42868 ** appears first.  A variable-length integer may not be more than 9 bytes long.
42869 ** As a special case, all 8 bytes of the 9th byte are used as data.  This
42870 ** allows a 64-bit integer to be encoded in 9 bytes.
42871 **
42872 **    0x00                      becomes  0x00000000
42873 **    0x7f                      becomes  0x0000007f
42874 **    0x81 0x00                 becomes  0x00000080
42875 **    0x82 0x00                 becomes  0x00000100
42876 **    0x80 0x7f                 becomes  0x0000007f
42877 **    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
42878 **    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
42879 **
42880 ** Variable length integers are used for rowids and to hold the number of
42881 ** bytes of key and data in a btree cell.
42882 **
42883 ** The content of a cell looks like this:
42884 **
42885 **    SIZE    DESCRIPTION
42886 **      4     Page number of the left child. Omitted if leaf flag is set.
42887 **     var    Number of bytes of data. Omitted if the zerodata flag is set.
42888 **     var    Number of bytes of key. Or the key itself if intkey flag is set.
42889 **      *     Payload
42890 **      4     First page of the overflow chain.  Omitted if no overflow
42891 **
42892 ** Overflow pages form a linked list.  Each page except the last is completely
42893 ** filled with data (pagesize - 4 bytes).  The last page can have as little
42894 ** as 1 byte of data.
42895 **
42896 **    SIZE    DESCRIPTION
42897 **      4     Page number of next overflow page
42898 **      *     Data
42899 **
42900 ** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
42901 ** file header points to the first in a linked list of trunk page.  Each trunk
42902 ** page points to multiple leaf pages.  The content of a leaf page is
42903 ** unspecified.  A trunk page looks like this:
42904 **
42905 **    SIZE    DESCRIPTION
42906 **      4     Page number of next trunk page
42907 **      4     Number of leaf pointers on this page
42908 **      *     zero or more pages numbers of leaves
42909 */
42910
42911
42912 /* The following value is the maximum cell size assuming a maximum page
42913 ** size give above.
42914 */
42915 #define MX_CELL_SIZE(pBt)  (pBt->pageSize-8)
42916
42917 /* The maximum number of cells on a single page of the database.  This
42918 ** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
42919 ** plus 2 bytes for the index to the cell in the page header).  Such
42920 ** small cells will be rare, but they are possible.
42921 */
42922 #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
42923
42924 /* Forward declarations */
42925 typedef struct MemPage MemPage;
42926 typedef struct BtLock BtLock;
42927
42928 /*
42929 ** This is a magic string that appears at the beginning of every
42930 ** SQLite database in order to identify the file as a real database.
42931 **
42932 ** You can change this value at compile-time by specifying a
42933 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
42934 ** header must be exactly 16 bytes including the zero-terminator so
42935 ** the string itself should be 15 characters long.  If you change
42936 ** the header, then your custom library will not be able to read 
42937 ** databases generated by the standard tools and the standard tools
42938 ** will not be able to read databases created by your custom library.
42939 */
42940 #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
42941 #  define SQLITE_FILE_HEADER "SQLite format 3"
42942 #endif
42943
42944 /*
42945 ** Page type flags.  An ORed combination of these flags appear as the
42946 ** first byte of on-disk image of every BTree page.
42947 */
42948 #define PTF_INTKEY    0x01
42949 #define PTF_ZERODATA  0x02
42950 #define PTF_LEAFDATA  0x04
42951 #define PTF_LEAF      0x08
42952
42953 /*
42954 ** As each page of the file is loaded into memory, an instance of the following
42955 ** structure is appended and initialized to zero.  This structure stores
42956 ** information about the page that is decoded from the raw file page.
42957 **
42958 ** The pParent field points back to the parent page.  This allows us to
42959 ** walk up the BTree from any leaf to the root.  Care must be taken to
42960 ** unref() the parent page pointer when this page is no longer referenced.
42961 ** The pageDestructor() routine handles that chore.
42962 **
42963 ** Access to all fields of this structure is controlled by the mutex
42964 ** stored in MemPage.pBt->mutex.
42965 */
42966 struct MemPage {
42967   u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
42968   u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
42969   u8 intKey;           /* True if intkey flag is set */
42970   u8 leaf;             /* True if leaf flag is set */
42971   u8 hasData;          /* True if this page stores data */
42972   u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
42973   u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
42974   u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
42975   u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
42976   u16 cellOffset;      /* Index in aData of first cell pointer */
42977   u16 nFree;           /* Number of free bytes on the page */
42978   u16 nCell;           /* Number of cells on this page, local and ovfl */
42979   u16 maskPage;        /* Mask for page offset */
42980   struct _OvflCell {   /* Cells that will not fit on aData[] */
42981     u8 *pCell;          /* Pointers to the body of the overflow cell */
42982     u16 idx;            /* Insert this cell before idx-th non-overflow cell */
42983   } aOvfl[5];
42984   BtShared *pBt;       /* Pointer to BtShared that this page is part of */
42985   u8 *aData;           /* Pointer to disk image of the page data */
42986   DbPage *pDbPage;     /* Pager page handle */
42987   Pgno pgno;           /* Page number for this page */
42988 };
42989
42990 /*
42991 ** The in-memory image of a disk page has the auxiliary information appended
42992 ** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
42993 ** that extra information.
42994 */
42995 #define EXTRA_SIZE sizeof(MemPage)
42996
42997 /*
42998 ** A linked list of the following structures is stored at BtShared.pLock.
42999 ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor 
43000 ** is opened on the table with root page BtShared.iTable. Locks are removed
43001 ** from this list when a transaction is committed or rolled back, or when
43002 ** a btree handle is closed.
43003 */
43004 struct BtLock {
43005   Btree *pBtree;        /* Btree handle holding this lock */
43006   Pgno iTable;          /* Root page of table */
43007   u8 eLock;             /* READ_LOCK or WRITE_LOCK */
43008   BtLock *pNext;        /* Next in BtShared.pLock list */
43009 };
43010
43011 /* Candidate values for BtLock.eLock */
43012 #define READ_LOCK     1
43013 #define WRITE_LOCK    2
43014
43015 /* A Btree handle
43016 **
43017 ** A database connection contains a pointer to an instance of
43018 ** this object for every database file that it has open.  This structure
43019 ** is opaque to the database connection.  The database connection cannot
43020 ** see the internals of this structure and only deals with pointers to
43021 ** this structure.
43022 **
43023 ** For some database files, the same underlying database cache might be 
43024 ** shared between multiple connections.  In that case, each connection
43025 ** has it own instance of this object.  But each instance of this object
43026 ** points to the same BtShared object.  The database cache and the
43027 ** schema associated with the database file are all contained within
43028 ** the BtShared object.
43029 **
43030 ** All fields in this structure are accessed under sqlite3.mutex.
43031 ** The pBt pointer itself may not be changed while there exists cursors 
43032 ** in the referenced BtShared that point back to this Btree since those
43033 ** cursors have to do go through this Btree to find their BtShared and
43034 ** they often do so without holding sqlite3.mutex.
43035 */
43036 struct Btree {
43037   sqlite3 *db;       /* The database connection holding this btree */
43038   BtShared *pBt;     /* Sharable content of this btree */
43039   u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
43040   u8 sharable;       /* True if we can share pBt with another db */
43041   u8 locked;         /* True if db currently has pBt locked */
43042   int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
43043   int nBackup;       /* Number of backup operations reading this btree */
43044   Btree *pNext;      /* List of other sharable Btrees from the same db */
43045   Btree *pPrev;      /* Back pointer of the same list */
43046 #ifndef SQLITE_OMIT_SHARED_CACHE
43047   BtLock lock;       /* Object used to lock page 1 */
43048 #endif
43049 };
43050
43051 /*
43052 ** Btree.inTrans may take one of the following values.
43053 **
43054 ** If the shared-data extension is enabled, there may be multiple users
43055 ** of the Btree structure. At most one of these may open a write transaction,
43056 ** but any number may have active read transactions.
43057 */
43058 #define TRANS_NONE  0
43059 #define TRANS_READ  1
43060 #define TRANS_WRITE 2
43061
43062 /*
43063 ** An instance of this object represents a single database file.
43064 ** 
43065 ** A single database file can be in use as the same time by two
43066 ** or more database connections.  When two or more connections are
43067 ** sharing the same database file, each connection has it own
43068 ** private Btree object for the file and each of those Btrees points
43069 ** to this one BtShared object.  BtShared.nRef is the number of
43070 ** connections currently sharing this database file.
43071 **
43072 ** Fields in this structure are accessed under the BtShared.mutex
43073 ** mutex, except for nRef and pNext which are accessed under the
43074 ** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
43075 ** may not be modified once it is initially set as long as nRef>0.
43076 ** The pSchema field may be set once under BtShared.mutex and
43077 ** thereafter is unchanged as long as nRef>0.
43078 **
43079 ** isPending:
43080 **
43081 **   If a BtShared client fails to obtain a write-lock on a database
43082 **   table (because there exists one or more read-locks on the table),
43083 **   the shared-cache enters 'pending-lock' state and isPending is
43084 **   set to true.
43085 **
43086 **   The shared-cache leaves the 'pending lock' state when either of
43087 **   the following occur:
43088 **
43089 **     1) The current writer (BtShared.pWriter) concludes its transaction, OR
43090 **     2) The number of locks held by other connections drops to zero.
43091 **
43092 **   while in the 'pending-lock' state, no connection may start a new
43093 **   transaction.
43094 **
43095 **   This feature is included to help prevent writer-starvation.
43096 */
43097 struct BtShared {
43098   Pager *pPager;        /* The page cache */
43099   sqlite3 *db;          /* Database connection currently using this Btree */
43100   BtCursor *pCursor;    /* A list of all open cursors */
43101   MemPage *pPage1;      /* First page of the database */
43102   u8 readOnly;          /* True if the underlying file is readonly */
43103   u8 pageSizeFixed;     /* True if the page size can no longer be changed */
43104   u8 secureDelete;      /* True if secure_delete is enabled */
43105   u8 initiallyEmpty;    /* Database is empty at start of transaction */
43106 #ifndef SQLITE_OMIT_AUTOVACUUM
43107   u8 autoVacuum;        /* True if auto-vacuum is enabled */
43108   u8 incrVacuum;        /* True if incr-vacuum is enabled */
43109 #endif
43110   u16 pageSize;         /* Total number of bytes on a page */
43111   u16 usableSize;       /* Number of usable bytes on each page */
43112   u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
43113   u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
43114   u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
43115   u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
43116   u8 inTransaction;     /* Transaction state */
43117   u8 doNotUseWAL;       /* If true, do not open write-ahead-log file */
43118   int nTransaction;     /* Number of open transactions (read + write) */
43119   u32 nPage;            /* Number of pages in the database */
43120   void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
43121   void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
43122   sqlite3_mutex *mutex; /* Non-recursive mutex required to access this struct */
43123   Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
43124 #ifndef SQLITE_OMIT_SHARED_CACHE
43125   int nRef;             /* Number of references to this structure */
43126   BtShared *pNext;      /* Next on a list of sharable BtShared structs */
43127   BtLock *pLock;        /* List of locks held on this shared-btree struct */
43128   Btree *pWriter;       /* Btree with currently open write transaction */
43129   u8 isExclusive;       /* True if pWriter has an EXCLUSIVE lock on the db */
43130   u8 isPending;         /* If waiting for read-locks to clear */
43131 #endif
43132   u8 *pTmpSpace;        /* BtShared.pageSize bytes of space for tmp use */
43133 };
43134
43135 /*
43136 ** An instance of the following structure is used to hold information
43137 ** about a cell.  The parseCellPtr() function fills in this structure
43138 ** based on information extract from the raw disk page.
43139 */
43140 typedef struct CellInfo CellInfo;
43141 struct CellInfo {
43142   u8 *pCell;     /* Pointer to the start of cell content */
43143   i64 nKey;      /* The key for INTKEY tables, or number of bytes in key */
43144   u32 nData;     /* Number of bytes of data */
43145   u32 nPayload;  /* Total amount of payload */
43146   u16 nHeader;   /* Size of the cell content header in bytes */
43147   u16 nLocal;    /* Amount of payload held locally */
43148   u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
43149   u16 nSize;     /* Size of the cell content on the main b-tree page */
43150 };
43151
43152 /*
43153 ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
43154 ** this will be declared corrupt. This value is calculated based on a
43155 ** maximum database size of 2^31 pages a minimum fanout of 2 for a
43156 ** root-node and 3 for all other internal nodes.
43157 **
43158 ** If a tree that appears to be taller than this is encountered, it is
43159 ** assumed that the database is corrupt.
43160 */
43161 #define BTCURSOR_MAX_DEPTH 20
43162
43163 /*
43164 ** A cursor is a pointer to a particular entry within a particular
43165 ** b-tree within a database file.
43166 **
43167 ** The entry is identified by its MemPage and the index in
43168 ** MemPage.aCell[] of the entry.
43169 **
43170 ** A single database file can shared by two more database connections,
43171 ** but cursors cannot be shared.  Each cursor is associated with a
43172 ** particular database connection identified BtCursor.pBtree.db.
43173 **
43174 ** Fields in this structure are accessed under the BtShared.mutex
43175 ** found at self->pBt->mutex. 
43176 */
43177 struct BtCursor {
43178   Btree *pBtree;            /* The Btree to which this cursor belongs */
43179   BtShared *pBt;            /* The BtShared this cursor points to */
43180   BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
43181   struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
43182   Pgno pgnoRoot;            /* The root page of this tree */
43183   sqlite3_int64 cachedRowid; /* Next rowid cache.  0 means not valid */
43184   CellInfo info;            /* A parse of the cell we are pointing at */
43185   u8 wrFlag;                /* True if writable */
43186   u8 atLast;                /* Cursor pointing to the last entry */
43187   u8 validNKey;             /* True if info.nKey is valid */
43188   u8 eState;                /* One of the CURSOR_XXX constants (see below) */
43189   void *pKey;      /* Saved key that was cursor's last known position */
43190   i64 nKey;        /* Size of pKey, or last integer key */
43191   int skipNext;    /* Prev() is noop if negative. Next() is noop if positive */
43192 #ifndef SQLITE_OMIT_INCRBLOB
43193   u8 isIncrblobHandle;      /* True if this cursor is an incr. io handle */
43194   Pgno *aOverflow;          /* Cache of overflow page locations */
43195 #endif
43196   i16 iPage;                            /* Index of current page in apPage */
43197   MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
43198   u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
43199 };
43200
43201 /*
43202 ** Potential values for BtCursor.eState.
43203 **
43204 ** CURSOR_VALID:
43205 **   Cursor points to a valid entry. getPayload() etc. may be called.
43206 **
43207 ** CURSOR_INVALID:
43208 **   Cursor does not point to a valid entry. This can happen (for example) 
43209 **   because the table is empty or because BtreeCursorFirst() has not been
43210 **   called.
43211 **
43212 ** CURSOR_REQUIRESEEK:
43213 **   The table that this cursor was opened on still exists, but has been 
43214 **   modified since the cursor was last used. The cursor position is saved
43215 **   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in 
43216 **   this state, restoreCursorPosition() can be called to attempt to
43217 **   seek the cursor to the saved position.
43218 **
43219 ** CURSOR_FAULT:
43220 **   A unrecoverable error (an I/O error or a malloc failure) has occurred
43221 **   on a different connection that shares the BtShared cache with this
43222 **   cursor.  The error has left the cache in an inconsistent state.
43223 **   Do nothing else with this cursor.  Any attempt to use the cursor
43224 **   should return the error code stored in BtCursor.skip
43225 */
43226 #define CURSOR_INVALID           0
43227 #define CURSOR_VALID             1
43228 #define CURSOR_REQUIRESEEK       2
43229 #define CURSOR_FAULT             3
43230
43231 /* 
43232 ** The database page the PENDING_BYTE occupies. This page is never used.
43233 */
43234 # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
43235
43236 /*
43237 ** These macros define the location of the pointer-map entry for a 
43238 ** database page. The first argument to each is the number of usable
43239 ** bytes on each page of the database (often 1024). The second is the
43240 ** page number to look up in the pointer map.
43241 **
43242 ** PTRMAP_PAGENO returns the database page number of the pointer-map
43243 ** page that stores the required pointer. PTRMAP_PTROFFSET returns
43244 ** the offset of the requested map entry.
43245 **
43246 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
43247 ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
43248 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
43249 ** this test.
43250 */
43251 #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
43252 #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
43253 #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
43254
43255 /*
43256 ** The pointer map is a lookup table that identifies the parent page for
43257 ** each child page in the database file.  The parent page is the page that
43258 ** contains a pointer to the child.  Every page in the database contains
43259 ** 0 or 1 parent pages.  (In this context 'database page' refers
43260 ** to any page that is not part of the pointer map itself.)  Each pointer map
43261 ** entry consists of a single byte 'type' and a 4 byte parent page number.
43262 ** The PTRMAP_XXX identifiers below are the valid types.
43263 **
43264 ** The purpose of the pointer map is to facility moving pages from one
43265 ** position in the file to another as part of autovacuum.  When a page
43266 ** is moved, the pointer in its parent must be updated to point to the
43267 ** new location.  The pointer map is used to locate the parent page quickly.
43268 **
43269 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
43270 **                  used in this case.
43271 **
43272 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number 
43273 **                  is not used in this case.
43274 **
43275 ** PTRMAP_OVERFLOW1: The database page is the first page in a list of 
43276 **                   overflow pages. The page number identifies the page that
43277 **                   contains the cell with a pointer to this overflow page.
43278 **
43279 ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
43280 **                   overflow pages. The page-number identifies the previous
43281 **                   page in the overflow page list.
43282 **
43283 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
43284 **               identifies the parent page in the btree.
43285 */
43286 #define PTRMAP_ROOTPAGE 1
43287 #define PTRMAP_FREEPAGE 2
43288 #define PTRMAP_OVERFLOW1 3
43289 #define PTRMAP_OVERFLOW2 4
43290 #define PTRMAP_BTREE 5
43291
43292 /* A bunch of assert() statements to check the transaction state variables
43293 ** of handle p (type Btree*) are internally consistent.
43294 */
43295 #define btreeIntegrity(p) \
43296   assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
43297   assert( p->pBt->inTransaction>=p->inTrans ); 
43298
43299
43300 /*
43301 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
43302 ** if the database supports auto-vacuum or not. Because it is used
43303 ** within an expression that is an argument to another macro 
43304 ** (sqliteMallocRaw), it is not possible to use conditional compilation.
43305 ** So, this macro is defined instead.
43306 */
43307 #ifndef SQLITE_OMIT_AUTOVACUUM
43308 #define ISAUTOVACUUM (pBt->autoVacuum)
43309 #else
43310 #define ISAUTOVACUUM 0
43311 #endif
43312
43313
43314 /*
43315 ** This structure is passed around through all the sanity checking routines
43316 ** in order to keep track of some global state information.
43317 */
43318 typedef struct IntegrityCk IntegrityCk;
43319 struct IntegrityCk {
43320   BtShared *pBt;    /* The tree being checked out */
43321   Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
43322   Pgno nPage;       /* Number of pages in the database */
43323   int *anRef;       /* Number of times each page is referenced */
43324   int mxErr;        /* Stop accumulating errors when this reaches zero */
43325   int nErr;         /* Number of messages written to zErrMsg so far */
43326   int mallocFailed; /* A memory allocation error has occurred */
43327   StrAccum errMsg;  /* Accumulate the error message text here */
43328 };
43329
43330 /*
43331 ** Read or write a two- and four-byte big-endian integer values.
43332 */
43333 #define get2byte(x)   ((x)[0]<<8 | (x)[1])
43334 #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
43335 #define get4byte sqlite3Get4byte
43336 #define put4byte sqlite3Put4byte
43337
43338 /************** End of btreeInt.h ********************************************/
43339 /************** Continuing where we left off in btmutex.c ********************/
43340 #ifndef SQLITE_OMIT_SHARED_CACHE
43341 #if SQLITE_THREADSAFE
43342
43343 /*
43344 ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
43345 ** set BtShared.db to the database handle associated with p and the
43346 ** p->locked boolean to true.
43347 */
43348 static void lockBtreeMutex(Btree *p){
43349   assert( p->locked==0 );
43350   assert( sqlite3_mutex_notheld(p->pBt->mutex) );
43351   assert( sqlite3_mutex_held(p->db->mutex) );
43352
43353   sqlite3_mutex_enter(p->pBt->mutex);
43354   p->pBt->db = p->db;
43355   p->locked = 1;
43356 }
43357
43358 /*
43359 ** Release the BtShared mutex associated with B-Tree handle p and
43360 ** clear the p->locked boolean.
43361 */
43362 static void unlockBtreeMutex(Btree *p){
43363   assert( p->locked==1 );
43364   assert( sqlite3_mutex_held(p->pBt->mutex) );
43365   assert( sqlite3_mutex_held(p->db->mutex) );
43366   assert( p->db==p->pBt->db );
43367
43368   sqlite3_mutex_leave(p->pBt->mutex);
43369   p->locked = 0;
43370 }
43371
43372 /*
43373 ** Enter a mutex on the given BTree object.
43374 **
43375 ** If the object is not sharable, then no mutex is ever required
43376 ** and this routine is a no-op.  The underlying mutex is non-recursive.
43377 ** But we keep a reference count in Btree.wantToLock so the behavior
43378 ** of this interface is recursive.
43379 **
43380 ** To avoid deadlocks, multiple Btrees are locked in the same order
43381 ** by all database connections.  The p->pNext is a list of other
43382 ** Btrees belonging to the same database connection as the p Btree
43383 ** which need to be locked after p.  If we cannot get a lock on
43384 ** p, then first unlock all of the others on p->pNext, then wait
43385 ** for the lock to become available on p, then relock all of the
43386 ** subsequent Btrees that desire a lock.
43387 */
43388 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
43389   Btree *pLater;
43390
43391   /* Some basic sanity checking on the Btree.  The list of Btrees
43392   ** connected by pNext and pPrev should be in sorted order by
43393   ** Btree.pBt value. All elements of the list should belong to
43394   ** the same connection. Only shared Btrees are on the list. */
43395   assert( p->pNext==0 || p->pNext->pBt>p->pBt );
43396   assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
43397   assert( p->pNext==0 || p->pNext->db==p->db );
43398   assert( p->pPrev==0 || p->pPrev->db==p->db );
43399   assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
43400
43401   /* Check for locking consistency */
43402   assert( !p->locked || p->wantToLock>0 );
43403   assert( p->sharable || p->wantToLock==0 );
43404
43405   /* We should already hold a lock on the database connection */
43406   assert( sqlite3_mutex_held(p->db->mutex) );
43407
43408   /* Unless the database is sharable and unlocked, then BtShared.db
43409   ** should already be set correctly. */
43410   assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
43411
43412   if( !p->sharable ) return;
43413   p->wantToLock++;
43414   if( p->locked ) return;
43415
43416   /* In most cases, we should be able to acquire the lock we
43417   ** want without having to go throught the ascending lock
43418   ** procedure that follows.  Just be sure not to block.
43419   */
43420   if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
43421     p->pBt->db = p->db;
43422     p->locked = 1;
43423     return;
43424   }
43425
43426   /* To avoid deadlock, first release all locks with a larger
43427   ** BtShared address.  Then acquire our lock.  Then reacquire
43428   ** the other BtShared locks that we used to hold in ascending
43429   ** order.
43430   */
43431   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
43432     assert( pLater->sharable );
43433     assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
43434     assert( !pLater->locked || pLater->wantToLock>0 );
43435     if( pLater->locked ){
43436       unlockBtreeMutex(pLater);
43437     }
43438   }
43439   lockBtreeMutex(p);
43440   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
43441     if( pLater->wantToLock ){
43442       lockBtreeMutex(pLater);
43443     }
43444   }
43445 }
43446
43447 /*
43448 ** Exit the recursive mutex on a Btree.
43449 */
43450 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
43451   if( p->sharable ){
43452     assert( p->wantToLock>0 );
43453     p->wantToLock--;
43454     if( p->wantToLock==0 ){
43455       unlockBtreeMutex(p);
43456     }
43457   }
43458 }
43459
43460 #ifndef NDEBUG
43461 /*
43462 ** Return true if the BtShared mutex is held on the btree, or if the
43463 ** B-Tree is not marked as sharable.
43464 **
43465 ** This routine is used only from within assert() statements.
43466 */
43467 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
43468   assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
43469   assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
43470   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
43471   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
43472
43473   return (p->sharable==0 || p->locked);
43474 }
43475 #endif
43476
43477
43478 #ifndef SQLITE_OMIT_INCRBLOB
43479 /*
43480 ** Enter and leave a mutex on a Btree given a cursor owned by that
43481 ** Btree.  These entry points are used by incremental I/O and can be
43482 ** omitted if that module is not used.
43483 */
43484 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
43485   sqlite3BtreeEnter(pCur->pBtree);
43486 }
43487 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
43488   sqlite3BtreeLeave(pCur->pBtree);
43489 }
43490 #endif /* SQLITE_OMIT_INCRBLOB */
43491
43492
43493 /*
43494 ** Enter the mutex on every Btree associated with a database
43495 ** connection.  This is needed (for example) prior to parsing
43496 ** a statement since we will be comparing table and column names
43497 ** against all schemas and we do not want those schemas being
43498 ** reset out from under us.
43499 **
43500 ** There is a corresponding leave-all procedures.
43501 **
43502 ** Enter the mutexes in accending order by BtShared pointer address
43503 ** to avoid the possibility of deadlock when two threads with
43504 ** two or more btrees in common both try to lock all their btrees
43505 ** at the same instant.
43506 */
43507 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
43508   int i;
43509   Btree *p, *pLater;
43510   assert( sqlite3_mutex_held(db->mutex) );
43511   for(i=0; i<db->nDb; i++){
43512     p = db->aDb[i].pBt;
43513     assert( !p || (p->locked==0 && p->sharable) || p->pBt->db==p->db );
43514     if( p && p->sharable ){
43515       p->wantToLock++;
43516       if( !p->locked ){
43517         assert( p->wantToLock==1 );
43518         while( p->pPrev ) p = p->pPrev;
43519         /* Reason for ALWAYS:  There must be at least on unlocked Btree in
43520         ** the chain.  Otherwise the !p->locked test above would have failed */
43521         while( p->locked && ALWAYS(p->pNext) ) p = p->pNext;
43522         for(pLater = p->pNext; pLater; pLater=pLater->pNext){
43523           if( pLater->locked ){
43524             unlockBtreeMutex(pLater);
43525           }
43526         }
43527         while( p ){
43528           lockBtreeMutex(p);
43529           p = p->pNext;
43530         }
43531       }
43532     }
43533   }
43534 }
43535 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
43536   int i;
43537   Btree *p;
43538   assert( sqlite3_mutex_held(db->mutex) );
43539   for(i=0; i<db->nDb; i++){
43540     p = db->aDb[i].pBt;
43541     if( p && p->sharable ){
43542       assert( p->wantToLock>0 );
43543       p->wantToLock--;
43544       if( p->wantToLock==0 ){
43545         unlockBtreeMutex(p);
43546       }
43547     }
43548   }
43549 }
43550
43551 #ifndef NDEBUG
43552 /*
43553 ** Return true if the current thread holds the database connection
43554 ** mutex and all required BtShared mutexes.
43555 **
43556 ** This routine is used inside assert() statements only.
43557 */
43558 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
43559   int i;
43560   if( !sqlite3_mutex_held(db->mutex) ){
43561     return 0;
43562   }
43563   for(i=0; i<db->nDb; i++){
43564     Btree *p;
43565     p = db->aDb[i].pBt;
43566     if( p && p->sharable &&
43567          (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
43568       return 0;
43569     }
43570   }
43571   return 1;
43572 }
43573 #endif /* NDEBUG */
43574
43575 /*
43576 ** Add a new Btree pointer to a BtreeMutexArray. 
43577 ** if the pointer can possibly be shared with
43578 ** another database connection.
43579 **
43580 ** The pointers are kept in sorted order by pBtree->pBt.  That
43581 ** way when we go to enter all the mutexes, we can enter them
43582 ** in order without every having to backup and retry and without
43583 ** worrying about deadlock.
43584 **
43585 ** The number of shared btrees will always be small (usually 0 or 1)
43586 ** so an insertion sort is an adequate algorithm here.
43587 */
43588 SQLITE_PRIVATE void sqlite3BtreeMutexArrayInsert(BtreeMutexArray *pArray, Btree *pBtree){
43589   int i, j;
43590   BtShared *pBt;
43591   if( pBtree==0 || pBtree->sharable==0 ) return;
43592 #ifndef NDEBUG
43593   {
43594     for(i=0; i<pArray->nMutex; i++){
43595       assert( pArray->aBtree[i]!=pBtree );
43596     }
43597   }
43598 #endif
43599   assert( pArray->nMutex>=0 );
43600   assert( pArray->nMutex<ArraySize(pArray->aBtree)-1 );
43601   pBt = pBtree->pBt;
43602   for(i=0; i<pArray->nMutex; i++){
43603     assert( pArray->aBtree[i]!=pBtree );
43604     if( pArray->aBtree[i]->pBt>pBt ){
43605       for(j=pArray->nMutex; j>i; j--){
43606         pArray->aBtree[j] = pArray->aBtree[j-1];
43607       }
43608       pArray->aBtree[i] = pBtree;
43609       pArray->nMutex++;
43610       return;
43611     }
43612   }
43613   pArray->aBtree[pArray->nMutex++] = pBtree;
43614 }
43615
43616 /*
43617 ** Enter the mutex of every btree in the array.  This routine is
43618 ** called at the beginning of sqlite3VdbeExec().  The mutexes are
43619 ** exited at the end of the same function.
43620 */
43621 SQLITE_PRIVATE void sqlite3BtreeMutexArrayEnter(BtreeMutexArray *pArray){
43622   int i;
43623   for(i=0; i<pArray->nMutex; i++){
43624     Btree *p = pArray->aBtree[i];
43625     /* Some basic sanity checking */
43626     assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
43627     assert( !p->locked || p->wantToLock>0 );
43628
43629     /* We should already hold a lock on the database connection */
43630     assert( sqlite3_mutex_held(p->db->mutex) );
43631
43632     /* The Btree is sharable because only sharable Btrees are entered
43633     ** into the array in the first place. */
43634     assert( p->sharable );
43635
43636     p->wantToLock++;
43637     if( !p->locked ){
43638       lockBtreeMutex(p);
43639     }
43640   }
43641 }
43642
43643 /*
43644 ** Leave the mutex of every btree in the group.
43645 */
43646 SQLITE_PRIVATE void sqlite3BtreeMutexArrayLeave(BtreeMutexArray *pArray){
43647   int i;
43648   for(i=0; i<pArray->nMutex; i++){
43649     Btree *p = pArray->aBtree[i];
43650     /* Some basic sanity checking */
43651     assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
43652     assert( p->locked );
43653     assert( p->wantToLock>0 );
43654
43655     /* We should already hold a lock on the database connection */
43656     assert( sqlite3_mutex_held(p->db->mutex) );
43657
43658     p->wantToLock--;
43659     if( p->wantToLock==0 ){
43660       unlockBtreeMutex(p);
43661     }
43662   }
43663 }
43664
43665 #else
43666 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
43667   p->pBt->db = p->db;
43668 }
43669 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
43670   int i;
43671   for(i=0; i<db->nDb; i++){
43672     Btree *p = db->aDb[i].pBt;
43673     if( p ){
43674       p->pBt->db = p->db;
43675     }
43676   }
43677 }
43678 #endif /* if SQLITE_THREADSAFE */
43679 #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
43680
43681 /************** End of btmutex.c *********************************************/
43682 /************** Begin file btree.c *******************************************/
43683 /*
43684 ** 2004 April 6
43685 **
43686 ** The author disclaims copyright to this source code.  In place of
43687 ** a legal notice, here is a blessing:
43688 **
43689 **    May you do good and not evil.
43690 **    May you find forgiveness for yourself and forgive others.
43691 **    May you share freely, never taking more than you give.
43692 **
43693 *************************************************************************
43694 ** This file implements a external (disk-based) database using BTrees.
43695 ** See the header comment on "btreeInt.h" for additional information.
43696 ** Including a description of file format and an overview of operation.
43697 */
43698
43699 /*
43700 ** The header string that appears at the beginning of every
43701 ** SQLite database.
43702 */
43703 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
43704
43705 /*
43706 ** Set this global variable to 1 to enable tracing using the TRACE
43707 ** macro.
43708 */
43709 #if 0
43710 int sqlite3BtreeTrace=1;  /* True to enable tracing */
43711 # define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
43712 #else
43713 # define TRACE(X)
43714 #endif
43715
43716
43717
43718 #ifndef SQLITE_OMIT_SHARED_CACHE
43719 /*
43720 ** A list of BtShared objects that are eligible for participation
43721 ** in shared cache.  This variable has file scope during normal builds,
43722 ** but the test harness needs to access it so we make it global for 
43723 ** test builds.
43724 **
43725 ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
43726 */
43727 #ifdef SQLITE_TEST
43728 SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
43729 #else
43730 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
43731 #endif
43732 #endif /* SQLITE_OMIT_SHARED_CACHE */
43733
43734 #ifndef SQLITE_OMIT_SHARED_CACHE
43735 /*
43736 ** Enable or disable the shared pager and schema features.
43737 **
43738 ** This routine has no effect on existing database connections.
43739 ** The shared cache setting effects only future calls to
43740 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
43741 */
43742 SQLITE_API int sqlite3_enable_shared_cache(int enable){
43743   sqlite3GlobalConfig.sharedCacheEnabled = enable;
43744   return SQLITE_OK;
43745 }
43746 #endif
43747
43748
43749
43750 #ifdef SQLITE_OMIT_SHARED_CACHE
43751   /*
43752   ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
43753   ** and clearAllSharedCacheTableLocks()
43754   ** manipulate entries in the BtShared.pLock linked list used to store
43755   ** shared-cache table level locks. If the library is compiled with the
43756   ** shared-cache feature disabled, then there is only ever one user
43757   ** of each BtShared structure and so this locking is not necessary. 
43758   ** So define the lock related functions as no-ops.
43759   */
43760   #define querySharedCacheTableLock(a,b,c) SQLITE_OK
43761   #define setSharedCacheTableLock(a,b,c) SQLITE_OK
43762   #define clearAllSharedCacheTableLocks(a)
43763   #define downgradeAllSharedCacheTableLocks(a)
43764   #define hasSharedCacheTableLock(a,b,c,d) 1
43765   #define hasReadConflicts(a, b) 0
43766 #endif
43767
43768 #ifndef SQLITE_OMIT_SHARED_CACHE
43769
43770 #ifdef SQLITE_DEBUG
43771 /*
43772 **** This function is only used as part of an assert() statement. ***
43773 **
43774 ** Check to see if pBtree holds the required locks to read or write to the 
43775 ** table with root page iRoot.   Return 1 if it does and 0 if not.
43776 **
43777 ** For example, when writing to a table with root-page iRoot via 
43778 ** Btree connection pBtree:
43779 **
43780 **    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
43781 **
43782 ** When writing to an index that resides in a sharable database, the 
43783 ** caller should have first obtained a lock specifying the root page of
43784 ** the corresponding table. This makes things a bit more complicated,
43785 ** as this module treats each table as a separate structure. To determine
43786 ** the table corresponding to the index being written, this
43787 ** function has to search through the database schema.
43788 **
43789 ** Instead of a lock on the table/index rooted at page iRoot, the caller may
43790 ** hold a write-lock on the schema table (root page 1). This is also
43791 ** acceptable.
43792 */
43793 static int hasSharedCacheTableLock(
43794   Btree *pBtree,         /* Handle that must hold lock */
43795   Pgno iRoot,            /* Root page of b-tree */
43796   int isIndex,           /* True if iRoot is the root of an index b-tree */
43797   int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
43798 ){
43799   Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
43800   Pgno iTab = 0;
43801   BtLock *pLock;
43802
43803   /* If this database is not shareable, or if the client is reading
43804   ** and has the read-uncommitted flag set, then no lock is required. 
43805   ** Return true immediately.
43806   */
43807   if( (pBtree->sharable==0)
43808    || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
43809   ){
43810     return 1;
43811   }
43812
43813   /* If the client is reading  or writing an index and the schema is
43814   ** not loaded, then it is too difficult to actually check to see if
43815   ** the correct locks are held.  So do not bother - just return true.
43816   ** This case does not come up very often anyhow.
43817   */
43818   if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
43819     return 1;
43820   }
43821
43822   /* Figure out the root-page that the lock should be held on. For table
43823   ** b-trees, this is just the root page of the b-tree being read or
43824   ** written. For index b-trees, it is the root page of the associated
43825   ** table.  */
43826   if( isIndex ){
43827     HashElem *p;
43828     for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
43829       Index *pIdx = (Index *)sqliteHashData(p);
43830       if( pIdx->tnum==(int)iRoot ){
43831         iTab = pIdx->pTable->tnum;
43832       }
43833     }
43834   }else{
43835     iTab = iRoot;
43836   }
43837
43838   /* Search for the required lock. Either a write-lock on root-page iTab, a 
43839   ** write-lock on the schema table, or (if the client is reading) a
43840   ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
43841   for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
43842     if( pLock->pBtree==pBtree 
43843      && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
43844      && pLock->eLock>=eLockType 
43845     ){
43846       return 1;
43847     }
43848   }
43849
43850   /* Failed to find the required lock. */
43851   return 0;
43852 }
43853 #endif /* SQLITE_DEBUG */
43854
43855 #ifdef SQLITE_DEBUG
43856 /*
43857 **** This function may be used as part of assert() statements only. ****
43858 **
43859 ** Return true if it would be illegal for pBtree to write into the
43860 ** table or index rooted at iRoot because other shared connections are
43861 ** simultaneously reading that same table or index.
43862 **
43863 ** It is illegal for pBtree to write if some other Btree object that
43864 ** shares the same BtShared object is currently reading or writing
43865 ** the iRoot table.  Except, if the other Btree object has the
43866 ** read-uncommitted flag set, then it is OK for the other object to
43867 ** have a read cursor.
43868 **
43869 ** For example, before writing to any part of the table or index
43870 ** rooted at page iRoot, one should call:
43871 **
43872 **    assert( !hasReadConflicts(pBtree, iRoot) );
43873 */
43874 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
43875   BtCursor *p;
43876   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
43877     if( p->pgnoRoot==iRoot 
43878      && p->pBtree!=pBtree
43879      && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
43880     ){
43881       return 1;
43882     }
43883   }
43884   return 0;
43885 }
43886 #endif    /* #ifdef SQLITE_DEBUG */
43887
43888 /*
43889 ** Query to see if Btree handle p may obtain a lock of type eLock 
43890 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
43891 ** SQLITE_OK if the lock may be obtained (by calling
43892 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
43893 */
43894 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
43895   BtShared *pBt = p->pBt;
43896   BtLock *pIter;
43897
43898   assert( sqlite3BtreeHoldsMutex(p) );
43899   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
43900   assert( p->db!=0 );
43901   assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
43902   
43903   /* If requesting a write-lock, then the Btree must have an open write
43904   ** transaction on this file. And, obviously, for this to be so there 
43905   ** must be an open write transaction on the file itself.
43906   */
43907   assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
43908   assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
43909   
43910   /* This routine is a no-op if the shared-cache is not enabled */
43911   if( !p->sharable ){
43912     return SQLITE_OK;
43913   }
43914
43915   /* If some other connection is holding an exclusive lock, the
43916   ** requested lock may not be obtained.
43917   */
43918   if( pBt->pWriter!=p && pBt->isExclusive ){
43919     sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
43920     return SQLITE_LOCKED_SHAREDCACHE;
43921   }
43922
43923   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
43924     /* The condition (pIter->eLock!=eLock) in the following if(...) 
43925     ** statement is a simplification of:
43926     **
43927     **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
43928     **
43929     ** since we know that if eLock==WRITE_LOCK, then no other connection
43930     ** may hold a WRITE_LOCK on any table in this file (since there can
43931     ** only be a single writer).
43932     */
43933     assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
43934     assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
43935     if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
43936       sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
43937       if( eLock==WRITE_LOCK ){
43938         assert( p==pBt->pWriter );
43939         pBt->isPending = 1;
43940       }
43941       return SQLITE_LOCKED_SHAREDCACHE;
43942     }
43943   }
43944   return SQLITE_OK;
43945 }
43946 #endif /* !SQLITE_OMIT_SHARED_CACHE */
43947
43948 #ifndef SQLITE_OMIT_SHARED_CACHE
43949 /*
43950 ** Add a lock on the table with root-page iTable to the shared-btree used
43951 ** by Btree handle p. Parameter eLock must be either READ_LOCK or 
43952 ** WRITE_LOCK.
43953 **
43954 ** This function assumes the following:
43955 **
43956 **   (a) The specified Btree object p is connected to a sharable
43957 **       database (one with the BtShared.sharable flag set), and
43958 **
43959 **   (b) No other Btree objects hold a lock that conflicts
43960 **       with the requested lock (i.e. querySharedCacheTableLock() has
43961 **       already been called and returned SQLITE_OK).
43962 **
43963 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM 
43964 ** is returned if a malloc attempt fails.
43965 */
43966 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
43967   BtShared *pBt = p->pBt;
43968   BtLock *pLock = 0;
43969   BtLock *pIter;
43970
43971   assert( sqlite3BtreeHoldsMutex(p) );
43972   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
43973   assert( p->db!=0 );
43974
43975   /* A connection with the read-uncommitted flag set will never try to
43976   ** obtain a read-lock using this function. The only read-lock obtained
43977   ** by a connection in read-uncommitted mode is on the sqlite_master 
43978   ** table, and that lock is obtained in BtreeBeginTrans().  */
43979   assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
43980
43981   /* This function should only be called on a sharable b-tree after it 
43982   ** has been determined that no other b-tree holds a conflicting lock.  */
43983   assert( p->sharable );
43984   assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
43985
43986   /* First search the list for an existing lock on this table. */
43987   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
43988     if( pIter->iTable==iTable && pIter->pBtree==p ){
43989       pLock = pIter;
43990       break;
43991     }
43992   }
43993
43994   /* If the above search did not find a BtLock struct associating Btree p
43995   ** with table iTable, allocate one and link it into the list.
43996   */
43997   if( !pLock ){
43998     pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
43999     if( !pLock ){
44000       return SQLITE_NOMEM;
44001     }
44002     pLock->iTable = iTable;
44003     pLock->pBtree = p;
44004     pLock->pNext = pBt->pLock;
44005     pBt->pLock = pLock;
44006   }
44007
44008   /* Set the BtLock.eLock variable to the maximum of the current lock
44009   ** and the requested lock. This means if a write-lock was already held
44010   ** and a read-lock requested, we don't incorrectly downgrade the lock.
44011   */
44012   assert( WRITE_LOCK>READ_LOCK );
44013   if( eLock>pLock->eLock ){
44014     pLock->eLock = eLock;
44015   }
44016
44017   return SQLITE_OK;
44018 }
44019 #endif /* !SQLITE_OMIT_SHARED_CACHE */
44020
44021 #ifndef SQLITE_OMIT_SHARED_CACHE
44022 /*
44023 ** Release all the table locks (locks obtained via calls to
44024 ** the setSharedCacheTableLock() procedure) held by Btree object p.
44025 **
44026 ** This function assumes that Btree p has an open read or write 
44027 ** transaction. If it does not, then the BtShared.isPending variable
44028 ** may be incorrectly cleared.
44029 */
44030 static void clearAllSharedCacheTableLocks(Btree *p){
44031   BtShared *pBt = p->pBt;
44032   BtLock **ppIter = &pBt->pLock;
44033
44034   assert( sqlite3BtreeHoldsMutex(p) );
44035   assert( p->sharable || 0==*ppIter );
44036   assert( p->inTrans>0 );
44037
44038   while( *ppIter ){
44039     BtLock *pLock = *ppIter;
44040     assert( pBt->isExclusive==0 || pBt->pWriter==pLock->pBtree );
44041     assert( pLock->pBtree->inTrans>=pLock->eLock );
44042     if( pLock->pBtree==p ){
44043       *ppIter = pLock->pNext;
44044       assert( pLock->iTable!=1 || pLock==&p->lock );
44045       if( pLock->iTable!=1 ){
44046         sqlite3_free(pLock);
44047       }
44048     }else{
44049       ppIter = &pLock->pNext;
44050     }
44051   }
44052
44053   assert( pBt->isPending==0 || pBt->pWriter );
44054   if( pBt->pWriter==p ){
44055     pBt->pWriter = 0;
44056     pBt->isExclusive = 0;
44057     pBt->isPending = 0;
44058   }else if( pBt->nTransaction==2 ){
44059     /* This function is called when Btree p is concluding its 
44060     ** transaction. If there currently exists a writer, and p is not
44061     ** that writer, then the number of locks held by connections other
44062     ** than the writer must be about to drop to zero. In this case
44063     ** set the isPending flag to 0.
44064     **
44065     ** If there is not currently a writer, then BtShared.isPending must
44066     ** be zero already. So this next line is harmless in that case.
44067     */
44068     pBt->isPending = 0;
44069   }
44070 }
44071
44072 /*
44073 ** This function changes all write-locks held by Btree p into read-locks.
44074 */
44075 static void downgradeAllSharedCacheTableLocks(Btree *p){
44076   BtShared *pBt = p->pBt;
44077   if( pBt->pWriter==p ){
44078     BtLock *pLock;
44079     pBt->pWriter = 0;
44080     pBt->isExclusive = 0;
44081     pBt->isPending = 0;
44082     for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
44083       assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
44084       pLock->eLock = READ_LOCK;
44085     }
44086   }
44087 }
44088
44089 #endif /* SQLITE_OMIT_SHARED_CACHE */
44090
44091 static void releasePage(MemPage *pPage);  /* Forward reference */
44092
44093 /*
44094 ***** This routine is used inside of assert() only ****
44095 **
44096 ** Verify that the cursor holds the mutex on its BtShared
44097 */
44098 #ifdef SQLITE_DEBUG
44099 static int cursorHoldsMutex(BtCursor *p){
44100   return sqlite3_mutex_held(p->pBt->mutex);
44101 }
44102 #endif
44103
44104
44105 #ifndef SQLITE_OMIT_INCRBLOB
44106 /*
44107 ** Invalidate the overflow page-list cache for cursor pCur, if any.
44108 */
44109 static void invalidateOverflowCache(BtCursor *pCur){
44110   assert( cursorHoldsMutex(pCur) );
44111   sqlite3_free(pCur->aOverflow);
44112   pCur->aOverflow = 0;
44113 }
44114
44115 /*
44116 ** Invalidate the overflow page-list cache for all cursors opened
44117 ** on the shared btree structure pBt.
44118 */
44119 static void invalidateAllOverflowCache(BtShared *pBt){
44120   BtCursor *p;
44121   assert( sqlite3_mutex_held(pBt->mutex) );
44122   for(p=pBt->pCursor; p; p=p->pNext){
44123     invalidateOverflowCache(p);
44124   }
44125 }
44126
44127 /*
44128 ** This function is called before modifying the contents of a table
44129 ** to invalidate any incrblob cursors that are open on the
44130 ** row or one of the rows being modified.
44131 **
44132 ** If argument isClearTable is true, then the entire contents of the
44133 ** table is about to be deleted. In this case invalidate all incrblob
44134 ** cursors open on any row within the table with root-page pgnoRoot.
44135 **
44136 ** Otherwise, if argument isClearTable is false, then the row with
44137 ** rowid iRow is being replaced or deleted. In this case invalidate
44138 ** only those incrblob cursors open on that specific row.
44139 */
44140 static void invalidateIncrblobCursors(
44141   Btree *pBtree,          /* The database file to check */
44142   i64 iRow,               /* The rowid that might be changing */
44143   int isClearTable        /* True if all rows are being deleted */
44144 ){
44145   BtCursor *p;
44146   BtShared *pBt = pBtree->pBt;
44147   assert( sqlite3BtreeHoldsMutex(pBtree) );
44148   for(p=pBt->pCursor; p; p=p->pNext){
44149     if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
44150       p->eState = CURSOR_INVALID;
44151     }
44152   }
44153 }
44154
44155 #else
44156   /* Stub functions when INCRBLOB is omitted */
44157   #define invalidateOverflowCache(x)
44158   #define invalidateAllOverflowCache(x)
44159   #define invalidateIncrblobCursors(x,y,z)
44160 #endif /* SQLITE_OMIT_INCRBLOB */
44161
44162 /*
44163 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called 
44164 ** when a page that previously contained data becomes a free-list leaf 
44165 ** page.
44166 **
44167 ** The BtShared.pHasContent bitvec exists to work around an obscure
44168 ** bug caused by the interaction of two useful IO optimizations surrounding
44169 ** free-list leaf pages:
44170 **
44171 **   1) When all data is deleted from a page and the page becomes
44172 **      a free-list leaf page, the page is not written to the database
44173 **      (as free-list leaf pages contain no meaningful data). Sometimes
44174 **      such a page is not even journalled (as it will not be modified,
44175 **      why bother journalling it?).
44176 **
44177 **   2) When a free-list leaf page is reused, its content is not read
44178 **      from the database or written to the journal file (why should it
44179 **      be, if it is not at all meaningful?).
44180 **
44181 ** By themselves, these optimizations work fine and provide a handy
44182 ** performance boost to bulk delete or insert operations. However, if
44183 ** a page is moved to the free-list and then reused within the same
44184 ** transaction, a problem comes up. If the page is not journalled when
44185 ** it is moved to the free-list and it is also not journalled when it
44186 ** is extracted from the free-list and reused, then the original data
44187 ** may be lost. In the event of a rollback, it may not be possible
44188 ** to restore the database to its original configuration.
44189 **
44190 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is 
44191 ** moved to become a free-list leaf page, the corresponding bit is
44192 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
44193 ** optimization 2 above is omitted if the corresponding bit is already
44194 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
44195 ** at the end of every transaction.
44196 */
44197 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
44198   int rc = SQLITE_OK;
44199   if( !pBt->pHasContent ){
44200     assert( pgno<=pBt->nPage );
44201     pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
44202     if( !pBt->pHasContent ){
44203       rc = SQLITE_NOMEM;
44204     }
44205   }
44206   if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
44207     rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
44208   }
44209   return rc;
44210 }
44211
44212 /*
44213 ** Query the BtShared.pHasContent vector.
44214 **
44215 ** This function is called when a free-list leaf page is removed from the
44216 ** free-list for reuse. It returns false if it is safe to retrieve the
44217 ** page from the pager layer with the 'no-content' flag set. True otherwise.
44218 */
44219 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
44220   Bitvec *p = pBt->pHasContent;
44221   return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
44222 }
44223
44224 /*
44225 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
44226 ** invoked at the conclusion of each write-transaction.
44227 */
44228 static void btreeClearHasContent(BtShared *pBt){
44229   sqlite3BitvecDestroy(pBt->pHasContent);
44230   pBt->pHasContent = 0;
44231 }
44232
44233 /*
44234 ** Save the current cursor position in the variables BtCursor.nKey 
44235 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
44236 **
44237 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
44238 ** prior to calling this routine.  
44239 */
44240 static int saveCursorPosition(BtCursor *pCur){
44241   int rc;
44242
44243   assert( CURSOR_VALID==pCur->eState );
44244   assert( 0==pCur->pKey );
44245   assert( cursorHoldsMutex(pCur) );
44246
44247   rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
44248   assert( rc==SQLITE_OK );  /* KeySize() cannot fail */
44249
44250   /* If this is an intKey table, then the above call to BtreeKeySize()
44251   ** stores the integer key in pCur->nKey. In this case this value is
44252   ** all that is required. Otherwise, if pCur is not open on an intKey
44253   ** table, then malloc space for and store the pCur->nKey bytes of key 
44254   ** data.
44255   */
44256   if( 0==pCur->apPage[0]->intKey ){
44257     void *pKey = sqlite3Malloc( (int)pCur->nKey );
44258     if( pKey ){
44259       rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
44260       if( rc==SQLITE_OK ){
44261         pCur->pKey = pKey;
44262       }else{
44263         sqlite3_free(pKey);
44264       }
44265     }else{
44266       rc = SQLITE_NOMEM;
44267     }
44268   }
44269   assert( !pCur->apPage[0]->intKey || !pCur->pKey );
44270
44271   if( rc==SQLITE_OK ){
44272     int i;
44273     for(i=0; i<=pCur->iPage; i++){
44274       releasePage(pCur->apPage[i]);
44275       pCur->apPage[i] = 0;
44276     }
44277     pCur->iPage = -1;
44278     pCur->eState = CURSOR_REQUIRESEEK;
44279   }
44280
44281   invalidateOverflowCache(pCur);
44282   return rc;
44283 }
44284
44285 /*
44286 ** Save the positions of all cursors (except pExcept) that are open on
44287 ** the table  with root-page iRoot. Usually, this is called just before cursor
44288 ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
44289 */
44290 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
44291   BtCursor *p;
44292   assert( sqlite3_mutex_held(pBt->mutex) );
44293   assert( pExcept==0 || pExcept->pBt==pBt );
44294   for(p=pBt->pCursor; p; p=p->pNext){
44295     if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) && 
44296         p->eState==CURSOR_VALID ){
44297       int rc = saveCursorPosition(p);
44298       if( SQLITE_OK!=rc ){
44299         return rc;
44300       }
44301     }
44302   }
44303   return SQLITE_OK;
44304 }
44305
44306 /*
44307 ** Clear the current cursor position.
44308 */
44309 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
44310   assert( cursorHoldsMutex(pCur) );
44311   sqlite3_free(pCur->pKey);
44312   pCur->pKey = 0;
44313   pCur->eState = CURSOR_INVALID;
44314 }
44315
44316 /*
44317 ** In this version of BtreeMoveto, pKey is a packed index record
44318 ** such as is generated by the OP_MakeRecord opcode.  Unpack the
44319 ** record and then call BtreeMovetoUnpacked() to do the work.
44320 */
44321 static int btreeMoveto(
44322   BtCursor *pCur,     /* Cursor open on the btree to be searched */
44323   const void *pKey,   /* Packed key if the btree is an index */
44324   i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
44325   int bias,           /* Bias search to the high end */
44326   int *pRes           /* Write search results here */
44327 ){
44328   int rc;                    /* Status code */
44329   UnpackedRecord *pIdxKey;   /* Unpacked index key */
44330   char aSpace[150];          /* Temp space for pIdxKey - to avoid a malloc */
44331
44332   if( pKey ){
44333     assert( nKey==(i64)(int)nKey );
44334     pIdxKey = sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey,
44335                                       aSpace, sizeof(aSpace));
44336     if( pIdxKey==0 ) return SQLITE_NOMEM;
44337   }else{
44338     pIdxKey = 0;
44339   }
44340   rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
44341   if( pKey ){
44342     sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
44343   }
44344   return rc;
44345 }
44346
44347 /*
44348 ** Restore the cursor to the position it was in (or as close to as possible)
44349 ** when saveCursorPosition() was called. Note that this call deletes the 
44350 ** saved position info stored by saveCursorPosition(), so there can be
44351 ** at most one effective restoreCursorPosition() call after each 
44352 ** saveCursorPosition().
44353 */
44354 static int btreeRestoreCursorPosition(BtCursor *pCur){
44355   int rc;
44356   assert( cursorHoldsMutex(pCur) );
44357   assert( pCur->eState>=CURSOR_REQUIRESEEK );
44358   if( pCur->eState==CURSOR_FAULT ){
44359     return pCur->skipNext;
44360   }
44361   pCur->eState = CURSOR_INVALID;
44362   rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
44363   if( rc==SQLITE_OK ){
44364     sqlite3_free(pCur->pKey);
44365     pCur->pKey = 0;
44366     assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
44367   }
44368   return rc;
44369 }
44370
44371 #define restoreCursorPosition(p) \
44372   (p->eState>=CURSOR_REQUIRESEEK ? \
44373          btreeRestoreCursorPosition(p) : \
44374          SQLITE_OK)
44375
44376 /*
44377 ** Determine whether or not a cursor has moved from the position it
44378 ** was last placed at.  Cursors can move when the row they are pointing
44379 ** at is deleted out from under them.
44380 **
44381 ** This routine returns an error code if something goes wrong.  The
44382 ** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
44383 */
44384 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
44385   int rc;
44386
44387   rc = restoreCursorPosition(pCur);
44388   if( rc ){
44389     *pHasMoved = 1;
44390     return rc;
44391   }
44392   if( pCur->eState!=CURSOR_VALID || pCur->skipNext!=0 ){
44393     *pHasMoved = 1;
44394   }else{
44395     *pHasMoved = 0;
44396   }
44397   return SQLITE_OK;
44398 }
44399
44400 #ifndef SQLITE_OMIT_AUTOVACUUM
44401 /*
44402 ** Given a page number of a regular database page, return the page
44403 ** number for the pointer-map page that contains the entry for the
44404 ** input page number.
44405 */
44406 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
44407   int nPagesPerMapPage;
44408   Pgno iPtrMap, ret;
44409   assert( sqlite3_mutex_held(pBt->mutex) );
44410   nPagesPerMapPage = (pBt->usableSize/5)+1;
44411   iPtrMap = (pgno-2)/nPagesPerMapPage;
44412   ret = (iPtrMap*nPagesPerMapPage) + 2; 
44413   if( ret==PENDING_BYTE_PAGE(pBt) ){
44414     ret++;
44415   }
44416   return ret;
44417 }
44418
44419 /*
44420 ** Write an entry into the pointer map.
44421 **
44422 ** This routine updates the pointer map entry for page number 'key'
44423 ** so that it maps to type 'eType' and parent page number 'pgno'.
44424 **
44425 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
44426 ** a no-op.  If an error occurs, the appropriate error code is written
44427 ** into *pRC.
44428 */
44429 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
44430   DbPage *pDbPage;  /* The pointer map page */
44431   u8 *pPtrmap;      /* The pointer map data */
44432   Pgno iPtrmap;     /* The pointer map page number */
44433   int offset;       /* Offset in pointer map page */
44434   int rc;           /* Return code from subfunctions */
44435
44436   if( *pRC ) return;
44437
44438   assert( sqlite3_mutex_held(pBt->mutex) );
44439   /* The master-journal page number must never be used as a pointer map page */
44440   assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
44441
44442   assert( pBt->autoVacuum );
44443   if( key==0 ){
44444     *pRC = SQLITE_CORRUPT_BKPT;
44445     return;
44446   }
44447   iPtrmap = PTRMAP_PAGENO(pBt, key);
44448   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
44449   if( rc!=SQLITE_OK ){
44450     *pRC = rc;
44451     return;
44452   }
44453   offset = PTRMAP_PTROFFSET(iPtrmap, key);
44454   if( offset<0 ){
44455     *pRC = SQLITE_CORRUPT_BKPT;
44456     goto ptrmap_exit;
44457   }
44458   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
44459
44460   if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
44461     TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
44462     *pRC= rc = sqlite3PagerWrite(pDbPage);
44463     if( rc==SQLITE_OK ){
44464       pPtrmap[offset] = eType;
44465       put4byte(&pPtrmap[offset+1], parent);
44466     }
44467   }
44468
44469 ptrmap_exit:
44470   sqlite3PagerUnref(pDbPage);
44471 }
44472
44473 /*
44474 ** Read an entry from the pointer map.
44475 **
44476 ** This routine retrieves the pointer map entry for page 'key', writing
44477 ** the type and parent page number to *pEType and *pPgno respectively.
44478 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
44479 */
44480 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
44481   DbPage *pDbPage;   /* The pointer map page */
44482   int iPtrmap;       /* Pointer map page index */
44483   u8 *pPtrmap;       /* Pointer map page data */
44484   int offset;        /* Offset of entry in pointer map */
44485   int rc;
44486
44487   assert( sqlite3_mutex_held(pBt->mutex) );
44488
44489   iPtrmap = PTRMAP_PAGENO(pBt, key);
44490   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
44491   if( rc!=0 ){
44492     return rc;
44493   }
44494   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
44495
44496   offset = PTRMAP_PTROFFSET(iPtrmap, key);
44497   assert( pEType!=0 );
44498   *pEType = pPtrmap[offset];
44499   if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
44500
44501   sqlite3PagerUnref(pDbPage);
44502   if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
44503   return SQLITE_OK;
44504 }
44505
44506 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
44507   #define ptrmapPut(w,x,y,z,rc)
44508   #define ptrmapGet(w,x,y,z) SQLITE_OK
44509   #define ptrmapPutOvflPtr(x, y, rc)
44510 #endif
44511
44512 /*
44513 ** Given a btree page and a cell index (0 means the first cell on
44514 ** the page, 1 means the second cell, and so forth) return a pointer
44515 ** to the cell content.
44516 **
44517 ** This routine works only for pages that do not contain overflow cells.
44518 */
44519 #define findCell(P,I) \
44520   ((P)->aData + ((P)->maskPage & get2byte(&(P)->aData[(P)->cellOffset+2*(I)])))
44521
44522 /*
44523 ** This a more complex version of findCell() that works for
44524 ** pages that do contain overflow cells.
44525 */
44526 static u8 *findOverflowCell(MemPage *pPage, int iCell){
44527   int i;
44528   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
44529   for(i=pPage->nOverflow-1; i>=0; i--){
44530     int k;
44531     struct _OvflCell *pOvfl;
44532     pOvfl = &pPage->aOvfl[i];
44533     k = pOvfl->idx;
44534     if( k<=iCell ){
44535       if( k==iCell ){
44536         return pOvfl->pCell;
44537       }
44538       iCell--;
44539     }
44540   }
44541   return findCell(pPage, iCell);
44542 }
44543
44544 /*
44545 ** Parse a cell content block and fill in the CellInfo structure.  There
44546 ** are two versions of this function.  btreeParseCell() takes a 
44547 ** cell index as the second argument and btreeParseCellPtr() 
44548 ** takes a pointer to the body of the cell as its second argument.
44549 **
44550 ** Within this file, the parseCell() macro can be called instead of
44551 ** btreeParseCellPtr(). Using some compilers, this will be faster.
44552 */
44553 static void btreeParseCellPtr(
44554   MemPage *pPage,         /* Page containing the cell */
44555   u8 *pCell,              /* Pointer to the cell text. */
44556   CellInfo *pInfo         /* Fill in this structure */
44557 ){
44558   u16 n;                  /* Number bytes in cell content header */
44559   u32 nPayload;           /* Number of bytes of cell payload */
44560
44561   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
44562
44563   pInfo->pCell = pCell;
44564   assert( pPage->leaf==0 || pPage->leaf==1 );
44565   n = pPage->childPtrSize;
44566   assert( n==4-4*pPage->leaf );
44567   if( pPage->intKey ){
44568     if( pPage->hasData ){
44569       n += getVarint32(&pCell[n], nPayload);
44570     }else{
44571       nPayload = 0;
44572     }
44573     n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
44574     pInfo->nData = nPayload;
44575   }else{
44576     pInfo->nData = 0;
44577     n += getVarint32(&pCell[n], nPayload);
44578     pInfo->nKey = nPayload;
44579   }
44580   pInfo->nPayload = nPayload;
44581   pInfo->nHeader = n;
44582   testcase( nPayload==pPage->maxLocal );
44583   testcase( nPayload==pPage->maxLocal+1 );
44584   if( likely(nPayload<=pPage->maxLocal) ){
44585     /* This is the (easy) common case where the entire payload fits
44586     ** on the local page.  No overflow is required.
44587     */
44588     int nSize;          /* Total size of cell content in bytes */
44589     nSize = nPayload + n;
44590     pInfo->nLocal = (u16)nPayload;
44591     pInfo->iOverflow = 0;
44592     if( (nSize & ~3)==0 ){
44593       nSize = 4;        /* Minimum cell size is 4 */
44594     }
44595     pInfo->nSize = (u16)nSize;
44596   }else{
44597     /* If the payload will not fit completely on the local page, we have
44598     ** to decide how much to store locally and how much to spill onto
44599     ** overflow pages.  The strategy is to minimize the amount of unused
44600     ** space on overflow pages while keeping the amount of local storage
44601     ** in between minLocal and maxLocal.
44602     **
44603     ** Warning:  changing the way overflow payload is distributed in any
44604     ** way will result in an incompatible file format.
44605     */
44606     int minLocal;  /* Minimum amount of payload held locally */
44607     int maxLocal;  /* Maximum amount of payload held locally */
44608     int surplus;   /* Overflow payload available for local storage */
44609
44610     minLocal = pPage->minLocal;
44611     maxLocal = pPage->maxLocal;
44612     surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
44613     testcase( surplus==maxLocal );
44614     testcase( surplus==maxLocal+1 );
44615     if( surplus <= maxLocal ){
44616       pInfo->nLocal = (u16)surplus;
44617     }else{
44618       pInfo->nLocal = (u16)minLocal;
44619     }
44620     pInfo->iOverflow = (u16)(pInfo->nLocal + n);
44621     pInfo->nSize = pInfo->iOverflow + 4;
44622   }
44623 }
44624 #define parseCell(pPage, iCell, pInfo) \
44625   btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
44626 static void btreeParseCell(
44627   MemPage *pPage,         /* Page containing the cell */
44628   int iCell,              /* The cell index.  First cell is 0 */
44629   CellInfo *pInfo         /* Fill in this structure */
44630 ){
44631   parseCell(pPage, iCell, pInfo);
44632 }
44633
44634 /*
44635 ** Compute the total number of bytes that a Cell needs in the cell
44636 ** data area of the btree-page.  The return number includes the cell
44637 ** data header and the local payload, but not any overflow page or
44638 ** the space used by the cell pointer.
44639 */
44640 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
44641   u8 *pIter = &pCell[pPage->childPtrSize];
44642   u32 nSize;
44643
44644 #ifdef SQLITE_DEBUG
44645   /* The value returned by this function should always be the same as
44646   ** the (CellInfo.nSize) value found by doing a full parse of the
44647   ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
44648   ** this function verifies that this invariant is not violated. */
44649   CellInfo debuginfo;
44650   btreeParseCellPtr(pPage, pCell, &debuginfo);
44651 #endif
44652
44653   if( pPage->intKey ){
44654     u8 *pEnd;
44655     if( pPage->hasData ){
44656       pIter += getVarint32(pIter, nSize);
44657     }else{
44658       nSize = 0;
44659     }
44660
44661     /* pIter now points at the 64-bit integer key value, a variable length 
44662     ** integer. The following block moves pIter to point at the first byte
44663     ** past the end of the key value. */
44664     pEnd = &pIter[9];
44665     while( (*pIter++)&0x80 && pIter<pEnd );
44666   }else{
44667     pIter += getVarint32(pIter, nSize);
44668   }
44669
44670   testcase( nSize==pPage->maxLocal );
44671   testcase( nSize==pPage->maxLocal+1 );
44672   if( nSize>pPage->maxLocal ){
44673     int minLocal = pPage->minLocal;
44674     nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
44675     testcase( nSize==pPage->maxLocal );
44676     testcase( nSize==pPage->maxLocal+1 );
44677     if( nSize>pPage->maxLocal ){
44678       nSize = minLocal;
44679     }
44680     nSize += 4;
44681   }
44682   nSize += (u32)(pIter - pCell);
44683
44684   /* The minimum size of any cell is 4 bytes. */
44685   if( nSize<4 ){
44686     nSize = 4;
44687   }
44688
44689   assert( nSize==debuginfo.nSize );
44690   return (u16)nSize;
44691 }
44692
44693 #ifdef SQLITE_DEBUG
44694 /* This variation on cellSizePtr() is used inside of assert() statements
44695 ** only. */
44696 static u16 cellSize(MemPage *pPage, int iCell){
44697   return cellSizePtr(pPage, findCell(pPage, iCell));
44698 }
44699 #endif
44700
44701 #ifndef SQLITE_OMIT_AUTOVACUUM
44702 /*
44703 ** If the cell pCell, part of page pPage contains a pointer
44704 ** to an overflow page, insert an entry into the pointer-map
44705 ** for the overflow page.
44706 */
44707 static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
44708   CellInfo info;
44709   if( *pRC ) return;
44710   assert( pCell!=0 );
44711   btreeParseCellPtr(pPage, pCell, &info);
44712   assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
44713   if( info.iOverflow ){
44714     Pgno ovfl = get4byte(&pCell[info.iOverflow]);
44715     ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
44716   }
44717 }
44718 #endif
44719
44720
44721 /*
44722 ** Defragment the page given.  All Cells are moved to the
44723 ** end of the page and all free space is collected into one
44724 ** big FreeBlk that occurs in between the header and cell
44725 ** pointer array and the cell content area.
44726 */
44727 static int defragmentPage(MemPage *pPage){
44728   int i;                     /* Loop counter */
44729   int pc;                    /* Address of a i-th cell */
44730   int hdr;                   /* Offset to the page header */
44731   int size;                  /* Size of a cell */
44732   int usableSize;            /* Number of usable bytes on a page */
44733   int cellOffset;            /* Offset to the cell pointer array */
44734   int cbrk;                  /* Offset to the cell content area */
44735   int nCell;                 /* Number of cells on the page */
44736   unsigned char *data;       /* The page data */
44737   unsigned char *temp;       /* Temp area for cell content */
44738   int iCellFirst;            /* First allowable cell index */
44739   int iCellLast;             /* Last possible cell index */
44740
44741
44742   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
44743   assert( pPage->pBt!=0 );
44744   assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
44745   assert( pPage->nOverflow==0 );
44746   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
44747   temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
44748   data = pPage->aData;
44749   hdr = pPage->hdrOffset;
44750   cellOffset = pPage->cellOffset;
44751   nCell = pPage->nCell;
44752   assert( nCell==get2byte(&data[hdr+3]) );
44753   usableSize = pPage->pBt->usableSize;
44754   cbrk = get2byte(&data[hdr+5]);
44755   memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
44756   cbrk = usableSize;
44757   iCellFirst = cellOffset + 2*nCell;
44758   iCellLast = usableSize - 4;
44759   for(i=0; i<nCell; i++){
44760     u8 *pAddr;     /* The i-th cell pointer */
44761     pAddr = &data[cellOffset + i*2];
44762     pc = get2byte(pAddr);
44763     testcase( pc==iCellFirst );
44764     testcase( pc==iCellLast );
44765 #if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
44766     /* These conditions have already been verified in btreeInitPage()
44767     ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined 
44768     */
44769     if( pc<iCellFirst || pc>iCellLast ){
44770       return SQLITE_CORRUPT_BKPT;
44771     }
44772 #endif
44773     assert( pc>=iCellFirst && pc<=iCellLast );
44774     size = cellSizePtr(pPage, &temp[pc]);
44775     cbrk -= size;
44776 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
44777     if( cbrk<iCellFirst ){
44778       return SQLITE_CORRUPT_BKPT;
44779     }
44780 #else
44781     if( cbrk<iCellFirst || pc+size>usableSize ){
44782       return SQLITE_CORRUPT_BKPT;
44783     }
44784 #endif
44785     assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
44786     testcase( cbrk+size==usableSize );
44787     testcase( pc+size==usableSize );
44788     memcpy(&data[cbrk], &temp[pc], size);
44789     put2byte(pAddr, cbrk);
44790   }
44791   assert( cbrk>=iCellFirst );
44792   put2byte(&data[hdr+5], cbrk);
44793   data[hdr+1] = 0;
44794   data[hdr+2] = 0;
44795   data[hdr+7] = 0;
44796   memset(&data[iCellFirst], 0, cbrk-iCellFirst);
44797   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
44798   if( cbrk-iCellFirst!=pPage->nFree ){
44799     return SQLITE_CORRUPT_BKPT;
44800   }
44801   return SQLITE_OK;
44802 }
44803
44804 /*
44805 ** Allocate nByte bytes of space from within the B-Tree page passed
44806 ** as the first argument. Write into *pIdx the index into pPage->aData[]
44807 ** of the first byte of allocated space. Return either SQLITE_OK or
44808 ** an error code (usually SQLITE_CORRUPT).
44809 **
44810 ** The caller guarantees that there is sufficient space to make the
44811 ** allocation.  This routine might need to defragment in order to bring
44812 ** all the space together, however.  This routine will avoid using
44813 ** the first two bytes past the cell pointer area since presumably this
44814 ** allocation is being made in order to insert a new cell, so we will
44815 ** also end up needing a new cell pointer.
44816 */
44817 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
44818   const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
44819   u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
44820   int nFrag;                           /* Number of fragmented bytes on pPage */
44821   int top;                             /* First byte of cell content area */
44822   int gap;        /* First byte of gap between cell pointers and cell content */
44823   int rc;         /* Integer return code */
44824   int usableSize; /* Usable size of the page */
44825   
44826   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
44827   assert( pPage->pBt );
44828   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
44829   assert( nByte>=0 );  /* Minimum cell size is 4 */
44830   assert( pPage->nFree>=nByte );
44831   assert( pPage->nOverflow==0 );
44832   usableSize = pPage->pBt->usableSize;
44833   assert( nByte < usableSize-8 );
44834
44835   nFrag = data[hdr+7];
44836   assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
44837   gap = pPage->cellOffset + 2*pPage->nCell;
44838   top = get2byte(&data[hdr+5]);
44839   if( gap>top ) return SQLITE_CORRUPT_BKPT;
44840   testcase( gap+2==top );
44841   testcase( gap+1==top );
44842   testcase( gap==top );
44843
44844   if( nFrag>=60 ){
44845     /* Always defragment highly fragmented pages */
44846     rc = defragmentPage(pPage);
44847     if( rc ) return rc;
44848     top = get2byte(&data[hdr+5]);
44849   }else if( gap+2<=top ){
44850     /* Search the freelist looking for a free slot big enough to satisfy 
44851     ** the request. The allocation is made from the first free slot in 
44852     ** the list that is large enough to accomadate it.
44853     */
44854     int pc, addr;
44855     for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
44856       int size;            /* Size of the free slot */
44857       if( pc>usableSize-4 || pc<addr+4 ){
44858         return SQLITE_CORRUPT_BKPT;
44859       }
44860       size = get2byte(&data[pc+2]);
44861       if( size>=nByte ){
44862         int x = size - nByte;
44863         testcase( x==4 );
44864         testcase( x==3 );
44865         if( x<4 ){
44866           /* Remove the slot from the free-list. Update the number of
44867           ** fragmented bytes within the page. */
44868           memcpy(&data[addr], &data[pc], 2);
44869           data[hdr+7] = (u8)(nFrag + x);
44870         }else if( size+pc > usableSize ){
44871           return SQLITE_CORRUPT_BKPT;
44872         }else{
44873           /* The slot remains on the free-list. Reduce its size to account
44874           ** for the portion used by the new allocation. */
44875           put2byte(&data[pc+2], x);
44876         }
44877         *pIdx = pc + x;
44878         return SQLITE_OK;
44879       }
44880     }
44881   }
44882
44883   /* Check to make sure there is enough space in the gap to satisfy
44884   ** the allocation.  If not, defragment.
44885   */
44886   testcase( gap+2+nByte==top );
44887   if( gap+2+nByte>top ){
44888     rc = defragmentPage(pPage);
44889     if( rc ) return rc;
44890     top = get2byte(&data[hdr+5]);
44891     assert( gap+nByte<=top );
44892   }
44893
44894
44895   /* Allocate memory from the gap in between the cell pointer array
44896   ** and the cell content area.  The btreeInitPage() call has already
44897   ** validated the freelist.  Given that the freelist is valid, there
44898   ** is no way that the allocation can extend off the end of the page.
44899   ** The assert() below verifies the previous sentence.
44900   */
44901   top -= nByte;
44902   put2byte(&data[hdr+5], top);
44903   assert( top+nByte <= pPage->pBt->usableSize );
44904   *pIdx = top;
44905   return SQLITE_OK;
44906 }
44907
44908 /*
44909 ** Return a section of the pPage->aData to the freelist.
44910 ** The first byte of the new free block is pPage->aDisk[start]
44911 ** and the size of the block is "size" bytes.
44912 **
44913 ** Most of the effort here is involved in coalesing adjacent
44914 ** free blocks into a single big free block.
44915 */
44916 static int freeSpace(MemPage *pPage, int start, int size){
44917   int addr, pbegin, hdr;
44918   int iLast;                        /* Largest possible freeblock offset */
44919   unsigned char *data = pPage->aData;
44920
44921   assert( pPage->pBt!=0 );
44922   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
44923   assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
44924   assert( (start + size)<=pPage->pBt->usableSize );
44925   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
44926   assert( size>=0 );   /* Minimum cell size is 4 */
44927
44928   if( pPage->pBt->secureDelete ){
44929     /* Overwrite deleted information with zeros when the secure_delete
44930     ** option is enabled */
44931     memset(&data[start], 0, size);
44932   }
44933
44934   /* Add the space back into the linked list of freeblocks.  Note that
44935   ** even though the freeblock list was checked by btreeInitPage(),
44936   ** btreeInitPage() did not detect overlapping cells or
44937   ** freeblocks that overlapped cells.   Nor does it detect when the
44938   ** cell content area exceeds the value in the page header.  If these
44939   ** situations arise, then subsequent insert operations might corrupt
44940   ** the freelist.  So we do need to check for corruption while scanning
44941   ** the freelist.
44942   */
44943   hdr = pPage->hdrOffset;
44944   addr = hdr + 1;
44945   iLast = pPage->pBt->usableSize - 4;
44946   assert( start<=iLast );
44947   while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
44948     if( pbegin<addr+4 ){
44949       return SQLITE_CORRUPT_BKPT;
44950     }
44951     addr = pbegin;
44952   }
44953   if( pbegin>iLast ){
44954     return SQLITE_CORRUPT_BKPT;
44955   }
44956   assert( pbegin>addr || pbegin==0 );
44957   put2byte(&data[addr], start);
44958   put2byte(&data[start], pbegin);
44959   put2byte(&data[start+2], size);
44960   pPage->nFree = pPage->nFree + (u16)size;
44961
44962   /* Coalesce adjacent free blocks */
44963   addr = hdr + 1;
44964   while( (pbegin = get2byte(&data[addr]))>0 ){
44965     int pnext, psize, x;
44966     assert( pbegin>addr );
44967     assert( pbegin<=pPage->pBt->usableSize-4 );
44968     pnext = get2byte(&data[pbegin]);
44969     psize = get2byte(&data[pbegin+2]);
44970     if( pbegin + psize + 3 >= pnext && pnext>0 ){
44971       int frag = pnext - (pbegin+psize);
44972       if( (frag<0) || (frag>(int)data[hdr+7]) ){
44973         return SQLITE_CORRUPT_BKPT;
44974       }
44975       data[hdr+7] -= (u8)frag;
44976       x = get2byte(&data[pnext]);
44977       put2byte(&data[pbegin], x);
44978       x = pnext + get2byte(&data[pnext+2]) - pbegin;
44979       put2byte(&data[pbegin+2], x);
44980     }else{
44981       addr = pbegin;
44982     }
44983   }
44984
44985   /* If the cell content area begins with a freeblock, remove it. */
44986   if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
44987     int top;
44988     pbegin = get2byte(&data[hdr+1]);
44989     memcpy(&data[hdr+1], &data[pbegin], 2);
44990     top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
44991     put2byte(&data[hdr+5], top);
44992   }
44993   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
44994   return SQLITE_OK;
44995 }
44996
44997 /*
44998 ** Decode the flags byte (the first byte of the header) for a page
44999 ** and initialize fields of the MemPage structure accordingly.
45000 **
45001 ** Only the following combinations are supported.  Anything different
45002 ** indicates a corrupt database files:
45003 **
45004 **         PTF_ZERODATA
45005 **         PTF_ZERODATA | PTF_LEAF
45006 **         PTF_LEAFDATA | PTF_INTKEY
45007 **         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
45008 */
45009 static int decodeFlags(MemPage *pPage, int flagByte){
45010   BtShared *pBt;     /* A copy of pPage->pBt */
45011
45012   assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
45013   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
45014   pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
45015   flagByte &= ~PTF_LEAF;
45016   pPage->childPtrSize = 4-4*pPage->leaf;
45017   pBt = pPage->pBt;
45018   if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
45019     pPage->intKey = 1;
45020     pPage->hasData = pPage->leaf;
45021     pPage->maxLocal = pBt->maxLeaf;
45022     pPage->minLocal = pBt->minLeaf;
45023   }else if( flagByte==PTF_ZERODATA ){
45024     pPage->intKey = 0;
45025     pPage->hasData = 0;
45026     pPage->maxLocal = pBt->maxLocal;
45027     pPage->minLocal = pBt->minLocal;
45028   }else{
45029     return SQLITE_CORRUPT_BKPT;
45030   }
45031   return SQLITE_OK;
45032 }
45033
45034 /*
45035 ** Initialize the auxiliary information for a disk block.
45036 **
45037 ** Return SQLITE_OK on success.  If we see that the page does
45038 ** not contain a well-formed database page, then return 
45039 ** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
45040 ** guarantee that the page is well-formed.  It only shows that
45041 ** we failed to detect any corruption.
45042 */
45043 static int btreeInitPage(MemPage *pPage){
45044
45045   assert( pPage->pBt!=0 );
45046   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
45047   assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
45048   assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
45049   assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
45050
45051   if( !pPage->isInit ){
45052     u16 pc;            /* Address of a freeblock within pPage->aData[] */
45053     u8 hdr;            /* Offset to beginning of page header */
45054     u8 *data;          /* Equal to pPage->aData */
45055     BtShared *pBt;        /* The main btree structure */
45056     u16 usableSize;    /* Amount of usable space on each page */
45057     u16 cellOffset;    /* Offset from start of page to first cell pointer */
45058     u16 nFree;         /* Number of unused bytes on the page */
45059     u16 top;           /* First byte of the cell content area */
45060     int iCellFirst;    /* First allowable cell or freeblock offset */
45061     int iCellLast;     /* Last possible cell or freeblock offset */
45062
45063     pBt = pPage->pBt;
45064
45065     hdr = pPage->hdrOffset;
45066     data = pPage->aData;
45067     if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
45068     assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
45069     pPage->maskPage = pBt->pageSize - 1;
45070     pPage->nOverflow = 0;
45071     usableSize = pBt->usableSize;
45072     pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
45073     top = get2byte(&data[hdr+5]);
45074     pPage->nCell = get2byte(&data[hdr+3]);
45075     if( pPage->nCell>MX_CELL(pBt) ){
45076       /* To many cells for a single page.  The page must be corrupt */
45077       return SQLITE_CORRUPT_BKPT;
45078     }
45079     testcase( pPage->nCell==MX_CELL(pBt) );
45080
45081     /* A malformed database page might cause us to read past the end
45082     ** of page when parsing a cell.  
45083     **
45084     ** The following block of code checks early to see if a cell extends
45085     ** past the end of a page boundary and causes SQLITE_CORRUPT to be 
45086     ** returned if it does.
45087     */
45088     iCellFirst = cellOffset + 2*pPage->nCell;
45089     iCellLast = usableSize - 4;
45090 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
45091     {
45092       int i;            /* Index into the cell pointer array */
45093       int sz;           /* Size of a cell */
45094
45095       if( !pPage->leaf ) iCellLast--;
45096       for(i=0; i<pPage->nCell; i++){
45097         pc = get2byte(&data[cellOffset+i*2]);
45098         testcase( pc==iCellFirst );
45099         testcase( pc==iCellLast );
45100         if( pc<iCellFirst || pc>iCellLast ){
45101           return SQLITE_CORRUPT_BKPT;
45102         }
45103         sz = cellSizePtr(pPage, &data[pc]);
45104         testcase( pc+sz==usableSize );
45105         if( pc+sz>usableSize ){
45106           return SQLITE_CORRUPT_BKPT;
45107         }
45108       }
45109       if( !pPage->leaf ) iCellLast++;
45110     }  
45111 #endif
45112
45113     /* Compute the total free space on the page */
45114     pc = get2byte(&data[hdr+1]);
45115     nFree = data[hdr+7] + top;
45116     while( pc>0 ){
45117       u16 next, size;
45118       if( pc<iCellFirst || pc>iCellLast ){
45119         /* Start of free block is off the page */
45120         return SQLITE_CORRUPT_BKPT; 
45121       }
45122       next = get2byte(&data[pc]);
45123       size = get2byte(&data[pc+2]);
45124       if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
45125         /* Free blocks must be in ascending order. And the last byte of
45126         ** the free-block must lie on the database page.  */
45127         return SQLITE_CORRUPT_BKPT; 
45128       }
45129       nFree = nFree + size;
45130       pc = next;
45131     }
45132
45133     /* At this point, nFree contains the sum of the offset to the start
45134     ** of the cell-content area plus the number of free bytes within
45135     ** the cell-content area. If this is greater than the usable-size
45136     ** of the page, then the page must be corrupted. This check also
45137     ** serves to verify that the offset to the start of the cell-content
45138     ** area, according to the page header, lies within the page.
45139     */
45140     if( nFree>usableSize ){
45141       return SQLITE_CORRUPT_BKPT; 
45142     }
45143     pPage->nFree = (u16)(nFree - iCellFirst);
45144     pPage->isInit = 1;
45145   }
45146   return SQLITE_OK;
45147 }
45148
45149 /*
45150 ** Set up a raw page so that it looks like a database page holding
45151 ** no entries.
45152 */
45153 static void zeroPage(MemPage *pPage, int flags){
45154   unsigned char *data = pPage->aData;
45155   BtShared *pBt = pPage->pBt;
45156   u8 hdr = pPage->hdrOffset;
45157   u16 first;
45158
45159   assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
45160   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
45161   assert( sqlite3PagerGetData(pPage->pDbPage) == data );
45162   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
45163   assert( sqlite3_mutex_held(pBt->mutex) );
45164   if( pBt->secureDelete ){
45165     memset(&data[hdr], 0, pBt->usableSize - hdr);
45166   }
45167   data[hdr] = (char)flags;
45168   first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
45169   memset(&data[hdr+1], 0, 4);
45170   data[hdr+7] = 0;
45171   put2byte(&data[hdr+5], pBt->usableSize);
45172   pPage->nFree = pBt->usableSize - first;
45173   decodeFlags(pPage, flags);
45174   pPage->hdrOffset = hdr;
45175   pPage->cellOffset = first;
45176   pPage->nOverflow = 0;
45177   assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
45178   pPage->maskPage = pBt->pageSize - 1;
45179   pPage->nCell = 0;
45180   pPage->isInit = 1;
45181 }
45182
45183
45184 /*
45185 ** Convert a DbPage obtained from the pager into a MemPage used by
45186 ** the btree layer.
45187 */
45188 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
45189   MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
45190   pPage->aData = sqlite3PagerGetData(pDbPage);
45191   pPage->pDbPage = pDbPage;
45192   pPage->pBt = pBt;
45193   pPage->pgno = pgno;
45194   pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
45195   return pPage; 
45196 }
45197
45198 /*
45199 ** Get a page from the pager.  Initialize the MemPage.pBt and
45200 ** MemPage.aData elements if needed.
45201 **
45202 ** If the noContent flag is set, it means that we do not care about
45203 ** the content of the page at this time.  So do not go to the disk
45204 ** to fetch the content.  Just fill in the content with zeros for now.
45205 ** If in the future we call sqlite3PagerWrite() on this page, that
45206 ** means we have started to be concerned about content and the disk
45207 ** read should occur at that point.
45208 */
45209 static int btreeGetPage(
45210   BtShared *pBt,       /* The btree */
45211   Pgno pgno,           /* Number of the page to fetch */
45212   MemPage **ppPage,    /* Return the page in this parameter */
45213   int noContent        /* Do not load page content if true */
45214 ){
45215   int rc;
45216   DbPage *pDbPage;
45217
45218   assert( sqlite3_mutex_held(pBt->mutex) );
45219   rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
45220   if( rc ) return rc;
45221   *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
45222   return SQLITE_OK;
45223 }
45224
45225 /*
45226 ** Retrieve a page from the pager cache. If the requested page is not
45227 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
45228 ** MemPage.aData elements if needed.
45229 */
45230 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
45231   DbPage *pDbPage;
45232   assert( sqlite3_mutex_held(pBt->mutex) );
45233   pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
45234   if( pDbPage ){
45235     return btreePageFromDbPage(pDbPage, pgno, pBt);
45236   }
45237   return 0;
45238 }
45239
45240 /*
45241 ** Return the size of the database file in pages. If there is any kind of
45242 ** error, return ((unsigned int)-1).
45243 */
45244 static Pgno btreePagecount(BtShared *pBt){
45245   return pBt->nPage;
45246 }
45247 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
45248   assert( sqlite3BtreeHoldsMutex(p) );
45249   assert( ((p->pBt->nPage)&0x8000000)==0 );
45250   return (int)btreePagecount(p->pBt);
45251 }
45252
45253 /*
45254 ** Get a page from the pager and initialize it.  This routine is just a
45255 ** convenience wrapper around separate calls to btreeGetPage() and 
45256 ** btreeInitPage().
45257 **
45258 ** If an error occurs, then the value *ppPage is set to is undefined. It
45259 ** may remain unchanged, or it may be set to an invalid value.
45260 */
45261 static int getAndInitPage(
45262   BtShared *pBt,          /* The database file */
45263   Pgno pgno,           /* Number of the page to get */
45264   MemPage **ppPage     /* Write the page pointer here */
45265 ){
45266   int rc;
45267   assert( sqlite3_mutex_held(pBt->mutex) );
45268
45269   if( pgno>btreePagecount(pBt) ){
45270     rc = SQLITE_CORRUPT_BKPT;
45271   }else{
45272     rc = btreeGetPage(pBt, pgno, ppPage, 0);
45273     if( rc==SQLITE_OK ){
45274       rc = btreeInitPage(*ppPage);
45275       if( rc!=SQLITE_OK ){
45276         releasePage(*ppPage);
45277       }
45278     }
45279   }
45280
45281   testcase( pgno==0 );
45282   assert( pgno!=0 || rc==SQLITE_CORRUPT );
45283   return rc;
45284 }
45285
45286 /*
45287 ** Release a MemPage.  This should be called once for each prior
45288 ** call to btreeGetPage.
45289 */
45290 static void releasePage(MemPage *pPage){
45291   if( pPage ){
45292     assert( pPage->aData );
45293     assert( pPage->pBt );
45294     assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
45295     assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
45296     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
45297     sqlite3PagerUnref(pPage->pDbPage);
45298   }
45299 }
45300
45301 /*
45302 ** During a rollback, when the pager reloads information into the cache
45303 ** so that the cache is restored to its original state at the start of
45304 ** the transaction, for each page restored this routine is called.
45305 **
45306 ** This routine needs to reset the extra data section at the end of the
45307 ** page to agree with the restored data.
45308 */
45309 static void pageReinit(DbPage *pData){
45310   MemPage *pPage;
45311   pPage = (MemPage *)sqlite3PagerGetExtra(pData);
45312   assert( sqlite3PagerPageRefcount(pData)>0 );
45313   if( pPage->isInit ){
45314     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
45315     pPage->isInit = 0;
45316     if( sqlite3PagerPageRefcount(pData)>1 ){
45317       /* pPage might not be a btree page;  it might be an overflow page
45318       ** or ptrmap page or a free page.  In those cases, the following
45319       ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
45320       ** But no harm is done by this.  And it is very important that
45321       ** btreeInitPage() be called on every btree page so we make
45322       ** the call for every page that comes in for re-initing. */
45323       btreeInitPage(pPage);
45324     }
45325   }
45326 }
45327
45328 /*
45329 ** Invoke the busy handler for a btree.
45330 */
45331 static int btreeInvokeBusyHandler(void *pArg){
45332   BtShared *pBt = (BtShared*)pArg;
45333   assert( pBt->db );
45334   assert( sqlite3_mutex_held(pBt->db->mutex) );
45335   return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
45336 }
45337
45338 /*
45339 ** Open a database file.
45340 ** 
45341 ** zFilename is the name of the database file.  If zFilename is NULL
45342 ** a new database with a random name is created.  This randomly named
45343 ** database file will be deleted when sqlite3BtreeClose() is called.
45344 ** If zFilename is ":memory:" then an in-memory database is created
45345 ** that is automatically destroyed when it is closed.
45346 **
45347 ** If the database is already opened in the same database connection
45348 ** and we are in shared cache mode, then the open will fail with an
45349 ** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
45350 ** objects in the same database connection since doing so will lead
45351 ** to problems with locking.
45352 */
45353 SQLITE_PRIVATE int sqlite3BtreeOpen(
45354   const char *zFilename,  /* Name of the file containing the BTree database */
45355   sqlite3 *db,            /* Associated database handle */
45356   Btree **ppBtree,        /* Pointer to new Btree object written here */
45357   int flags,              /* Options */
45358   int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
45359 ){
45360   sqlite3_vfs *pVfs;             /* The VFS to use for this btree */
45361   BtShared *pBt = 0;             /* Shared part of btree structure */
45362   Btree *p;                      /* Handle to return */
45363   sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
45364   int rc = SQLITE_OK;            /* Result code from this function */
45365   u8 nReserve;                   /* Byte of unused space on each page */
45366   unsigned char zDbHeader[100];  /* Database header content */
45367
45368   /* Set the variable isMemdb to true for an in-memory database, or 
45369   ** false for a file-based database. This symbol is only required if
45370   ** either of the shared-data or autovacuum features are compiled 
45371   ** into the library.
45372   */
45373 #if !defined(SQLITE_OMIT_SHARED_CACHE) || !defined(SQLITE_OMIT_AUTOVACUUM)
45374   #ifdef SQLITE_OMIT_MEMORYDB
45375     const int isMemdb = 0;
45376   #else
45377     const int isMemdb = zFilename && !strcmp(zFilename, ":memory:");
45378   #endif
45379 #endif
45380
45381   assert( db!=0 );
45382   assert( sqlite3_mutex_held(db->mutex) );
45383
45384   pVfs = db->pVfs;
45385   p = sqlite3MallocZero(sizeof(Btree));
45386   if( !p ){
45387     return SQLITE_NOMEM;
45388   }
45389   p->inTrans = TRANS_NONE;
45390   p->db = db;
45391 #ifndef SQLITE_OMIT_SHARED_CACHE
45392   p->lock.pBtree = p;
45393   p->lock.iTable = 1;
45394 #endif
45395
45396 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
45397   /*
45398   ** If this Btree is a candidate for shared cache, try to find an
45399   ** existing BtShared object that we can share with
45400   */
45401   if( isMemdb==0 && zFilename && zFilename[0] ){
45402     if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
45403       int nFullPathname = pVfs->mxPathname+1;
45404       char *zFullPathname = sqlite3Malloc(nFullPathname);
45405       sqlite3_mutex *mutexShared;
45406       p->sharable = 1;
45407       if( !zFullPathname ){
45408         sqlite3_free(p);
45409         return SQLITE_NOMEM;
45410       }
45411       sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
45412       mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
45413       sqlite3_mutex_enter(mutexOpen);
45414       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
45415       sqlite3_mutex_enter(mutexShared);
45416       for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
45417         assert( pBt->nRef>0 );
45418         if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
45419                  && sqlite3PagerVfs(pBt->pPager)==pVfs ){
45420           int iDb;
45421           for(iDb=db->nDb-1; iDb>=0; iDb--){
45422             Btree *pExisting = db->aDb[iDb].pBt;
45423             if( pExisting && pExisting->pBt==pBt ){
45424               sqlite3_mutex_leave(mutexShared);
45425               sqlite3_mutex_leave(mutexOpen);
45426               sqlite3_free(zFullPathname);
45427               sqlite3_free(p);
45428               return SQLITE_CONSTRAINT;
45429             }
45430           }
45431           p->pBt = pBt;
45432           pBt->nRef++;
45433           break;
45434         }
45435       }
45436       sqlite3_mutex_leave(mutexShared);
45437       sqlite3_free(zFullPathname);
45438     }
45439 #ifdef SQLITE_DEBUG
45440     else{
45441       /* In debug mode, we mark all persistent databases as sharable
45442       ** even when they are not.  This exercises the locking code and
45443       ** gives more opportunity for asserts(sqlite3_mutex_held())
45444       ** statements to find locking problems.
45445       */
45446       p->sharable = 1;
45447     }
45448 #endif
45449   }
45450 #endif
45451   if( pBt==0 ){
45452     /*
45453     ** The following asserts make sure that structures used by the btree are
45454     ** the right size.  This is to guard against size changes that result
45455     ** when compiling on a different architecture.
45456     */
45457     assert( sizeof(i64)==8 || sizeof(i64)==4 );
45458     assert( sizeof(u64)==8 || sizeof(u64)==4 );
45459     assert( sizeof(u32)==4 );
45460     assert( sizeof(u16)==2 );
45461     assert( sizeof(Pgno)==4 );
45462   
45463     pBt = sqlite3MallocZero( sizeof(*pBt) );
45464     if( pBt==0 ){
45465       rc = SQLITE_NOMEM;
45466       goto btree_open_out;
45467     }
45468     rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
45469                           EXTRA_SIZE, flags, vfsFlags, pageReinit);
45470     if( rc==SQLITE_OK ){
45471       rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
45472     }
45473     if( rc!=SQLITE_OK ){
45474       goto btree_open_out;
45475     }
45476     pBt->db = db;
45477     sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
45478     p->pBt = pBt;
45479   
45480     pBt->pCursor = 0;
45481     pBt->pPage1 = 0;
45482     pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
45483 #ifdef SQLITE_SECURE_DELETE
45484     pBt->secureDelete = 1;
45485 #endif
45486     pBt->pageSize = get2byte(&zDbHeader[16]);
45487     if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
45488          || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
45489       pBt->pageSize = 0;
45490 #ifndef SQLITE_OMIT_AUTOVACUUM
45491       /* If the magic name ":memory:" will create an in-memory database, then
45492       ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
45493       ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
45494       ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
45495       ** regular file-name. In this case the auto-vacuum applies as per normal.
45496       */
45497       if( zFilename && !isMemdb ){
45498         pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
45499         pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
45500       }
45501 #endif
45502       nReserve = 0;
45503     }else{
45504       nReserve = zDbHeader[20];
45505       pBt->pageSizeFixed = 1;
45506 #ifndef SQLITE_OMIT_AUTOVACUUM
45507       pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
45508       pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
45509 #endif
45510     }
45511     rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
45512     if( rc ) goto btree_open_out;
45513     pBt->usableSize = pBt->pageSize - nReserve;
45514     assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
45515    
45516 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
45517     /* Add the new BtShared object to the linked list sharable BtShareds.
45518     */
45519     if( p->sharable ){
45520       sqlite3_mutex *mutexShared;
45521       pBt->nRef = 1;
45522       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
45523       if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
45524         pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
45525         if( pBt->mutex==0 ){
45526           rc = SQLITE_NOMEM;
45527           db->mallocFailed = 0;
45528           goto btree_open_out;
45529         }
45530       }
45531       sqlite3_mutex_enter(mutexShared);
45532       pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
45533       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
45534       sqlite3_mutex_leave(mutexShared);
45535     }
45536 #endif
45537   }
45538
45539 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
45540   /* If the new Btree uses a sharable pBtShared, then link the new
45541   ** Btree into the list of all sharable Btrees for the same connection.
45542   ** The list is kept in ascending order by pBt address.
45543   */
45544   if( p->sharable ){
45545     int i;
45546     Btree *pSib;
45547     for(i=0; i<db->nDb; i++){
45548       if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
45549         while( pSib->pPrev ){ pSib = pSib->pPrev; }
45550         if( p->pBt<pSib->pBt ){
45551           p->pNext = pSib;
45552           p->pPrev = 0;
45553           pSib->pPrev = p;
45554         }else{
45555           while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
45556             pSib = pSib->pNext;
45557           }
45558           p->pNext = pSib->pNext;
45559           p->pPrev = pSib;
45560           if( p->pNext ){
45561             p->pNext->pPrev = p;
45562           }
45563           pSib->pNext = p;
45564         }
45565         break;
45566       }
45567     }
45568   }
45569 #endif
45570   *ppBtree = p;
45571
45572 btree_open_out:
45573   if( rc!=SQLITE_OK ){
45574     if( pBt && pBt->pPager ){
45575       sqlite3PagerClose(pBt->pPager);
45576     }
45577     sqlite3_free(pBt);
45578     sqlite3_free(p);
45579     *ppBtree = 0;
45580   }
45581   if( mutexOpen ){
45582     assert( sqlite3_mutex_held(mutexOpen) );
45583     sqlite3_mutex_leave(mutexOpen);
45584   }
45585   return rc;
45586 }
45587
45588 /*
45589 ** Decrement the BtShared.nRef counter.  When it reaches zero,
45590 ** remove the BtShared structure from the sharing list.  Return
45591 ** true if the BtShared.nRef counter reaches zero and return
45592 ** false if it is still positive.
45593 */
45594 static int removeFromSharingList(BtShared *pBt){
45595 #ifndef SQLITE_OMIT_SHARED_CACHE
45596   sqlite3_mutex *pMaster;
45597   BtShared *pList;
45598   int removed = 0;
45599
45600   assert( sqlite3_mutex_notheld(pBt->mutex) );
45601   pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
45602   sqlite3_mutex_enter(pMaster);
45603   pBt->nRef--;
45604   if( pBt->nRef<=0 ){
45605     if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
45606       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
45607     }else{
45608       pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
45609       while( ALWAYS(pList) && pList->pNext!=pBt ){
45610         pList=pList->pNext;
45611       }
45612       if( ALWAYS(pList) ){
45613         pList->pNext = pBt->pNext;
45614       }
45615     }
45616     if( SQLITE_THREADSAFE ){
45617       sqlite3_mutex_free(pBt->mutex);
45618     }
45619     removed = 1;
45620   }
45621   sqlite3_mutex_leave(pMaster);
45622   return removed;
45623 #else
45624   return 1;
45625 #endif
45626 }
45627
45628 /*
45629 ** Make sure pBt->pTmpSpace points to an allocation of 
45630 ** MX_CELL_SIZE(pBt) bytes.
45631 */
45632 static void allocateTempSpace(BtShared *pBt){
45633   if( !pBt->pTmpSpace ){
45634     pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
45635   }
45636 }
45637
45638 /*
45639 ** Free the pBt->pTmpSpace allocation
45640 */
45641 static void freeTempSpace(BtShared *pBt){
45642   sqlite3PageFree( pBt->pTmpSpace);
45643   pBt->pTmpSpace = 0;
45644 }
45645
45646 /*
45647 ** Close an open database and invalidate all cursors.
45648 */
45649 SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
45650   BtShared *pBt = p->pBt;
45651   BtCursor *pCur;
45652
45653   /* Close all cursors opened via this handle.  */
45654   assert( sqlite3_mutex_held(p->db->mutex) );
45655   sqlite3BtreeEnter(p);
45656   pCur = pBt->pCursor;
45657   while( pCur ){
45658     BtCursor *pTmp = pCur;
45659     pCur = pCur->pNext;
45660     if( pTmp->pBtree==p ){
45661       sqlite3BtreeCloseCursor(pTmp);
45662     }
45663   }
45664
45665   /* Rollback any active transaction and free the handle structure.
45666   ** The call to sqlite3BtreeRollback() drops any table-locks held by
45667   ** this handle.
45668   */
45669   sqlite3BtreeRollback(p);
45670   sqlite3BtreeLeave(p);
45671
45672   /* If there are still other outstanding references to the shared-btree
45673   ** structure, return now. The remainder of this procedure cleans 
45674   ** up the shared-btree.
45675   */
45676   assert( p->wantToLock==0 && p->locked==0 );
45677   if( !p->sharable || removeFromSharingList(pBt) ){
45678     /* The pBt is no longer on the sharing list, so we can access
45679     ** it without having to hold the mutex.
45680     **
45681     ** Clean out and delete the BtShared object.
45682     */
45683     assert( !pBt->pCursor );
45684     sqlite3PagerClose(pBt->pPager);
45685     if( pBt->xFreeSchema && pBt->pSchema ){
45686       pBt->xFreeSchema(pBt->pSchema);
45687     }
45688     sqlite3_free(pBt->pSchema);
45689     freeTempSpace(pBt);
45690     sqlite3_free(pBt);
45691   }
45692
45693 #ifndef SQLITE_OMIT_SHARED_CACHE
45694   assert( p->wantToLock==0 );
45695   assert( p->locked==0 );
45696   if( p->pPrev ) p->pPrev->pNext = p->pNext;
45697   if( p->pNext ) p->pNext->pPrev = p->pPrev;
45698 #endif
45699
45700   sqlite3_free(p);
45701   return SQLITE_OK;
45702 }
45703
45704 /*
45705 ** Change the limit on the number of pages allowed in the cache.
45706 **
45707 ** The maximum number of cache pages is set to the absolute
45708 ** value of mxPage.  If mxPage is negative, the pager will
45709 ** operate asynchronously - it will not stop to do fsync()s
45710 ** to insure data is written to the disk surface before
45711 ** continuing.  Transactions still work if synchronous is off,
45712 ** and the database cannot be corrupted if this program
45713 ** crashes.  But if the operating system crashes or there is
45714 ** an abrupt power failure when synchronous is off, the database
45715 ** could be left in an inconsistent and unrecoverable state.
45716 ** Synchronous is on by default so database corruption is not
45717 ** normally a worry.
45718 */
45719 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
45720   BtShared *pBt = p->pBt;
45721   assert( sqlite3_mutex_held(p->db->mutex) );
45722   sqlite3BtreeEnter(p);
45723   sqlite3PagerSetCachesize(pBt->pPager, mxPage);
45724   sqlite3BtreeLeave(p);
45725   return SQLITE_OK;
45726 }
45727
45728 /*
45729 ** Change the way data is synced to disk in order to increase or decrease
45730 ** how well the database resists damage due to OS crashes and power
45731 ** failures.  Level 1 is the same as asynchronous (no syncs() occur and
45732 ** there is a high probability of damage)  Level 2 is the default.  There
45733 ** is a very low but non-zero probability of damage.  Level 3 reduces the
45734 ** probability of damage to near zero but with a write performance reduction.
45735 */
45736 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
45737 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree *p, int level, int fullSync){
45738   BtShared *pBt = p->pBt;
45739   assert( sqlite3_mutex_held(p->db->mutex) );
45740   sqlite3BtreeEnter(p);
45741   sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync);
45742   sqlite3BtreeLeave(p);
45743   return SQLITE_OK;
45744 }
45745 #endif
45746
45747 /*
45748 ** Return TRUE if the given btree is set to safety level 1.  In other
45749 ** words, return TRUE if no sync() occurs on the disk files.
45750 */
45751 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
45752   BtShared *pBt = p->pBt;
45753   int rc;
45754   assert( sqlite3_mutex_held(p->db->mutex) );  
45755   sqlite3BtreeEnter(p);
45756   assert( pBt && pBt->pPager );
45757   rc = sqlite3PagerNosync(pBt->pPager);
45758   sqlite3BtreeLeave(p);
45759   return rc;
45760 }
45761
45762 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
45763 /*
45764 ** Change the default pages size and the number of reserved bytes per page.
45765 ** Or, if the page size has already been fixed, return SQLITE_READONLY 
45766 ** without changing anything.
45767 **
45768 ** The page size must be a power of 2 between 512 and 65536.  If the page
45769 ** size supplied does not meet this constraint then the page size is not
45770 ** changed.
45771 **
45772 ** Page sizes are constrained to be a power of two so that the region
45773 ** of the database file used for locking (beginning at PENDING_BYTE,
45774 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
45775 ** at the beginning of a page.
45776 **
45777 ** If parameter nReserve is less than zero, then the number of reserved
45778 ** bytes per page is left unchanged.
45779 **
45780 ** If the iFix!=0 then the pageSizeFixed flag is set so that the page size
45781 ** and autovacuum mode can no longer be changed.
45782 */
45783 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
45784   int rc = SQLITE_OK;
45785   BtShared *pBt = p->pBt;
45786   assert( nReserve>=-1 && nReserve<=255 );
45787   sqlite3BtreeEnter(p);
45788   if( pBt->pageSizeFixed ){
45789     sqlite3BtreeLeave(p);
45790     return SQLITE_READONLY;
45791   }
45792   if( nReserve<0 ){
45793     nReserve = pBt->pageSize - pBt->usableSize;
45794   }
45795   assert( nReserve>=0 && nReserve<=255 );
45796   if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
45797         ((pageSize-1)&pageSize)==0 ){
45798     assert( (pageSize & 7)==0 );
45799     assert( !pBt->pPage1 && !pBt->pCursor );
45800     pBt->pageSize = (u16)pageSize;
45801     freeTempSpace(pBt);
45802   }
45803   rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
45804   pBt->usableSize = pBt->pageSize - (u16)nReserve;
45805   if( iFix ) pBt->pageSizeFixed = 1;
45806   sqlite3BtreeLeave(p);
45807   return rc;
45808 }
45809
45810 /*
45811 ** Return the currently defined page size
45812 */
45813 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
45814   return p->pBt->pageSize;
45815 }
45816
45817 /*
45818 ** Return the number of bytes of space at the end of every page that
45819 ** are intentually left unused.  This is the "reserved" space that is
45820 ** sometimes used by extensions.
45821 */
45822 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
45823   int n;
45824   sqlite3BtreeEnter(p);
45825   n = p->pBt->pageSize - p->pBt->usableSize;
45826   sqlite3BtreeLeave(p);
45827   return n;
45828 }
45829
45830 /*
45831 ** Set the maximum page count for a database if mxPage is positive.
45832 ** No changes are made if mxPage is 0 or negative.
45833 ** Regardless of the value of mxPage, return the maximum page count.
45834 */
45835 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
45836   int n;
45837   sqlite3BtreeEnter(p);
45838   n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
45839   sqlite3BtreeLeave(p);
45840   return n;
45841 }
45842
45843 /*
45844 ** Set the secureDelete flag if newFlag is 0 or 1.  If newFlag is -1,
45845 ** then make no changes.  Always return the value of the secureDelete
45846 ** setting after the change.
45847 */
45848 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
45849   int b;
45850   if( p==0 ) return 0;
45851   sqlite3BtreeEnter(p);
45852   if( newFlag>=0 ){
45853     p->pBt->secureDelete = (newFlag!=0) ? 1 : 0;
45854   } 
45855   b = p->pBt->secureDelete;
45856   sqlite3BtreeLeave(p);
45857   return b;
45858 }
45859 #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
45860
45861 /*
45862 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
45863 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
45864 ** is disabled. The default value for the auto-vacuum property is 
45865 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
45866 */
45867 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
45868 #ifdef SQLITE_OMIT_AUTOVACUUM
45869   return SQLITE_READONLY;
45870 #else
45871   BtShared *pBt = p->pBt;
45872   int rc = SQLITE_OK;
45873   u8 av = (u8)autoVacuum;
45874
45875   sqlite3BtreeEnter(p);
45876   if( pBt->pageSizeFixed && (av ?1:0)!=pBt->autoVacuum ){
45877     rc = SQLITE_READONLY;
45878   }else{
45879     pBt->autoVacuum = av ?1:0;
45880     pBt->incrVacuum = av==2 ?1:0;
45881   }
45882   sqlite3BtreeLeave(p);
45883   return rc;
45884 #endif
45885 }
45886
45887 /*
45888 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is 
45889 ** enabled 1 is returned. Otherwise 0.
45890 */
45891 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
45892 #ifdef SQLITE_OMIT_AUTOVACUUM
45893   return BTREE_AUTOVACUUM_NONE;
45894 #else
45895   int rc;
45896   sqlite3BtreeEnter(p);
45897   rc = (
45898     (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
45899     (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
45900     BTREE_AUTOVACUUM_INCR
45901   );
45902   sqlite3BtreeLeave(p);
45903   return rc;
45904 #endif
45905 }
45906
45907
45908 /*
45909 ** Get a reference to pPage1 of the database file.  This will
45910 ** also acquire a readlock on that file.
45911 **
45912 ** SQLITE_OK is returned on success.  If the file is not a
45913 ** well-formed database file, then SQLITE_CORRUPT is returned.
45914 ** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
45915 ** is returned if we run out of memory. 
45916 */
45917 static int lockBtree(BtShared *pBt){
45918   int rc;              /* Result code from subfunctions */
45919   MemPage *pPage1;     /* Page 1 of the database file */
45920   int nPage;           /* Number of pages in the database */
45921   int nPageFile = 0;   /* Number of pages in the database file */
45922   int nPageHeader;     /* Number of pages in the database according to hdr */
45923
45924   assert( sqlite3_mutex_held(pBt->mutex) );
45925   assert( pBt->pPage1==0 );
45926   rc = sqlite3PagerSharedLock(pBt->pPager);
45927   if( rc!=SQLITE_OK ) return rc;
45928   rc = btreeGetPage(pBt, 1, &pPage1, 0);
45929   if( rc!=SQLITE_OK ) return rc;
45930
45931   /* Do some checking to help insure the file we opened really is
45932   ** a valid database file. 
45933   */
45934   nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
45935   if( (rc = sqlite3PagerPagecount(pBt->pPager, &nPageFile))!=SQLITE_OK ){;
45936     goto page1_init_failed;
45937   }
45938   if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
45939     nPage = nPageFile;
45940   }
45941   if( nPage>0 ){
45942     int pageSize;
45943     int usableSize;
45944     u8 *page1 = pPage1->aData;
45945     rc = SQLITE_NOTADB;
45946     if( memcmp(page1, zMagicHeader, 16)!=0 ){
45947       goto page1_init_failed;
45948     }
45949
45950 #ifdef SQLITE_OMIT_WAL
45951     if( page1[18]>1 ){
45952       pBt->readOnly = 1;
45953     }
45954     if( page1[19]>1 ){
45955       goto page1_init_failed;
45956     }
45957 #else
45958     if( page1[18]>2 ){
45959       pBt->readOnly = 1;
45960     }
45961     if( page1[19]>2 ){
45962       goto page1_init_failed;
45963     }
45964
45965     /* If the write version is set to 2, this database should be accessed
45966     ** in WAL mode. If the log is not already open, open it now. Then 
45967     ** return SQLITE_OK and return without populating BtShared.pPage1.
45968     ** The caller detects this and calls this function again. This is
45969     ** required as the version of page 1 currently in the page1 buffer
45970     ** may not be the latest version - there may be a newer one in the log
45971     ** file.
45972     */
45973     if( page1[19]==2 && pBt->doNotUseWAL==0 ){
45974       int isOpen = 0;
45975       rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
45976       if( rc!=SQLITE_OK ){
45977         goto page1_init_failed;
45978       }else if( isOpen==0 ){
45979         releasePage(pPage1);
45980         return SQLITE_OK;
45981       }
45982       rc = SQLITE_NOTADB;
45983     }
45984 #endif
45985
45986     /* The maximum embedded fraction must be exactly 25%.  And the minimum
45987     ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
45988     ** The original design allowed these amounts to vary, but as of
45989     ** version 3.6.0, we require them to be fixed.
45990     */
45991     if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
45992       goto page1_init_failed;
45993     }
45994     pageSize = get2byte(&page1[16]);
45995     if( ((pageSize-1)&pageSize)!=0 || pageSize<512 ||
45996         (SQLITE_MAX_PAGE_SIZE<32768 && pageSize>SQLITE_MAX_PAGE_SIZE)
45997     ){
45998       goto page1_init_failed;
45999     }
46000     assert( (pageSize & 7)==0 );
46001     usableSize = pageSize - page1[20];
46002     if( pageSize!=pBt->pageSize ){
46003       /* After reading the first page of the database assuming a page size
46004       ** of BtShared.pageSize, we have discovered that the page-size is
46005       ** actually pageSize. Unlock the database, leave pBt->pPage1 at
46006       ** zero and return SQLITE_OK. The caller will call this function
46007       ** again with the correct page-size.
46008       */
46009       releasePage(pPage1);
46010       pBt->usableSize = (u16)usableSize;
46011       pBt->pageSize = (u16)pageSize;
46012       freeTempSpace(pBt);
46013       rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
46014                                    pageSize-usableSize);
46015       return rc;
46016     }
46017     if( nPageHeader>nPageFile ){
46018       rc = SQLITE_CORRUPT_BKPT;
46019       goto page1_init_failed;
46020     }
46021     if( usableSize<480 ){
46022       goto page1_init_failed;
46023     }
46024     pBt->pageSize = (u16)pageSize;
46025     pBt->usableSize = (u16)usableSize;
46026 #ifndef SQLITE_OMIT_AUTOVACUUM
46027     pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
46028     pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
46029 #endif
46030   }
46031
46032   /* maxLocal is the maximum amount of payload to store locally for
46033   ** a cell.  Make sure it is small enough so that at least minFanout
46034   ** cells can will fit on one page.  We assume a 10-byte page header.
46035   ** Besides the payload, the cell must store:
46036   **     2-byte pointer to the cell
46037   **     4-byte child pointer
46038   **     9-byte nKey value
46039   **     4-byte nData value
46040   **     4-byte overflow page pointer
46041   ** So a cell consists of a 2-byte poiner, a header which is as much as
46042   ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
46043   ** page pointer.
46044   */
46045   pBt->maxLocal = (pBt->usableSize-12)*64/255 - 23;
46046   pBt->minLocal = (pBt->usableSize-12)*32/255 - 23;
46047   pBt->maxLeaf = pBt->usableSize - 35;
46048   pBt->minLeaf = (pBt->usableSize-12)*32/255 - 23;
46049   assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
46050   pBt->pPage1 = pPage1;
46051   pBt->nPage = nPage;
46052   return SQLITE_OK;
46053
46054 page1_init_failed:
46055   releasePage(pPage1);
46056   pBt->pPage1 = 0;
46057   return rc;
46058 }
46059
46060 /*
46061 ** If there are no outstanding cursors and we are not in the middle
46062 ** of a transaction but there is a read lock on the database, then
46063 ** this routine unrefs the first page of the database file which 
46064 ** has the effect of releasing the read lock.
46065 **
46066 ** If there is a transaction in progress, this routine is a no-op.
46067 */
46068 static void unlockBtreeIfUnused(BtShared *pBt){
46069   assert( sqlite3_mutex_held(pBt->mutex) );
46070   assert( pBt->pCursor==0 || pBt->inTransaction>TRANS_NONE );
46071   if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
46072     assert( pBt->pPage1->aData );
46073     assert( sqlite3PagerRefcount(pBt->pPager)==1 );
46074     assert( pBt->pPage1->aData );
46075     releasePage(pBt->pPage1);
46076     pBt->pPage1 = 0;
46077   }
46078 }
46079
46080 /*
46081 ** If pBt points to an empty file then convert that empty file
46082 ** into a new empty database by initializing the first page of
46083 ** the database.
46084 */
46085 static int newDatabase(BtShared *pBt){
46086   MemPage *pP1;
46087   unsigned char *data;
46088   int rc;
46089
46090   assert( sqlite3_mutex_held(pBt->mutex) );
46091   if( pBt->nPage>0 ){
46092     return SQLITE_OK;
46093   }
46094   pP1 = pBt->pPage1;
46095   assert( pP1!=0 );
46096   data = pP1->aData;
46097   rc = sqlite3PagerWrite(pP1->pDbPage);
46098   if( rc ) return rc;
46099   memcpy(data, zMagicHeader, sizeof(zMagicHeader));
46100   assert( sizeof(zMagicHeader)==16 );
46101   put2byte(&data[16], pBt->pageSize);
46102   data[18] = 1;
46103   data[19] = 1;
46104   assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
46105   data[20] = (u8)(pBt->pageSize - pBt->usableSize);
46106   data[21] = 64;
46107   data[22] = 32;
46108   data[23] = 32;
46109   memset(&data[24], 0, 100-24);
46110   zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
46111   pBt->pageSizeFixed = 1;
46112 #ifndef SQLITE_OMIT_AUTOVACUUM
46113   assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
46114   assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
46115   put4byte(&data[36 + 4*4], pBt->autoVacuum);
46116   put4byte(&data[36 + 7*4], pBt->incrVacuum);
46117 #endif
46118   pBt->nPage = 1;
46119   data[31] = 1;
46120   return SQLITE_OK;
46121 }
46122
46123 /*
46124 ** Attempt to start a new transaction. A write-transaction
46125 ** is started if the second argument is nonzero, otherwise a read-
46126 ** transaction.  If the second argument is 2 or more and exclusive
46127 ** transaction is started, meaning that no other process is allowed
46128 ** to access the database.  A preexisting transaction may not be
46129 ** upgraded to exclusive by calling this routine a second time - the
46130 ** exclusivity flag only works for a new transaction.
46131 **
46132 ** A write-transaction must be started before attempting any 
46133 ** changes to the database.  None of the following routines 
46134 ** will work unless a transaction is started first:
46135 **
46136 **      sqlite3BtreeCreateTable()
46137 **      sqlite3BtreeCreateIndex()
46138 **      sqlite3BtreeClearTable()
46139 **      sqlite3BtreeDropTable()
46140 **      sqlite3BtreeInsert()
46141 **      sqlite3BtreeDelete()
46142 **      sqlite3BtreeUpdateMeta()
46143 **
46144 ** If an initial attempt to acquire the lock fails because of lock contention
46145 ** and the database was previously unlocked, then invoke the busy handler
46146 ** if there is one.  But if there was previously a read-lock, do not
46147 ** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is 
46148 ** returned when there is already a read-lock in order to avoid a deadlock.
46149 **
46150 ** Suppose there are two processes A and B.  A has a read lock and B has
46151 ** a reserved lock.  B tries to promote to exclusive but is blocked because
46152 ** of A's read lock.  A tries to promote to reserved but is blocked by B.
46153 ** One or the other of the two processes must give way or there can be
46154 ** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
46155 ** when A already has a read lock, we encourage A to give up and let B
46156 ** proceed.
46157 */
46158 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
46159   sqlite3 *pBlock = 0;
46160   BtShared *pBt = p->pBt;
46161   int rc = SQLITE_OK;
46162
46163   sqlite3BtreeEnter(p);
46164   btreeIntegrity(p);
46165
46166   /* If the btree is already in a write-transaction, or it
46167   ** is already in a read-transaction and a read-transaction
46168   ** is requested, this is a no-op.
46169   */
46170   if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
46171     goto trans_begun;
46172   }
46173
46174   /* Write transactions are not possible on a read-only database */
46175   if( pBt->readOnly && wrflag ){
46176     rc = SQLITE_READONLY;
46177     goto trans_begun;
46178   }
46179
46180 #ifndef SQLITE_OMIT_SHARED_CACHE
46181   /* If another database handle has already opened a write transaction 
46182   ** on this shared-btree structure and a second write transaction is
46183   ** requested, return SQLITE_LOCKED.
46184   */
46185   if( (wrflag && pBt->inTransaction==TRANS_WRITE) || pBt->isPending ){
46186     pBlock = pBt->pWriter->db;
46187   }else if( wrflag>1 ){
46188     BtLock *pIter;
46189     for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
46190       if( pIter->pBtree!=p ){
46191         pBlock = pIter->pBtree->db;
46192         break;
46193       }
46194     }
46195   }
46196   if( pBlock ){
46197     sqlite3ConnectionBlocked(p->db, pBlock);
46198     rc = SQLITE_LOCKED_SHAREDCACHE;
46199     goto trans_begun;
46200   }
46201 #endif
46202
46203   /* Any read-only or read-write transaction implies a read-lock on 
46204   ** page 1. So if some other shared-cache client already has a write-lock 
46205   ** on page 1, the transaction cannot be opened. */
46206   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
46207   if( SQLITE_OK!=rc ) goto trans_begun;
46208
46209   pBt->initiallyEmpty = (u8)(pBt->nPage==0);
46210   do {
46211     /* Call lockBtree() until either pBt->pPage1 is populated or
46212     ** lockBtree() returns something other than SQLITE_OK. lockBtree()
46213     ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
46214     ** reading page 1 it discovers that the page-size of the database 
46215     ** file is not pBt->pageSize. In this case lockBtree() will update
46216     ** pBt->pageSize to the page-size of the file on disk.
46217     */
46218     while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
46219
46220     if( rc==SQLITE_OK && wrflag ){
46221       if( pBt->readOnly ){
46222         rc = SQLITE_READONLY;
46223       }else{
46224         rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
46225         if( rc==SQLITE_OK ){
46226           rc = newDatabase(pBt);
46227         }
46228       }
46229     }
46230   
46231     if( rc!=SQLITE_OK ){
46232       unlockBtreeIfUnused(pBt);
46233     }
46234   }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
46235           btreeInvokeBusyHandler(pBt) );
46236
46237   if( rc==SQLITE_OK ){
46238     if( p->inTrans==TRANS_NONE ){
46239       pBt->nTransaction++;
46240 #ifndef SQLITE_OMIT_SHARED_CACHE
46241       if( p->sharable ){
46242         assert( p->lock.pBtree==p && p->lock.iTable==1 );
46243         p->lock.eLock = READ_LOCK;
46244         p->lock.pNext = pBt->pLock;
46245         pBt->pLock = &p->lock;
46246       }
46247 #endif
46248     }
46249     p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
46250     if( p->inTrans>pBt->inTransaction ){
46251       pBt->inTransaction = p->inTrans;
46252     }
46253 #ifndef SQLITE_OMIT_SHARED_CACHE
46254     if( wrflag ){
46255       assert( !pBt->pWriter );
46256       pBt->pWriter = p;
46257       pBt->isExclusive = (u8)(wrflag>1);
46258     }
46259 #endif
46260   }
46261
46262
46263 trans_begun:
46264   if( rc==SQLITE_OK && wrflag ){
46265     /* This call makes sure that the pager has the correct number of
46266     ** open savepoints. If the second parameter is greater than 0 and
46267     ** the sub-journal is not already open, then it will be opened here.
46268     */
46269     rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
46270   }
46271
46272   btreeIntegrity(p);
46273   sqlite3BtreeLeave(p);
46274   return rc;
46275 }
46276
46277 #ifndef SQLITE_OMIT_AUTOVACUUM
46278
46279 /*
46280 ** Set the pointer-map entries for all children of page pPage. Also, if
46281 ** pPage contains cells that point to overflow pages, set the pointer
46282 ** map entries for the overflow pages as well.
46283 */
46284 static int setChildPtrmaps(MemPage *pPage){
46285   int i;                             /* Counter variable */
46286   int nCell;                         /* Number of cells in page pPage */
46287   int rc;                            /* Return code */
46288   BtShared *pBt = pPage->pBt;
46289   u8 isInitOrig = pPage->isInit;
46290   Pgno pgno = pPage->pgno;
46291
46292   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
46293   rc = btreeInitPage(pPage);
46294   if( rc!=SQLITE_OK ){
46295     goto set_child_ptrmaps_out;
46296   }
46297   nCell = pPage->nCell;
46298
46299   for(i=0; i<nCell; i++){
46300     u8 *pCell = findCell(pPage, i);
46301
46302     ptrmapPutOvflPtr(pPage, pCell, &rc);
46303
46304     if( !pPage->leaf ){
46305       Pgno childPgno = get4byte(pCell);
46306       ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
46307     }
46308   }
46309
46310   if( !pPage->leaf ){
46311     Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
46312     ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
46313   }
46314
46315 set_child_ptrmaps_out:
46316   pPage->isInit = isInitOrig;
46317   return rc;
46318 }
46319
46320 /*
46321 ** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
46322 ** that it points to iTo. Parameter eType describes the type of pointer to
46323 ** be modified, as  follows:
46324 **
46325 ** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child 
46326 **                   page of pPage.
46327 **
46328 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
46329 **                   page pointed to by one of the cells on pPage.
46330 **
46331 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
46332 **                   overflow page in the list.
46333 */
46334 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
46335   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
46336   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
46337   if( eType==PTRMAP_OVERFLOW2 ){
46338     /* The pointer is always the first 4 bytes of the page in this case.  */
46339     if( get4byte(pPage->aData)!=iFrom ){
46340       return SQLITE_CORRUPT_BKPT;
46341     }
46342     put4byte(pPage->aData, iTo);
46343   }else{
46344     u8 isInitOrig = pPage->isInit;
46345     int i;
46346     int nCell;
46347
46348     btreeInitPage(pPage);
46349     nCell = pPage->nCell;
46350
46351     for(i=0; i<nCell; i++){
46352       u8 *pCell = findCell(pPage, i);
46353       if( eType==PTRMAP_OVERFLOW1 ){
46354         CellInfo info;
46355         btreeParseCellPtr(pPage, pCell, &info);
46356         if( info.iOverflow ){
46357           if( iFrom==get4byte(&pCell[info.iOverflow]) ){
46358             put4byte(&pCell[info.iOverflow], iTo);
46359             break;
46360           }
46361         }
46362       }else{
46363         if( get4byte(pCell)==iFrom ){
46364           put4byte(pCell, iTo);
46365           break;
46366         }
46367       }
46368     }
46369   
46370     if( i==nCell ){
46371       if( eType!=PTRMAP_BTREE || 
46372           get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
46373         return SQLITE_CORRUPT_BKPT;
46374       }
46375       put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
46376     }
46377
46378     pPage->isInit = isInitOrig;
46379   }
46380   return SQLITE_OK;
46381 }
46382
46383
46384 /*
46385 ** Move the open database page pDbPage to location iFreePage in the 
46386 ** database. The pDbPage reference remains valid.
46387 **
46388 ** The isCommit flag indicates that there is no need to remember that
46389 ** the journal needs to be sync()ed before database page pDbPage->pgno 
46390 ** can be written to. The caller has already promised not to write to that
46391 ** page.
46392 */
46393 static int relocatePage(
46394   BtShared *pBt,           /* Btree */
46395   MemPage *pDbPage,        /* Open page to move */
46396   u8 eType,                /* Pointer map 'type' entry for pDbPage */
46397   Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
46398   Pgno iFreePage,          /* The location to move pDbPage to */
46399   int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
46400 ){
46401   MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
46402   Pgno iDbPage = pDbPage->pgno;
46403   Pager *pPager = pBt->pPager;
46404   int rc;
46405
46406   assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 || 
46407       eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
46408   assert( sqlite3_mutex_held(pBt->mutex) );
46409   assert( pDbPage->pBt==pBt );
46410
46411   /* Move page iDbPage from its current location to page number iFreePage */
46412   TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n", 
46413       iDbPage, iFreePage, iPtrPage, eType));
46414   rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
46415   if( rc!=SQLITE_OK ){
46416     return rc;
46417   }
46418   pDbPage->pgno = iFreePage;
46419
46420   /* If pDbPage was a btree-page, then it may have child pages and/or cells
46421   ** that point to overflow pages. The pointer map entries for all these
46422   ** pages need to be changed.
46423   **
46424   ** If pDbPage is an overflow page, then the first 4 bytes may store a
46425   ** pointer to a subsequent overflow page. If this is the case, then
46426   ** the pointer map needs to be updated for the subsequent overflow page.
46427   */
46428   if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
46429     rc = setChildPtrmaps(pDbPage);
46430     if( rc!=SQLITE_OK ){
46431       return rc;
46432     }
46433   }else{
46434     Pgno nextOvfl = get4byte(pDbPage->aData);
46435     if( nextOvfl!=0 ){
46436       ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
46437       if( rc!=SQLITE_OK ){
46438         return rc;
46439       }
46440     }
46441   }
46442
46443   /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
46444   ** that it points at iFreePage. Also fix the pointer map entry for
46445   ** iPtrPage.
46446   */
46447   if( eType!=PTRMAP_ROOTPAGE ){
46448     rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
46449     if( rc!=SQLITE_OK ){
46450       return rc;
46451     }
46452     rc = sqlite3PagerWrite(pPtrPage->pDbPage);
46453     if( rc!=SQLITE_OK ){
46454       releasePage(pPtrPage);
46455       return rc;
46456     }
46457     rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
46458     releasePage(pPtrPage);
46459     if( rc==SQLITE_OK ){
46460       ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
46461     }
46462   }
46463   return rc;
46464 }
46465
46466 /* Forward declaration required by incrVacuumStep(). */
46467 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
46468
46469 /*
46470 ** Perform a single step of an incremental-vacuum. If successful,
46471 ** return SQLITE_OK. If there is no work to do (and therefore no
46472 ** point in calling this function again), return SQLITE_DONE.
46473 **
46474 ** More specificly, this function attempts to re-organize the 
46475 ** database so that the last page of the file currently in use
46476 ** is no longer in use.
46477 **
46478 ** If the nFin parameter is non-zero, this function assumes
46479 ** that the caller will keep calling incrVacuumStep() until
46480 ** it returns SQLITE_DONE or an error, and that nFin is the
46481 ** number of pages the database file will contain after this 
46482 ** process is complete.  If nFin is zero, it is assumed that
46483 ** incrVacuumStep() will be called a finite amount of times
46484 ** which may or may not empty the freelist.  A full autovacuum
46485 ** has nFin>0.  A "PRAGMA incremental_vacuum" has nFin==0.
46486 */
46487 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){
46488   Pgno nFreeList;           /* Number of pages still on the free-list */
46489   int rc;
46490
46491   assert( sqlite3_mutex_held(pBt->mutex) );
46492   assert( iLastPg>nFin );
46493
46494   if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
46495     u8 eType;
46496     Pgno iPtrPage;
46497
46498     nFreeList = get4byte(&pBt->pPage1->aData[36]);
46499     if( nFreeList==0 ){
46500       return SQLITE_DONE;
46501     }
46502
46503     rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
46504     if( rc!=SQLITE_OK ){
46505       return rc;
46506     }
46507     if( eType==PTRMAP_ROOTPAGE ){
46508       return SQLITE_CORRUPT_BKPT;
46509     }
46510
46511     if( eType==PTRMAP_FREEPAGE ){
46512       if( nFin==0 ){
46513         /* Remove the page from the files free-list. This is not required
46514         ** if nFin is non-zero. In that case, the free-list will be
46515         ** truncated to zero after this function returns, so it doesn't 
46516         ** matter if it still contains some garbage entries.
46517         */
46518         Pgno iFreePg;
46519         MemPage *pFreePg;
46520         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
46521         if( rc!=SQLITE_OK ){
46522           return rc;
46523         }
46524         assert( iFreePg==iLastPg );
46525         releasePage(pFreePg);
46526       }
46527     } else {
46528       Pgno iFreePg;             /* Index of free page to move pLastPg to */
46529       MemPage *pLastPg;
46530
46531       rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
46532       if( rc!=SQLITE_OK ){
46533         return rc;
46534       }
46535
46536       /* If nFin is zero, this loop runs exactly once and page pLastPg
46537       ** is swapped with the first free page pulled off the free list.
46538       **
46539       ** On the other hand, if nFin is greater than zero, then keep
46540       ** looping until a free-page located within the first nFin pages
46541       ** of the file is found.
46542       */
46543       do {
46544         MemPage *pFreePg;
46545         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
46546         if( rc!=SQLITE_OK ){
46547           releasePage(pLastPg);
46548           return rc;
46549         }
46550         releasePage(pFreePg);
46551       }while( nFin!=0 && iFreePg>nFin );
46552       assert( iFreePg<iLastPg );
46553       
46554       rc = sqlite3PagerWrite(pLastPg->pDbPage);
46555       if( rc==SQLITE_OK ){
46556         rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
46557       }
46558       releasePage(pLastPg);
46559       if( rc!=SQLITE_OK ){
46560         return rc;
46561       }
46562     }
46563   }
46564
46565   if( nFin==0 ){
46566     iLastPg--;
46567     while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){
46568       if( PTRMAP_ISPAGE(pBt, iLastPg) ){
46569         MemPage *pPg;
46570         rc = btreeGetPage(pBt, iLastPg, &pPg, 0);
46571         if( rc!=SQLITE_OK ){
46572           return rc;
46573         }
46574         rc = sqlite3PagerWrite(pPg->pDbPage);
46575         releasePage(pPg);
46576         if( rc!=SQLITE_OK ){
46577           return rc;
46578         }
46579       }
46580       iLastPg--;
46581     }
46582     sqlite3PagerTruncateImage(pBt->pPager, iLastPg);
46583     pBt->nPage = iLastPg;
46584   }
46585   return SQLITE_OK;
46586 }
46587
46588 /*
46589 ** A write-transaction must be opened before calling this function.
46590 ** It performs a single unit of work towards an incremental vacuum.
46591 **
46592 ** If the incremental vacuum is finished after this function has run,
46593 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
46594 ** SQLITE_OK is returned. Otherwise an SQLite error code. 
46595 */
46596 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
46597   int rc;
46598   BtShared *pBt = p->pBt;
46599
46600   sqlite3BtreeEnter(p);
46601   assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
46602   if( !pBt->autoVacuum ){
46603     rc = SQLITE_DONE;
46604   }else{
46605     invalidateAllOverflowCache(pBt);
46606     rc = incrVacuumStep(pBt, 0, btreePagecount(pBt));
46607     if( rc==SQLITE_OK ){
46608       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
46609       put4byte(&pBt->pPage1->aData[28], pBt->nPage);
46610     }
46611   }
46612   sqlite3BtreeLeave(p);
46613   return rc;
46614 }
46615
46616 /*
46617 ** This routine is called prior to sqlite3PagerCommit when a transaction
46618 ** is commited for an auto-vacuum database.
46619 **
46620 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
46621 ** the database file should be truncated to during the commit process. 
46622 ** i.e. the database has been reorganized so that only the first *pnTrunc
46623 ** pages are in use.
46624 */
46625 static int autoVacuumCommit(BtShared *pBt){
46626   int rc = SQLITE_OK;
46627   Pager *pPager = pBt->pPager;
46628   VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
46629
46630   assert( sqlite3_mutex_held(pBt->mutex) );
46631   invalidateAllOverflowCache(pBt);
46632   assert(pBt->autoVacuum);
46633   if( !pBt->incrVacuum ){
46634     Pgno nFin;         /* Number of pages in database after autovacuuming */
46635     Pgno nFree;        /* Number of pages on the freelist initially */
46636     Pgno nPtrmap;      /* Number of PtrMap pages to be freed */
46637     Pgno iFree;        /* The next page to be freed */
46638     int nEntry;        /* Number of entries on one ptrmap page */
46639     Pgno nOrig;        /* Database size before freeing */
46640
46641     nOrig = btreePagecount(pBt);
46642     if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
46643       /* It is not possible to create a database for which the final page
46644       ** is either a pointer-map page or the pending-byte page. If one
46645       ** is encountered, this indicates corruption.
46646       */
46647       return SQLITE_CORRUPT_BKPT;
46648     }
46649
46650     nFree = get4byte(&pBt->pPage1->aData[36]);
46651     nEntry = pBt->usableSize/5;
46652     nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
46653     nFin = nOrig - nFree - nPtrmap;
46654     if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
46655       nFin--;
46656     }
46657     while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
46658       nFin--;
46659     }
46660     if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
46661
46662     for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
46663       rc = incrVacuumStep(pBt, nFin, iFree);
46664     }
46665     if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
46666       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
46667       put4byte(&pBt->pPage1->aData[32], 0);
46668       put4byte(&pBt->pPage1->aData[36], 0);
46669       put4byte(&pBt->pPage1->aData[28], nFin);
46670       sqlite3PagerTruncateImage(pBt->pPager, nFin);
46671       pBt->nPage = nFin;
46672     }
46673     if( rc!=SQLITE_OK ){
46674       sqlite3PagerRollback(pPager);
46675     }
46676   }
46677
46678   assert( nRef==sqlite3PagerRefcount(pPager) );
46679   return rc;
46680 }
46681
46682 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
46683 # define setChildPtrmaps(x) SQLITE_OK
46684 #endif
46685
46686 /*
46687 ** This routine does the first phase of a two-phase commit.  This routine
46688 ** causes a rollback journal to be created (if it does not already exist)
46689 ** and populated with enough information so that if a power loss occurs
46690 ** the database can be restored to its original state by playing back
46691 ** the journal.  Then the contents of the journal are flushed out to
46692 ** the disk.  After the journal is safely on oxide, the changes to the
46693 ** database are written into the database file and flushed to oxide.
46694 ** At the end of this call, the rollback journal still exists on the
46695 ** disk and we are still holding all locks, so the transaction has not
46696 ** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
46697 ** commit process.
46698 **
46699 ** This call is a no-op if no write-transaction is currently active on pBt.
46700 **
46701 ** Otherwise, sync the database file for the btree pBt. zMaster points to
46702 ** the name of a master journal file that should be written into the
46703 ** individual journal file, or is NULL, indicating no master journal file 
46704 ** (single database transaction).
46705 **
46706 ** When this is called, the master journal should already have been
46707 ** created, populated with this journal pointer and synced to disk.
46708 **
46709 ** Once this is routine has returned, the only thing required to commit
46710 ** the write-transaction for this database file is to delete the journal.
46711 */
46712 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
46713   int rc = SQLITE_OK;
46714   if( p->inTrans==TRANS_WRITE ){
46715     BtShared *pBt = p->pBt;
46716     sqlite3BtreeEnter(p);
46717 #ifndef SQLITE_OMIT_AUTOVACUUM
46718     if( pBt->autoVacuum ){
46719       rc = autoVacuumCommit(pBt);
46720       if( rc!=SQLITE_OK ){
46721         sqlite3BtreeLeave(p);
46722         return rc;
46723       }
46724     }
46725 #endif
46726     rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
46727     sqlite3BtreeLeave(p);
46728   }
46729   return rc;
46730 }
46731
46732 /*
46733 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
46734 ** at the conclusion of a transaction.
46735 */
46736 static void btreeEndTransaction(Btree *p){
46737   BtShared *pBt = p->pBt;
46738   assert( sqlite3BtreeHoldsMutex(p) );
46739
46740   btreeClearHasContent(pBt);
46741   if( p->inTrans>TRANS_NONE && p->db->activeVdbeCnt>1 ){
46742     /* If there are other active statements that belong to this database
46743     ** handle, downgrade to a read-only transaction. The other statements
46744     ** may still be reading from the database.  */
46745     downgradeAllSharedCacheTableLocks(p);
46746     p->inTrans = TRANS_READ;
46747   }else{
46748     /* If the handle had any kind of transaction open, decrement the 
46749     ** transaction count of the shared btree. If the transaction count 
46750     ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
46751     ** call below will unlock the pager.  */
46752     if( p->inTrans!=TRANS_NONE ){
46753       clearAllSharedCacheTableLocks(p);
46754       pBt->nTransaction--;
46755       if( 0==pBt->nTransaction ){
46756         pBt->inTransaction = TRANS_NONE;
46757       }
46758     }
46759
46760     /* Set the current transaction state to TRANS_NONE and unlock the 
46761     ** pager if this call closed the only read or write transaction.  */
46762     p->inTrans = TRANS_NONE;
46763     unlockBtreeIfUnused(pBt);
46764   }
46765
46766   btreeIntegrity(p);
46767 }
46768
46769 /*
46770 ** Commit the transaction currently in progress.
46771 **
46772 ** This routine implements the second phase of a 2-phase commit.  The
46773 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
46774 ** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
46775 ** routine did all the work of writing information out to disk and flushing the
46776 ** contents so that they are written onto the disk platter.  All this
46777 ** routine has to do is delete or truncate or zero the header in the
46778 ** the rollback journal (which causes the transaction to commit) and
46779 ** drop locks.
46780 **
46781 ** This will release the write lock on the database file.  If there
46782 ** are no active cursors, it also releases the read lock.
46783 */
46784 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p){
46785   BtShared *pBt = p->pBt;
46786
46787   sqlite3BtreeEnter(p);
46788   btreeIntegrity(p);
46789
46790   /* If the handle has a write-transaction open, commit the shared-btrees 
46791   ** transaction and set the shared state to TRANS_READ.
46792   */
46793   if( p->inTrans==TRANS_WRITE ){
46794     int rc;
46795     assert( pBt->inTransaction==TRANS_WRITE );
46796     assert( pBt->nTransaction>0 );
46797     rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
46798     if( rc!=SQLITE_OK ){
46799       sqlite3BtreeLeave(p);
46800       return rc;
46801     }
46802     pBt->inTransaction = TRANS_READ;
46803   }
46804
46805   btreeEndTransaction(p);
46806   sqlite3BtreeLeave(p);
46807   return SQLITE_OK;
46808 }
46809
46810 /*
46811 ** Do both phases of a commit.
46812 */
46813 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
46814   int rc;
46815   sqlite3BtreeEnter(p);
46816   rc = sqlite3BtreeCommitPhaseOne(p, 0);
46817   if( rc==SQLITE_OK ){
46818     rc = sqlite3BtreeCommitPhaseTwo(p);
46819   }
46820   sqlite3BtreeLeave(p);
46821   return rc;
46822 }
46823
46824 #ifndef NDEBUG
46825 /*
46826 ** Return the number of write-cursors open on this handle. This is for use
46827 ** in assert() expressions, so it is only compiled if NDEBUG is not
46828 ** defined.
46829 **
46830 ** For the purposes of this routine, a write-cursor is any cursor that
46831 ** is capable of writing to the databse.  That means the cursor was
46832 ** originally opened for writing and the cursor has not be disabled
46833 ** by having its state changed to CURSOR_FAULT.
46834 */
46835 static int countWriteCursors(BtShared *pBt){
46836   BtCursor *pCur;
46837   int r = 0;
46838   for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
46839     if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++; 
46840   }
46841   return r;
46842 }
46843 #endif
46844
46845 /*
46846 ** This routine sets the state to CURSOR_FAULT and the error
46847 ** code to errCode for every cursor on BtShared that pBtree
46848 ** references.
46849 **
46850 ** Every cursor is tripped, including cursors that belong
46851 ** to other database connections that happen to be sharing
46852 ** the cache with pBtree.
46853 **
46854 ** This routine gets called when a rollback occurs.
46855 ** All cursors using the same cache must be tripped
46856 ** to prevent them from trying to use the btree after
46857 ** the rollback.  The rollback may have deleted tables
46858 ** or moved root pages, so it is not sufficient to
46859 ** save the state of the cursor.  The cursor must be
46860 ** invalidated.
46861 */
46862 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
46863   BtCursor *p;
46864   sqlite3BtreeEnter(pBtree);
46865   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
46866     int i;
46867     sqlite3BtreeClearCursor(p);
46868     p->eState = CURSOR_FAULT;
46869     p->skipNext = errCode;
46870     for(i=0; i<=p->iPage; i++){
46871       releasePage(p->apPage[i]);
46872       p->apPage[i] = 0;
46873     }
46874   }
46875   sqlite3BtreeLeave(pBtree);
46876 }
46877
46878 /*
46879 ** Rollback the transaction in progress.  All cursors will be
46880 ** invalided by this operation.  Any attempt to use a cursor
46881 ** that was open at the beginning of this operation will result
46882 ** in an error.
46883 **
46884 ** This will release the write lock on the database file.  If there
46885 ** are no active cursors, it also releases the read lock.
46886 */
46887 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p){
46888   int rc;
46889   BtShared *pBt = p->pBt;
46890   MemPage *pPage1;
46891
46892   sqlite3BtreeEnter(p);
46893   rc = saveAllCursors(pBt, 0, 0);
46894 #ifndef SQLITE_OMIT_SHARED_CACHE
46895   if( rc!=SQLITE_OK ){
46896     /* This is a horrible situation. An IO or malloc() error occurred whilst
46897     ** trying to save cursor positions. If this is an automatic rollback (as
46898     ** the result of a constraint, malloc() failure or IO error) then 
46899     ** the cache may be internally inconsistent (not contain valid trees) so
46900     ** we cannot simply return the error to the caller. Instead, abort 
46901     ** all queries that may be using any of the cursors that failed to save.
46902     */
46903     sqlite3BtreeTripAllCursors(p, rc);
46904   }
46905 #endif
46906   btreeIntegrity(p);
46907
46908   if( p->inTrans==TRANS_WRITE ){
46909     int rc2;
46910
46911     assert( TRANS_WRITE==pBt->inTransaction );
46912     rc2 = sqlite3PagerRollback(pBt->pPager);
46913     if( rc2!=SQLITE_OK ){
46914       rc = rc2;
46915     }
46916
46917     /* The rollback may have destroyed the pPage1->aData value.  So
46918     ** call btreeGetPage() on page 1 again to make
46919     ** sure pPage1->aData is set correctly. */
46920     if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
46921       int nPage = get4byte(28+(u8*)pPage1->aData);
46922       testcase( nPage==0 );
46923       if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
46924       testcase( pBt->nPage!=nPage );
46925       pBt->nPage = nPage;
46926       releasePage(pPage1);
46927     }
46928     assert( countWriteCursors(pBt)==0 );
46929     pBt->inTransaction = TRANS_READ;
46930   }
46931
46932   btreeEndTransaction(p);
46933   sqlite3BtreeLeave(p);
46934   return rc;
46935 }
46936
46937 /*
46938 ** Start a statement subtransaction. The subtransaction can can be rolled
46939 ** back independently of the main transaction. You must start a transaction 
46940 ** before starting a subtransaction. The subtransaction is ended automatically 
46941 ** if the main transaction commits or rolls back.
46942 **
46943 ** Statement subtransactions are used around individual SQL statements
46944 ** that are contained within a BEGIN...COMMIT block.  If a constraint
46945 ** error occurs within the statement, the effect of that one statement
46946 ** can be rolled back without having to rollback the entire transaction.
46947 **
46948 ** A statement sub-transaction is implemented as an anonymous savepoint. The
46949 ** value passed as the second parameter is the total number of savepoints,
46950 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
46951 ** are no active savepoints and no other statement-transactions open,
46952 ** iStatement is 1. This anonymous savepoint can be released or rolled back
46953 ** using the sqlite3BtreeSavepoint() function.
46954 */
46955 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
46956   int rc;
46957   BtShared *pBt = p->pBt;
46958   sqlite3BtreeEnter(p);
46959   assert( p->inTrans==TRANS_WRITE );
46960   assert( pBt->readOnly==0 );
46961   assert( iStatement>0 );
46962   assert( iStatement>p->db->nSavepoint );
46963   assert( pBt->inTransaction==TRANS_WRITE );
46964   /* At the pager level, a statement transaction is a savepoint with
46965   ** an index greater than all savepoints created explicitly using
46966   ** SQL statements. It is illegal to open, release or rollback any
46967   ** such savepoints while the statement transaction savepoint is active.
46968   */
46969   rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
46970   sqlite3BtreeLeave(p);
46971   return rc;
46972 }
46973
46974 /*
46975 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
46976 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
46977 ** savepoint identified by parameter iSavepoint, depending on the value 
46978 ** of op.
46979 **
46980 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
46981 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the 
46982 ** contents of the entire transaction are rolled back. This is different
46983 ** from a normal transaction rollback, as no locks are released and the
46984 ** transaction remains open.
46985 */
46986 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
46987   int rc = SQLITE_OK;
46988   if( p && p->inTrans==TRANS_WRITE ){
46989     BtShared *pBt = p->pBt;
46990     assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
46991     assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
46992     sqlite3BtreeEnter(p);
46993     rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
46994     if( rc==SQLITE_OK ){
46995       if( iSavepoint<0 && pBt->initiallyEmpty ) pBt->nPage = 0;
46996       rc = newDatabase(pBt);
46997       pBt->nPage = get4byte(28 + pBt->pPage1->aData);
46998       if( pBt->nPage==0 ){
46999         sqlite3PagerPagecount(pBt->pPager, (int*)&pBt->nPage);
47000       }
47001     }
47002     sqlite3BtreeLeave(p);
47003   }
47004   return rc;
47005 }
47006
47007 /*
47008 ** Create a new cursor for the BTree whose root is on the page
47009 ** iTable. If a read-only cursor is requested, it is assumed that
47010 ** the caller already has at least a read-only transaction open
47011 ** on the database already. If a write-cursor is requested, then
47012 ** the caller is assumed to have an open write transaction.
47013 **
47014 ** If wrFlag==0, then the cursor can only be used for reading.
47015 ** If wrFlag==1, then the cursor can be used for reading or for
47016 ** writing if other conditions for writing are also met.  These
47017 ** are the conditions that must be met in order for writing to
47018 ** be allowed:
47019 **
47020 ** 1:  The cursor must have been opened with wrFlag==1
47021 **
47022 ** 2:  Other database connections that share the same pager cache
47023 **     but which are not in the READ_UNCOMMITTED state may not have
47024 **     cursors open with wrFlag==0 on the same table.  Otherwise
47025 **     the changes made by this write cursor would be visible to
47026 **     the read cursors in the other database connection.
47027 **
47028 ** 3:  The database must be writable (not on read-only media)
47029 **
47030 ** 4:  There must be an active transaction.
47031 **
47032 ** No checking is done to make sure that page iTable really is the
47033 ** root page of a b-tree.  If it is not, then the cursor acquired
47034 ** will not work correctly.
47035 **
47036 ** It is assumed that the sqlite3BtreeCursorZero() has been called
47037 ** on pCur to initialize the memory space prior to invoking this routine.
47038 */
47039 static int btreeCursor(
47040   Btree *p,                              /* The btree */
47041   int iTable,                            /* Root page of table to open */
47042   int wrFlag,                            /* 1 to write. 0 read-only */
47043   struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
47044   BtCursor *pCur                         /* Space for new cursor */
47045 ){
47046   BtShared *pBt = p->pBt;                /* Shared b-tree handle */
47047
47048   assert( sqlite3BtreeHoldsMutex(p) );
47049   assert( wrFlag==0 || wrFlag==1 );
47050
47051   /* The following assert statements verify that if this is a sharable 
47052   ** b-tree database, the connection is holding the required table locks, 
47053   ** and that no other connection has any open cursor that conflicts with 
47054   ** this lock.  */
47055   assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
47056   assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
47057
47058   /* Assert that the caller has opened the required transaction. */
47059   assert( p->inTrans>TRANS_NONE );
47060   assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
47061   assert( pBt->pPage1 && pBt->pPage1->aData );
47062
47063   if( NEVER(wrFlag && pBt->readOnly) ){
47064     return SQLITE_READONLY;
47065   }
47066   if( iTable==1 && btreePagecount(pBt)==0 ){
47067     return SQLITE_EMPTY;
47068   }
47069
47070   /* Now that no other errors can occur, finish filling in the BtCursor
47071   ** variables and link the cursor into the BtShared list.  */
47072   pCur->pgnoRoot = (Pgno)iTable;
47073   pCur->iPage = -1;
47074   pCur->pKeyInfo = pKeyInfo;
47075   pCur->pBtree = p;
47076   pCur->pBt = pBt;
47077   pCur->wrFlag = (u8)wrFlag;
47078   pCur->pNext = pBt->pCursor;
47079   if( pCur->pNext ){
47080     pCur->pNext->pPrev = pCur;
47081   }
47082   pBt->pCursor = pCur;
47083   pCur->eState = CURSOR_INVALID;
47084   pCur->cachedRowid = 0;
47085   return SQLITE_OK;
47086 }
47087 SQLITE_PRIVATE int sqlite3BtreeCursor(
47088   Btree *p,                                   /* The btree */
47089   int iTable,                                 /* Root page of table to open */
47090   int wrFlag,                                 /* 1 to write. 0 read-only */
47091   struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
47092   BtCursor *pCur                              /* Write new cursor here */
47093 ){
47094   int rc;
47095   sqlite3BtreeEnter(p);
47096   rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
47097   sqlite3BtreeLeave(p);
47098   return rc;
47099 }
47100
47101 /*
47102 ** Return the size of a BtCursor object in bytes.
47103 **
47104 ** This interfaces is needed so that users of cursors can preallocate
47105 ** sufficient storage to hold a cursor.  The BtCursor object is opaque
47106 ** to users so they cannot do the sizeof() themselves - they must call
47107 ** this routine.
47108 */
47109 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
47110   return ROUND8(sizeof(BtCursor));
47111 }
47112
47113 /*
47114 ** Initialize memory that will be converted into a BtCursor object.
47115 **
47116 ** The simple approach here would be to memset() the entire object
47117 ** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
47118 ** do not need to be zeroed and they are large, so we can save a lot
47119 ** of run-time by skipping the initialization of those elements.
47120 */
47121 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
47122   memset(p, 0, offsetof(BtCursor, iPage));
47123 }
47124
47125 /*
47126 ** Set the cached rowid value of every cursor in the same database file
47127 ** as pCur and having the same root page number as pCur.  The value is
47128 ** set to iRowid.
47129 **
47130 ** Only positive rowid values are considered valid for this cache.
47131 ** The cache is initialized to zero, indicating an invalid cache.
47132 ** A btree will work fine with zero or negative rowids.  We just cannot
47133 ** cache zero or negative rowids, which means tables that use zero or
47134 ** negative rowids might run a little slower.  But in practice, zero
47135 ** or negative rowids are very uncommon so this should not be a problem.
47136 */
47137 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
47138   BtCursor *p;
47139   for(p=pCur->pBt->pCursor; p; p=p->pNext){
47140     if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
47141   }
47142   assert( pCur->cachedRowid==iRowid );
47143 }
47144
47145 /*
47146 ** Return the cached rowid for the given cursor.  A negative or zero
47147 ** return value indicates that the rowid cache is invalid and should be
47148 ** ignored.  If the rowid cache has never before been set, then a
47149 ** zero is returned.
47150 */
47151 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
47152   return pCur->cachedRowid;
47153 }
47154
47155 /*
47156 ** Close a cursor.  The read lock on the database file is released
47157 ** when the last cursor is closed.
47158 */
47159 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
47160   Btree *pBtree = pCur->pBtree;
47161   if( pBtree ){
47162     int i;
47163     BtShared *pBt = pCur->pBt;
47164     sqlite3BtreeEnter(pBtree);
47165     sqlite3BtreeClearCursor(pCur);
47166     if( pCur->pPrev ){
47167       pCur->pPrev->pNext = pCur->pNext;
47168     }else{
47169       pBt->pCursor = pCur->pNext;
47170     }
47171     if( pCur->pNext ){
47172       pCur->pNext->pPrev = pCur->pPrev;
47173     }
47174     for(i=0; i<=pCur->iPage; i++){
47175       releasePage(pCur->apPage[i]);
47176     }
47177     unlockBtreeIfUnused(pBt);
47178     invalidateOverflowCache(pCur);
47179     /* sqlite3_free(pCur); */
47180     sqlite3BtreeLeave(pBtree);
47181   }
47182   return SQLITE_OK;
47183 }
47184
47185 /*
47186 ** Make sure the BtCursor* given in the argument has a valid
47187 ** BtCursor.info structure.  If it is not already valid, call
47188 ** btreeParseCell() to fill it in.
47189 **
47190 ** BtCursor.info is a cache of the information in the current cell.
47191 ** Using this cache reduces the number of calls to btreeParseCell().
47192 **
47193 ** 2007-06-25:  There is a bug in some versions of MSVC that cause the
47194 ** compiler to crash when getCellInfo() is implemented as a macro.
47195 ** But there is a measureable speed advantage to using the macro on gcc
47196 ** (when less compiler optimizations like -Os or -O0 are used and the
47197 ** compiler is not doing agressive inlining.)  So we use a real function
47198 ** for MSVC and a macro for everything else.  Ticket #2457.
47199 */
47200 #ifndef NDEBUG
47201   static void assertCellInfo(BtCursor *pCur){
47202     CellInfo info;
47203     int iPage = pCur->iPage;
47204     memset(&info, 0, sizeof(info));
47205     btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
47206     assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
47207   }
47208 #else
47209   #define assertCellInfo(x)
47210 #endif
47211 #ifdef _MSC_VER
47212   /* Use a real function in MSVC to work around bugs in that compiler. */
47213   static void getCellInfo(BtCursor *pCur){
47214     if( pCur->info.nSize==0 ){
47215       int iPage = pCur->iPage;
47216       btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
47217       pCur->validNKey = 1;
47218     }else{
47219       assertCellInfo(pCur);
47220     }
47221   }
47222 #else /* if not _MSC_VER */
47223   /* Use a macro in all other compilers so that the function is inlined */
47224 #define getCellInfo(pCur)                                                      \
47225   if( pCur->info.nSize==0 ){                                                   \
47226     int iPage = pCur->iPage;                                                   \
47227     btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
47228     pCur->validNKey = 1;                                                       \
47229   }else{                                                                       \
47230     assertCellInfo(pCur);                                                      \
47231   }
47232 #endif /* _MSC_VER */
47233
47234 #ifndef NDEBUG  /* The next routine used only within assert() statements */
47235 /*
47236 ** Return true if the given BtCursor is valid.  A valid cursor is one
47237 ** that is currently pointing to a row in a (non-empty) table.
47238 ** This is a verification routine is used only within assert() statements.
47239 */
47240 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
47241   return pCur && pCur->eState==CURSOR_VALID;
47242 }
47243 #endif /* NDEBUG */
47244
47245 /*
47246 ** Set *pSize to the size of the buffer needed to hold the value of
47247 ** the key for the current entry.  If the cursor is not pointing
47248 ** to a valid entry, *pSize is set to 0. 
47249 **
47250 ** For a table with the INTKEY flag set, this routine returns the key
47251 ** itself, not the number of bytes in the key.
47252 **
47253 ** The caller must position the cursor prior to invoking this routine.
47254 ** 
47255 ** This routine cannot fail.  It always returns SQLITE_OK.  
47256 */
47257 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
47258   assert( cursorHoldsMutex(pCur) );
47259   assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
47260   if( pCur->eState!=CURSOR_VALID ){
47261     *pSize = 0;
47262   }else{
47263     getCellInfo(pCur);
47264     *pSize = pCur->info.nKey;
47265   }
47266   return SQLITE_OK;
47267 }
47268
47269 /*
47270 ** Set *pSize to the number of bytes of data in the entry the
47271 ** cursor currently points to.
47272 **
47273 ** The caller must guarantee that the cursor is pointing to a non-NULL
47274 ** valid entry.  In other words, the calling procedure must guarantee
47275 ** that the cursor has Cursor.eState==CURSOR_VALID.
47276 **
47277 ** Failure is not possible.  This function always returns SQLITE_OK.
47278 ** It might just as well be a procedure (returning void) but we continue
47279 ** to return an integer result code for historical reasons.
47280 */
47281 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
47282   assert( cursorHoldsMutex(pCur) );
47283   assert( pCur->eState==CURSOR_VALID );
47284   getCellInfo(pCur);
47285   *pSize = pCur->info.nData;
47286   return SQLITE_OK;
47287 }
47288
47289 /*
47290 ** Given the page number of an overflow page in the database (parameter
47291 ** ovfl), this function finds the page number of the next page in the 
47292 ** linked list of overflow pages. If possible, it uses the auto-vacuum
47293 ** pointer-map data instead of reading the content of page ovfl to do so. 
47294 **
47295 ** If an error occurs an SQLite error code is returned. Otherwise:
47296 **
47297 ** The page number of the next overflow page in the linked list is 
47298 ** written to *pPgnoNext. If page ovfl is the last page in its linked 
47299 ** list, *pPgnoNext is set to zero. 
47300 **
47301 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
47302 ** to page number pOvfl was obtained, then *ppPage is set to point to that
47303 ** reference. It is the responsibility of the caller to call releasePage()
47304 ** on *ppPage to free the reference. In no reference was obtained (because
47305 ** the pointer-map was used to obtain the value for *pPgnoNext), then
47306 ** *ppPage is set to zero.
47307 */
47308 static int getOverflowPage(
47309   BtShared *pBt,               /* The database file */
47310   Pgno ovfl,                   /* Current overflow page number */
47311   MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
47312   Pgno *pPgnoNext              /* OUT: Next overflow page number */
47313 ){
47314   Pgno next = 0;
47315   MemPage *pPage = 0;
47316   int rc = SQLITE_OK;
47317
47318   assert( sqlite3_mutex_held(pBt->mutex) );
47319   assert(pPgnoNext);
47320
47321 #ifndef SQLITE_OMIT_AUTOVACUUM
47322   /* Try to find the next page in the overflow list using the
47323   ** autovacuum pointer-map pages. Guess that the next page in 
47324   ** the overflow list is page number (ovfl+1). If that guess turns 
47325   ** out to be wrong, fall back to loading the data of page 
47326   ** number ovfl to determine the next page number.
47327   */
47328   if( pBt->autoVacuum ){
47329     Pgno pgno;
47330     Pgno iGuess = ovfl+1;
47331     u8 eType;
47332
47333     while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
47334       iGuess++;
47335     }
47336
47337     if( iGuess<=btreePagecount(pBt) ){
47338       rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
47339       if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
47340         next = iGuess;
47341         rc = SQLITE_DONE;
47342       }
47343     }
47344   }
47345 #endif
47346
47347   assert( next==0 || rc==SQLITE_DONE );
47348   if( rc==SQLITE_OK ){
47349     rc = btreeGetPage(pBt, ovfl, &pPage, 0);
47350     assert( rc==SQLITE_OK || pPage==0 );
47351     if( rc==SQLITE_OK ){
47352       next = get4byte(pPage->aData);
47353     }
47354   }
47355
47356   *pPgnoNext = next;
47357   if( ppPage ){
47358     *ppPage = pPage;
47359   }else{
47360     releasePage(pPage);
47361   }
47362   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
47363 }
47364
47365 /*
47366 ** Copy data from a buffer to a page, or from a page to a buffer.
47367 **
47368 ** pPayload is a pointer to data stored on database page pDbPage.
47369 ** If argument eOp is false, then nByte bytes of data are copied
47370 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
47371 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
47372 ** of data are copied from the buffer pBuf to pPayload.
47373 **
47374 ** SQLITE_OK is returned on success, otherwise an error code.
47375 */
47376 static int copyPayload(
47377   void *pPayload,           /* Pointer to page data */
47378   void *pBuf,               /* Pointer to buffer */
47379   int nByte,                /* Number of bytes to copy */
47380   int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
47381   DbPage *pDbPage           /* Page containing pPayload */
47382 ){
47383   if( eOp ){
47384     /* Copy data from buffer to page (a write operation) */
47385     int rc = sqlite3PagerWrite(pDbPage);
47386     if( rc!=SQLITE_OK ){
47387       return rc;
47388     }
47389     memcpy(pPayload, pBuf, nByte);
47390   }else{
47391     /* Copy data from page to buffer (a read operation) */
47392     memcpy(pBuf, pPayload, nByte);
47393   }
47394   return SQLITE_OK;
47395 }
47396
47397 /*
47398 ** This function is used to read or overwrite payload information
47399 ** for the entry that the pCur cursor is pointing to. If the eOp
47400 ** parameter is 0, this is a read operation (data copied into
47401 ** buffer pBuf). If it is non-zero, a write (data copied from
47402 ** buffer pBuf).
47403 **
47404 ** A total of "amt" bytes are read or written beginning at "offset".
47405 ** Data is read to or from the buffer pBuf.
47406 **
47407 ** The content being read or written might appear on the main page
47408 ** or be scattered out on multiple overflow pages.
47409 **
47410 ** If the BtCursor.isIncrblobHandle flag is set, and the current
47411 ** cursor entry uses one or more overflow pages, this function
47412 ** allocates space for and lazily popluates the overflow page-list 
47413 ** cache array (BtCursor.aOverflow). Subsequent calls use this
47414 ** cache to make seeking to the supplied offset more efficient.
47415 **
47416 ** Once an overflow page-list cache has been allocated, it may be
47417 ** invalidated if some other cursor writes to the same table, or if
47418 ** the cursor is moved to a different row. Additionally, in auto-vacuum
47419 ** mode, the following events may invalidate an overflow page-list cache.
47420 **
47421 **   * An incremental vacuum,
47422 **   * A commit in auto_vacuum="full" mode,
47423 **   * Creating a table (may require moving an overflow page).
47424 */
47425 static int accessPayload(
47426   BtCursor *pCur,      /* Cursor pointing to entry to read from */
47427   u32 offset,          /* Begin reading this far into payload */
47428   u32 amt,             /* Read this many bytes */
47429   unsigned char *pBuf, /* Write the bytes into this buffer */ 
47430   int eOp              /* zero to read. non-zero to write. */
47431 ){
47432   unsigned char *aPayload;
47433   int rc = SQLITE_OK;
47434   u32 nKey;
47435   int iIdx = 0;
47436   MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
47437   BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
47438
47439   assert( pPage );
47440   assert( pCur->eState==CURSOR_VALID );
47441   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
47442   assert( cursorHoldsMutex(pCur) );
47443
47444   getCellInfo(pCur);
47445   aPayload = pCur->info.pCell + pCur->info.nHeader;
47446   nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
47447
47448   if( NEVER(offset+amt > nKey+pCur->info.nData) 
47449    || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
47450   ){
47451     /* Trying to read or write past the end of the data is an error */
47452     return SQLITE_CORRUPT_BKPT;
47453   }
47454
47455   /* Check if data must be read/written to/from the btree page itself. */
47456   if( offset<pCur->info.nLocal ){
47457     int a = amt;
47458     if( a+offset>pCur->info.nLocal ){
47459       a = pCur->info.nLocal - offset;
47460     }
47461     rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
47462     offset = 0;
47463     pBuf += a;
47464     amt -= a;
47465   }else{
47466     offset -= pCur->info.nLocal;
47467   }
47468
47469   if( rc==SQLITE_OK && amt>0 ){
47470     const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
47471     Pgno nextPage;
47472
47473     nextPage = get4byte(&aPayload[pCur->info.nLocal]);
47474
47475 #ifndef SQLITE_OMIT_INCRBLOB
47476     /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
47477     ** has not been allocated, allocate it now. The array is sized at
47478     ** one entry for each overflow page in the overflow chain. The
47479     ** page number of the first overflow page is stored in aOverflow[0],
47480     ** etc. A value of 0 in the aOverflow[] array means "not yet known"
47481     ** (the cache is lazily populated).
47482     */
47483     if( pCur->isIncrblobHandle && !pCur->aOverflow ){
47484       int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
47485       pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
47486       /* nOvfl is always positive.  If it were zero, fetchPayload would have
47487       ** been used instead of this routine. */
47488       if( ALWAYS(nOvfl) && !pCur->aOverflow ){
47489         rc = SQLITE_NOMEM;
47490       }
47491     }
47492
47493     /* If the overflow page-list cache has been allocated and the
47494     ** entry for the first required overflow page is valid, skip
47495     ** directly to it.
47496     */
47497     if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
47498       iIdx = (offset/ovflSize);
47499       nextPage = pCur->aOverflow[iIdx];
47500       offset = (offset%ovflSize);
47501     }
47502 #endif
47503
47504     for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
47505
47506 #ifndef SQLITE_OMIT_INCRBLOB
47507       /* If required, populate the overflow page-list cache. */
47508       if( pCur->aOverflow ){
47509         assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
47510         pCur->aOverflow[iIdx] = nextPage;
47511       }
47512 #endif
47513
47514       if( offset>=ovflSize ){
47515         /* The only reason to read this page is to obtain the page
47516         ** number for the next page in the overflow chain. The page
47517         ** data is not required. So first try to lookup the overflow
47518         ** page-list cache, if any, then fall back to the getOverflowPage()
47519         ** function.
47520         */
47521 #ifndef SQLITE_OMIT_INCRBLOB
47522         if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
47523           nextPage = pCur->aOverflow[iIdx+1];
47524         } else 
47525 #endif
47526           rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
47527         offset -= ovflSize;
47528       }else{
47529         /* Need to read this page properly. It contains some of the
47530         ** range of data that is being read (eOp==0) or written (eOp!=0).
47531         */
47532         DbPage *pDbPage;
47533         int a = amt;
47534         rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
47535         if( rc==SQLITE_OK ){
47536           aPayload = sqlite3PagerGetData(pDbPage);
47537           nextPage = get4byte(aPayload);
47538           if( a + offset > ovflSize ){
47539             a = ovflSize - offset;
47540           }
47541           rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
47542           sqlite3PagerUnref(pDbPage);
47543           offset = 0;
47544           amt -= a;
47545           pBuf += a;
47546         }
47547       }
47548     }
47549   }
47550
47551   if( rc==SQLITE_OK && amt>0 ){
47552     return SQLITE_CORRUPT_BKPT;
47553   }
47554   return rc;
47555 }
47556
47557 /*
47558 ** Read part of the key associated with cursor pCur.  Exactly
47559 ** "amt" bytes will be transfered into pBuf[].  The transfer
47560 ** begins at "offset".
47561 **
47562 ** The caller must ensure that pCur is pointing to a valid row
47563 ** in the table.
47564 **
47565 ** Return SQLITE_OK on success or an error code if anything goes
47566 ** wrong.  An error is returned if "offset+amt" is larger than
47567 ** the available payload.
47568 */
47569 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
47570   assert( cursorHoldsMutex(pCur) );
47571   assert( pCur->eState==CURSOR_VALID );
47572   assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
47573   assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
47574   return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
47575 }
47576
47577 /*
47578 ** Read part of the data associated with cursor pCur.  Exactly
47579 ** "amt" bytes will be transfered into pBuf[].  The transfer
47580 ** begins at "offset".
47581 **
47582 ** Return SQLITE_OK on success or an error code if anything goes
47583 ** wrong.  An error is returned if "offset+amt" is larger than
47584 ** the available payload.
47585 */
47586 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
47587   int rc;
47588
47589 #ifndef SQLITE_OMIT_INCRBLOB
47590   if ( pCur->eState==CURSOR_INVALID ){
47591     return SQLITE_ABORT;
47592   }
47593 #endif
47594
47595   assert( cursorHoldsMutex(pCur) );
47596   rc = restoreCursorPosition(pCur);
47597   if( rc==SQLITE_OK ){
47598     assert( pCur->eState==CURSOR_VALID );
47599     assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
47600     assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
47601     rc = accessPayload(pCur, offset, amt, pBuf, 0);
47602   }
47603   return rc;
47604 }
47605
47606 /*
47607 ** Return a pointer to payload information from the entry that the 
47608 ** pCur cursor is pointing to.  The pointer is to the beginning of
47609 ** the key if skipKey==0 and it points to the beginning of data if
47610 ** skipKey==1.  The number of bytes of available key/data is written
47611 ** into *pAmt.  If *pAmt==0, then the value returned will not be
47612 ** a valid pointer.
47613 **
47614 ** This routine is an optimization.  It is common for the entire key
47615 ** and data to fit on the local page and for there to be no overflow
47616 ** pages.  When that is so, this routine can be used to access the
47617 ** key and data without making a copy.  If the key and/or data spills
47618 ** onto overflow pages, then accessPayload() must be used to reassemble
47619 ** the key/data and copy it into a preallocated buffer.
47620 **
47621 ** The pointer returned by this routine looks directly into the cached
47622 ** page of the database.  The data might change or move the next time
47623 ** any btree routine is called.
47624 */
47625 static const unsigned char *fetchPayload(
47626   BtCursor *pCur,      /* Cursor pointing to entry to read from */
47627   int *pAmt,           /* Write the number of available bytes here */
47628   int skipKey          /* read beginning at data if this is true */
47629 ){
47630   unsigned char *aPayload;
47631   MemPage *pPage;
47632   u32 nKey;
47633   u32 nLocal;
47634
47635   assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
47636   assert( pCur->eState==CURSOR_VALID );
47637   assert( cursorHoldsMutex(pCur) );
47638   pPage = pCur->apPage[pCur->iPage];
47639   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
47640   if( NEVER(pCur->info.nSize==0) ){
47641     btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
47642                    &pCur->info);
47643   }
47644   aPayload = pCur->info.pCell;
47645   aPayload += pCur->info.nHeader;
47646   if( pPage->intKey ){
47647     nKey = 0;
47648   }else{
47649     nKey = (int)pCur->info.nKey;
47650   }
47651   if( skipKey ){
47652     aPayload += nKey;
47653     nLocal = pCur->info.nLocal - nKey;
47654   }else{
47655     nLocal = pCur->info.nLocal;
47656     assert( nLocal<=nKey );
47657   }
47658   *pAmt = nLocal;
47659   return aPayload;
47660 }
47661
47662
47663 /*
47664 ** For the entry that cursor pCur is point to, return as
47665 ** many bytes of the key or data as are available on the local
47666 ** b-tree page.  Write the number of available bytes into *pAmt.
47667 **
47668 ** The pointer returned is ephemeral.  The key/data may move
47669 ** or be destroyed on the next call to any Btree routine,
47670 ** including calls from other threads against the same cache.
47671 ** Hence, a mutex on the BtShared should be held prior to calling
47672 ** this routine.
47673 **
47674 ** These routines is used to get quick access to key and data
47675 ** in the common case where no overflow pages are used.
47676 */
47677 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
47678   const void *p = 0;
47679   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
47680   assert( cursorHoldsMutex(pCur) );
47681   if( ALWAYS(pCur->eState==CURSOR_VALID) ){
47682     p = (const void*)fetchPayload(pCur, pAmt, 0);
47683   }
47684   return p;
47685 }
47686 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
47687   const void *p = 0;
47688   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
47689   assert( cursorHoldsMutex(pCur) );
47690   if( ALWAYS(pCur->eState==CURSOR_VALID) ){
47691     p = (const void*)fetchPayload(pCur, pAmt, 1);
47692   }
47693   return p;
47694 }
47695
47696
47697 /*
47698 ** Move the cursor down to a new child page.  The newPgno argument is the
47699 ** page number of the child page to move to.
47700 **
47701 ** This function returns SQLITE_CORRUPT if the page-header flags field of
47702 ** the new child page does not match the flags field of the parent (i.e.
47703 ** if an intkey page appears to be the parent of a non-intkey page, or
47704 ** vice-versa).
47705 */
47706 static int moveToChild(BtCursor *pCur, u32 newPgno){
47707   int rc;
47708   int i = pCur->iPage;
47709   MemPage *pNewPage;
47710   BtShared *pBt = pCur->pBt;
47711
47712   assert( cursorHoldsMutex(pCur) );
47713   assert( pCur->eState==CURSOR_VALID );
47714   assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
47715   if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
47716     return SQLITE_CORRUPT_BKPT;
47717   }
47718   rc = getAndInitPage(pBt, newPgno, &pNewPage);
47719   if( rc ) return rc;
47720   pCur->apPage[i+1] = pNewPage;
47721   pCur->aiIdx[i+1] = 0;
47722   pCur->iPage++;
47723
47724   pCur->info.nSize = 0;
47725   pCur->validNKey = 0;
47726   if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
47727     return SQLITE_CORRUPT_BKPT;
47728   }
47729   return SQLITE_OK;
47730 }
47731
47732 #ifndef NDEBUG
47733 /*
47734 ** Page pParent is an internal (non-leaf) tree page. This function 
47735 ** asserts that page number iChild is the left-child if the iIdx'th
47736 ** cell in page pParent. Or, if iIdx is equal to the total number of
47737 ** cells in pParent, that page number iChild is the right-child of
47738 ** the page.
47739 */
47740 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
47741   assert( iIdx<=pParent->nCell );
47742   if( iIdx==pParent->nCell ){
47743     assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
47744   }else{
47745     assert( get4byte(findCell(pParent, iIdx))==iChild );
47746   }
47747 }
47748 #else
47749 #  define assertParentIndex(x,y,z) 
47750 #endif
47751
47752 /*
47753 ** Move the cursor up to the parent page.
47754 **
47755 ** pCur->idx is set to the cell index that contains the pointer
47756 ** to the page we are coming from.  If we are coming from the
47757 ** right-most child page then pCur->idx is set to one more than
47758 ** the largest cell index.
47759 */
47760 static void moveToParent(BtCursor *pCur){
47761   assert( cursorHoldsMutex(pCur) );
47762   assert( pCur->eState==CURSOR_VALID );
47763   assert( pCur->iPage>0 );
47764   assert( pCur->apPage[pCur->iPage] );
47765   assertParentIndex(
47766     pCur->apPage[pCur->iPage-1], 
47767     pCur->aiIdx[pCur->iPage-1], 
47768     pCur->apPage[pCur->iPage]->pgno
47769   );
47770   releasePage(pCur->apPage[pCur->iPage]);
47771   pCur->iPage--;
47772   pCur->info.nSize = 0;
47773   pCur->validNKey = 0;
47774 }
47775
47776 /*
47777 ** Move the cursor to point to the root page of its b-tree structure.
47778 **
47779 ** If the table has a virtual root page, then the cursor is moved to point
47780 ** to the virtual root page instead of the actual root page. A table has a
47781 ** virtual root page when the actual root page contains no cells and a 
47782 ** single child page. This can only happen with the table rooted at page 1.
47783 **
47784 ** If the b-tree structure is empty, the cursor state is set to 
47785 ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
47786 ** cell located on the root (or virtual root) page and the cursor state
47787 ** is set to CURSOR_VALID.
47788 **
47789 ** If this function returns successfully, it may be assumed that the
47790 ** page-header flags indicate that the [virtual] root-page is the expected 
47791 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
47792 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
47793 ** indicating a table b-tree, or if the caller did specify a KeyInfo 
47794 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
47795 ** b-tree).
47796 */
47797 static int moveToRoot(BtCursor *pCur){
47798   MemPage *pRoot;
47799   int rc = SQLITE_OK;
47800   Btree *p = pCur->pBtree;
47801   BtShared *pBt = p->pBt;
47802
47803   assert( cursorHoldsMutex(pCur) );
47804   assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
47805   assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
47806   assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
47807   if( pCur->eState>=CURSOR_REQUIRESEEK ){
47808     if( pCur->eState==CURSOR_FAULT ){
47809       assert( pCur->skipNext!=SQLITE_OK );
47810       return pCur->skipNext;
47811     }
47812     sqlite3BtreeClearCursor(pCur);
47813   }
47814
47815   if( pCur->iPage>=0 ){
47816     int i;
47817     for(i=1; i<=pCur->iPage; i++){
47818       releasePage(pCur->apPage[i]);
47819     }
47820     pCur->iPage = 0;
47821   }else{
47822     rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
47823     if( rc!=SQLITE_OK ){
47824       pCur->eState = CURSOR_INVALID;
47825       return rc;
47826     }
47827     pCur->iPage = 0;
47828
47829     /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
47830     ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
47831     ** NULL, the caller expects a table b-tree. If this is not the case,
47832     ** return an SQLITE_CORRUPT error.  */
47833     assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );
47834     if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){
47835       return SQLITE_CORRUPT_BKPT;
47836     }
47837   }
47838
47839   /* Assert that the root page is of the correct type. This must be the
47840   ** case as the call to this function that loaded the root-page (either
47841   ** this call or a previous invocation) would have detected corruption 
47842   ** if the assumption were not true, and it is not possible for the flags 
47843   ** byte to have been modified while this cursor is holding a reference
47844   ** to the page.  */
47845   pRoot = pCur->apPage[0];
47846   assert( pRoot->pgno==pCur->pgnoRoot );
47847   assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );
47848
47849   pCur->aiIdx[0] = 0;
47850   pCur->info.nSize = 0;
47851   pCur->atLast = 0;
47852   pCur->validNKey = 0;
47853
47854   if( pRoot->nCell==0 && !pRoot->leaf ){
47855     Pgno subpage;
47856     if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
47857     subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
47858     pCur->eState = CURSOR_VALID;
47859     rc = moveToChild(pCur, subpage);
47860   }else{
47861     pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
47862   }
47863   return rc;
47864 }
47865
47866 /*
47867 ** Move the cursor down to the left-most leaf entry beneath the
47868 ** entry to which it is currently pointing.
47869 **
47870 ** The left-most leaf is the one with the smallest key - the first
47871 ** in ascending order.
47872 */
47873 static int moveToLeftmost(BtCursor *pCur){
47874   Pgno pgno;
47875   int rc = SQLITE_OK;
47876   MemPage *pPage;
47877
47878   assert( cursorHoldsMutex(pCur) );
47879   assert( pCur->eState==CURSOR_VALID );
47880   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
47881     assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
47882     pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
47883     rc = moveToChild(pCur, pgno);
47884   }
47885   return rc;
47886 }
47887
47888 /*
47889 ** Move the cursor down to the right-most leaf entry beneath the
47890 ** page to which it is currently pointing.  Notice the difference
47891 ** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
47892 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
47893 ** finds the right-most entry beneath the *page*.
47894 **
47895 ** The right-most entry is the one with the largest key - the last
47896 ** key in ascending order.
47897 */
47898 static int moveToRightmost(BtCursor *pCur){
47899   Pgno pgno;
47900   int rc = SQLITE_OK;
47901   MemPage *pPage = 0;
47902
47903   assert( cursorHoldsMutex(pCur) );
47904   assert( pCur->eState==CURSOR_VALID );
47905   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
47906     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
47907     pCur->aiIdx[pCur->iPage] = pPage->nCell;
47908     rc = moveToChild(pCur, pgno);
47909   }
47910   if( rc==SQLITE_OK ){
47911     pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
47912     pCur->info.nSize = 0;
47913     pCur->validNKey = 0;
47914   }
47915   return rc;
47916 }
47917
47918 /* Move the cursor to the first entry in the table.  Return SQLITE_OK
47919 ** on success.  Set *pRes to 0 if the cursor actually points to something
47920 ** or set *pRes to 1 if the table is empty.
47921 */
47922 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
47923   int rc;
47924
47925   assert( cursorHoldsMutex(pCur) );
47926   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
47927   rc = moveToRoot(pCur);
47928   if( rc==SQLITE_OK ){
47929     if( pCur->eState==CURSOR_INVALID ){
47930       assert( pCur->apPage[pCur->iPage]->nCell==0 );
47931       *pRes = 1;
47932     }else{
47933       assert( pCur->apPage[pCur->iPage]->nCell>0 );
47934       *pRes = 0;
47935       rc = moveToLeftmost(pCur);
47936     }
47937   }
47938   return rc;
47939 }
47940
47941 /* Move the cursor to the last entry in the table.  Return SQLITE_OK
47942 ** on success.  Set *pRes to 0 if the cursor actually points to something
47943 ** or set *pRes to 1 if the table is empty.
47944 */
47945 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
47946   int rc;
47947  
47948   assert( cursorHoldsMutex(pCur) );
47949   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
47950
47951   /* If the cursor already points to the last entry, this is a no-op. */
47952   if( CURSOR_VALID==pCur->eState && pCur->atLast ){
47953 #ifdef SQLITE_DEBUG
47954     /* This block serves to assert() that the cursor really does point 
47955     ** to the last entry in the b-tree. */
47956     int ii;
47957     for(ii=0; ii<pCur->iPage; ii++){
47958       assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
47959     }
47960     assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
47961     assert( pCur->apPage[pCur->iPage]->leaf );
47962 #endif
47963     return SQLITE_OK;
47964   }
47965
47966   rc = moveToRoot(pCur);
47967   if( rc==SQLITE_OK ){
47968     if( CURSOR_INVALID==pCur->eState ){
47969       assert( pCur->apPage[pCur->iPage]->nCell==0 );
47970       *pRes = 1;
47971     }else{
47972       assert( pCur->eState==CURSOR_VALID );
47973       *pRes = 0;
47974       rc = moveToRightmost(pCur);
47975       pCur->atLast = rc==SQLITE_OK ?1:0;
47976     }
47977   }
47978   return rc;
47979 }
47980
47981 /* Move the cursor so that it points to an entry near the key 
47982 ** specified by pIdxKey or intKey.   Return a success code.
47983 **
47984 ** For INTKEY tables, the intKey parameter is used.  pIdxKey 
47985 ** must be NULL.  For index tables, pIdxKey is used and intKey
47986 ** is ignored.
47987 **
47988 ** If an exact match is not found, then the cursor is always
47989 ** left pointing at a leaf page which would hold the entry if it
47990 ** were present.  The cursor might point to an entry that comes
47991 ** before or after the key.
47992 **
47993 ** An integer is written into *pRes which is the result of
47994 ** comparing the key with the entry to which the cursor is 
47995 ** pointing.  The meaning of the integer written into
47996 ** *pRes is as follows:
47997 **
47998 **     *pRes<0      The cursor is left pointing at an entry that
47999 **                  is smaller than intKey/pIdxKey or if the table is empty
48000 **                  and the cursor is therefore left point to nothing.
48001 **
48002 **     *pRes==0     The cursor is left pointing at an entry that
48003 **                  exactly matches intKey/pIdxKey.
48004 **
48005 **     *pRes>0      The cursor is left pointing at an entry that
48006 **                  is larger than intKey/pIdxKey.
48007 **
48008 */
48009 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
48010   BtCursor *pCur,          /* The cursor to be moved */
48011   UnpackedRecord *pIdxKey, /* Unpacked index key */
48012   i64 intKey,              /* The table key */
48013   int biasRight,           /* If true, bias the search to the high end */
48014   int *pRes                /* Write search results here */
48015 ){
48016   int rc;
48017
48018   assert( cursorHoldsMutex(pCur) );
48019   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
48020   assert( pRes );
48021   assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
48022
48023   /* If the cursor is already positioned at the point we are trying
48024   ** to move to, then just return without doing any work */
48025   if( pCur->eState==CURSOR_VALID && pCur->validNKey 
48026    && pCur->apPage[0]->intKey 
48027   ){
48028     if( pCur->info.nKey==intKey ){
48029       *pRes = 0;
48030       return SQLITE_OK;
48031     }
48032     if( pCur->atLast && pCur->info.nKey<intKey ){
48033       *pRes = -1;
48034       return SQLITE_OK;
48035     }
48036   }
48037
48038   rc = moveToRoot(pCur);
48039   if( rc ){
48040     return rc;
48041   }
48042   assert( pCur->apPage[pCur->iPage] );
48043   assert( pCur->apPage[pCur->iPage]->isInit );
48044   assert( pCur->apPage[pCur->iPage]->nCell>0 || pCur->eState==CURSOR_INVALID );
48045   if( pCur->eState==CURSOR_INVALID ){
48046     *pRes = -1;
48047     assert( pCur->apPage[pCur->iPage]->nCell==0 );
48048     return SQLITE_OK;
48049   }
48050   assert( pCur->apPage[0]->intKey || pIdxKey );
48051   for(;;){
48052     int lwr, upr;
48053     Pgno chldPg;
48054     MemPage *pPage = pCur->apPage[pCur->iPage];
48055     int c;
48056
48057     /* pPage->nCell must be greater than zero. If this is the root-page
48058     ** the cursor would have been INVALID above and this for(;;) loop
48059     ** not run. If this is not the root-page, then the moveToChild() routine
48060     ** would have already detected db corruption. Similarly, pPage must
48061     ** be the right kind (index or table) of b-tree page. Otherwise
48062     ** a moveToChild() or moveToRoot() call would have detected corruption.  */
48063     assert( pPage->nCell>0 );
48064     assert( pPage->intKey==(pIdxKey==0) );
48065     lwr = 0;
48066     upr = pPage->nCell-1;
48067     if( biasRight ){
48068       pCur->aiIdx[pCur->iPage] = (u16)upr;
48069     }else{
48070       pCur->aiIdx[pCur->iPage] = (u16)((upr+lwr)/2);
48071     }
48072     for(;;){
48073       int idx = pCur->aiIdx[pCur->iPage]; /* Index of current cell in pPage */
48074       u8 *pCell;                          /* Pointer to current cell in pPage */
48075
48076       pCur->info.nSize = 0;
48077       pCell = findCell(pPage, idx) + pPage->childPtrSize;
48078       if( pPage->intKey ){
48079         i64 nCellKey;
48080         if( pPage->hasData ){
48081           u32 dummy;
48082           pCell += getVarint32(pCell, dummy);
48083         }
48084         getVarint(pCell, (u64*)&nCellKey);
48085         if( nCellKey==intKey ){
48086           c = 0;
48087         }else if( nCellKey<intKey ){
48088           c = -1;
48089         }else{
48090           assert( nCellKey>intKey );
48091           c = +1;
48092         }
48093         pCur->validNKey = 1;
48094         pCur->info.nKey = nCellKey;
48095       }else{
48096         /* The maximum supported page-size is 32768 bytes. This means that
48097         ** the maximum number of record bytes stored on an index B-Tree
48098         ** page is at most 8198 bytes, which may be stored as a 2-byte
48099         ** varint. This information is used to attempt to avoid parsing 
48100         ** the entire cell by checking for the cases where the record is 
48101         ** stored entirely within the b-tree page by inspecting the first 
48102         ** 2 bytes of the cell.
48103         */
48104         int nCell = pCell[0];
48105         if( !(nCell & 0x80) && nCell<=pPage->maxLocal ){
48106           /* This branch runs if the record-size field of the cell is a
48107           ** single byte varint and the record fits entirely on the main
48108           ** b-tree page.  */
48109           c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
48110         }else if( !(pCell[1] & 0x80) 
48111           && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
48112         ){
48113           /* The record-size field is a 2 byte varint and the record 
48114           ** fits entirely on the main b-tree page.  */
48115           c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
48116         }else{
48117           /* The record flows over onto one or more overflow pages. In
48118           ** this case the whole cell needs to be parsed, a buffer allocated
48119           ** and accessPayload() used to retrieve the record into the
48120           ** buffer before VdbeRecordCompare() can be called. */
48121           void *pCellKey;
48122           u8 * const pCellBody = pCell - pPage->childPtrSize;
48123           btreeParseCellPtr(pPage, pCellBody, &pCur->info);
48124           nCell = (int)pCur->info.nKey;
48125           pCellKey = sqlite3Malloc( nCell );
48126           if( pCellKey==0 ){
48127             rc = SQLITE_NOMEM;
48128             goto moveto_finish;
48129           }
48130           rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
48131           if( rc ){
48132             sqlite3_free(pCellKey);
48133             goto moveto_finish;
48134           }
48135           c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
48136           sqlite3_free(pCellKey);
48137         }
48138       }
48139       if( c==0 ){
48140         if( pPage->intKey && !pPage->leaf ){
48141           lwr = idx;
48142           upr = lwr - 1;
48143           break;
48144         }else{
48145           *pRes = 0;
48146           rc = SQLITE_OK;
48147           goto moveto_finish;
48148         }
48149       }
48150       if( c<0 ){
48151         lwr = idx+1;
48152       }else{
48153         upr = idx-1;
48154       }
48155       if( lwr>upr ){
48156         break;
48157       }
48158       pCur->aiIdx[pCur->iPage] = (u16)((lwr+upr)/2);
48159     }
48160     assert( lwr==upr+1 );
48161     assert( pPage->isInit );
48162     if( pPage->leaf ){
48163       chldPg = 0;
48164     }else if( lwr>=pPage->nCell ){
48165       chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
48166     }else{
48167       chldPg = get4byte(findCell(pPage, lwr));
48168     }
48169     if( chldPg==0 ){
48170       assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
48171       *pRes = c;
48172       rc = SQLITE_OK;
48173       goto moveto_finish;
48174     }
48175     pCur->aiIdx[pCur->iPage] = (u16)lwr;
48176     pCur->info.nSize = 0;
48177     pCur->validNKey = 0;
48178     rc = moveToChild(pCur, chldPg);
48179     if( rc ) goto moveto_finish;
48180   }
48181 moveto_finish:
48182   return rc;
48183 }
48184
48185
48186 /*
48187 ** Return TRUE if the cursor is not pointing at an entry of the table.
48188 **
48189 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
48190 ** past the last entry in the table or sqlite3BtreePrev() moves past
48191 ** the first entry.  TRUE is also returned if the table is empty.
48192 */
48193 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
48194   /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
48195   ** have been deleted? This API will need to change to return an error code
48196   ** as well as the boolean result value.
48197   */
48198   return (CURSOR_VALID!=pCur->eState);
48199 }
48200
48201 /*
48202 ** Advance the cursor to the next entry in the database.  If
48203 ** successful then set *pRes=0.  If the cursor
48204 ** was already pointing to the last entry in the database before
48205 ** this routine was called, then set *pRes=1.
48206 */
48207 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
48208   int rc;
48209   int idx;
48210   MemPage *pPage;
48211
48212   assert( cursorHoldsMutex(pCur) );
48213   rc = restoreCursorPosition(pCur);
48214   if( rc!=SQLITE_OK ){
48215     return rc;
48216   }
48217   assert( pRes!=0 );
48218   if( CURSOR_INVALID==pCur->eState ){
48219     *pRes = 1;
48220     return SQLITE_OK;
48221   }
48222   if( pCur->skipNext>0 ){
48223     pCur->skipNext = 0;
48224     *pRes = 0;
48225     return SQLITE_OK;
48226   }
48227   pCur->skipNext = 0;
48228
48229   pPage = pCur->apPage[pCur->iPage];
48230   idx = ++pCur->aiIdx[pCur->iPage];
48231   assert( pPage->isInit );
48232   assert( idx<=pPage->nCell );
48233
48234   pCur->info.nSize = 0;
48235   pCur->validNKey = 0;
48236   if( idx>=pPage->nCell ){
48237     if( !pPage->leaf ){
48238       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
48239       if( rc ) return rc;
48240       rc = moveToLeftmost(pCur);
48241       *pRes = 0;
48242       return rc;
48243     }
48244     do{
48245       if( pCur->iPage==0 ){
48246         *pRes = 1;
48247         pCur->eState = CURSOR_INVALID;
48248         return SQLITE_OK;
48249       }
48250       moveToParent(pCur);
48251       pPage = pCur->apPage[pCur->iPage];
48252     }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
48253     *pRes = 0;
48254     if( pPage->intKey ){
48255       rc = sqlite3BtreeNext(pCur, pRes);
48256     }else{
48257       rc = SQLITE_OK;
48258     }
48259     return rc;
48260   }
48261   *pRes = 0;
48262   if( pPage->leaf ){
48263     return SQLITE_OK;
48264   }
48265   rc = moveToLeftmost(pCur);
48266   return rc;
48267 }
48268
48269
48270 /*
48271 ** Step the cursor to the back to the previous entry in the database.  If
48272 ** successful then set *pRes=0.  If the cursor
48273 ** was already pointing to the first entry in the database before
48274 ** this routine was called, then set *pRes=1.
48275 */
48276 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
48277   int rc;
48278   MemPage *pPage;
48279
48280   assert( cursorHoldsMutex(pCur) );
48281   rc = restoreCursorPosition(pCur);
48282   if( rc!=SQLITE_OK ){
48283     return rc;
48284   }
48285   pCur->atLast = 0;
48286   if( CURSOR_INVALID==pCur->eState ){
48287     *pRes = 1;
48288     return SQLITE_OK;
48289   }
48290   if( pCur->skipNext<0 ){
48291     pCur->skipNext = 0;
48292     *pRes = 0;
48293     return SQLITE_OK;
48294   }
48295   pCur->skipNext = 0;
48296
48297   pPage = pCur->apPage[pCur->iPage];
48298   assert( pPage->isInit );
48299   if( !pPage->leaf ){
48300     int idx = pCur->aiIdx[pCur->iPage];
48301     rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
48302     if( rc ){
48303       return rc;
48304     }
48305     rc = moveToRightmost(pCur);
48306   }else{
48307     while( pCur->aiIdx[pCur->iPage]==0 ){
48308       if( pCur->iPage==0 ){
48309         pCur->eState = CURSOR_INVALID;
48310         *pRes = 1;
48311         return SQLITE_OK;
48312       }
48313       moveToParent(pCur);
48314     }
48315     pCur->info.nSize = 0;
48316     pCur->validNKey = 0;
48317
48318     pCur->aiIdx[pCur->iPage]--;
48319     pPage = pCur->apPage[pCur->iPage];
48320     if( pPage->intKey && !pPage->leaf ){
48321       rc = sqlite3BtreePrevious(pCur, pRes);
48322     }else{
48323       rc = SQLITE_OK;
48324     }
48325   }
48326   *pRes = 0;
48327   return rc;
48328 }
48329
48330 /*
48331 ** Allocate a new page from the database file.
48332 **
48333 ** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
48334 ** has already been called on the new page.)  The new page has also
48335 ** been referenced and the calling routine is responsible for calling
48336 ** sqlite3PagerUnref() on the new page when it is done.
48337 **
48338 ** SQLITE_OK is returned on success.  Any other return value indicates
48339 ** an error.  *ppPage and *pPgno are undefined in the event of an error.
48340 ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
48341 **
48342 ** If the "nearby" parameter is not 0, then a (feeble) effort is made to 
48343 ** locate a page close to the page number "nearby".  This can be used in an
48344 ** attempt to keep related pages close to each other in the database file,
48345 ** which in turn can make database access faster.
48346 **
48347 ** If the "exact" parameter is not 0, and the page-number nearby exists 
48348 ** anywhere on the free-list, then it is guarenteed to be returned. This
48349 ** is only used by auto-vacuum databases when allocating a new table.
48350 */
48351 static int allocateBtreePage(
48352   BtShared *pBt, 
48353   MemPage **ppPage, 
48354   Pgno *pPgno, 
48355   Pgno nearby,
48356   u8 exact
48357 ){
48358   MemPage *pPage1;
48359   int rc;
48360   u32 n;     /* Number of pages on the freelist */
48361   u32 k;     /* Number of leaves on the trunk of the freelist */
48362   MemPage *pTrunk = 0;
48363   MemPage *pPrevTrunk = 0;
48364   Pgno mxPage;     /* Total size of the database file */
48365
48366   assert( sqlite3_mutex_held(pBt->mutex) );
48367   pPage1 = pBt->pPage1;
48368   mxPage = btreePagecount(pBt);
48369   n = get4byte(&pPage1->aData[36]);
48370   testcase( n==mxPage-1 );
48371   if( n>=mxPage ){
48372     return SQLITE_CORRUPT_BKPT;
48373   }
48374   if( n>0 ){
48375     /* There are pages on the freelist.  Reuse one of those pages. */
48376     Pgno iTrunk;
48377     u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
48378     
48379     /* If the 'exact' parameter was true and a query of the pointer-map
48380     ** shows that the page 'nearby' is somewhere on the free-list, then
48381     ** the entire-list will be searched for that page.
48382     */
48383 #ifndef SQLITE_OMIT_AUTOVACUUM
48384     if( exact && nearby<=mxPage ){
48385       u8 eType;
48386       assert( nearby>0 );
48387       assert( pBt->autoVacuum );
48388       rc = ptrmapGet(pBt, nearby, &eType, 0);
48389       if( rc ) return rc;
48390       if( eType==PTRMAP_FREEPAGE ){
48391         searchList = 1;
48392       }
48393       *pPgno = nearby;
48394     }
48395 #endif
48396
48397     /* Decrement the free-list count by 1. Set iTrunk to the index of the
48398     ** first free-list trunk page. iPrevTrunk is initially 1.
48399     */
48400     rc = sqlite3PagerWrite(pPage1->pDbPage);
48401     if( rc ) return rc;
48402     put4byte(&pPage1->aData[36], n-1);
48403
48404     /* The code within this loop is run only once if the 'searchList' variable
48405     ** is not true. Otherwise, it runs once for each trunk-page on the
48406     ** free-list until the page 'nearby' is located.
48407     */
48408     do {
48409       pPrevTrunk = pTrunk;
48410       if( pPrevTrunk ){
48411         iTrunk = get4byte(&pPrevTrunk->aData[0]);
48412       }else{
48413         iTrunk = get4byte(&pPage1->aData[32]);
48414       }
48415       testcase( iTrunk==mxPage );
48416       if( iTrunk>mxPage ){
48417         rc = SQLITE_CORRUPT_BKPT;
48418       }else{
48419         rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
48420       }
48421       if( rc ){
48422         pTrunk = 0;
48423         goto end_allocate_page;
48424       }
48425
48426       k = get4byte(&pTrunk->aData[4]);
48427       if( k==0 && !searchList ){
48428         /* The trunk has no leaves and the list is not being searched. 
48429         ** So extract the trunk page itself and use it as the newly 
48430         ** allocated page */
48431         assert( pPrevTrunk==0 );
48432         rc = sqlite3PagerWrite(pTrunk->pDbPage);
48433         if( rc ){
48434           goto end_allocate_page;
48435         }
48436         *pPgno = iTrunk;
48437         memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
48438         *ppPage = pTrunk;
48439         pTrunk = 0;
48440         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
48441       }else if( k>(u32)(pBt->usableSize/4 - 2) ){
48442         /* Value of k is out of range.  Database corruption */
48443         rc = SQLITE_CORRUPT_BKPT;
48444         goto end_allocate_page;
48445 #ifndef SQLITE_OMIT_AUTOVACUUM
48446       }else if( searchList && nearby==iTrunk ){
48447         /* The list is being searched and this trunk page is the page
48448         ** to allocate, regardless of whether it has leaves.
48449         */
48450         assert( *pPgno==iTrunk );
48451         *ppPage = pTrunk;
48452         searchList = 0;
48453         rc = sqlite3PagerWrite(pTrunk->pDbPage);
48454         if( rc ){
48455           goto end_allocate_page;
48456         }
48457         if( k==0 ){
48458           if( !pPrevTrunk ){
48459             memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
48460           }else{
48461             memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
48462           }
48463         }else{
48464           /* The trunk page is required by the caller but it contains 
48465           ** pointers to free-list leaves. The first leaf becomes a trunk
48466           ** page in this case.
48467           */
48468           MemPage *pNewTrunk;
48469           Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
48470           if( iNewTrunk>mxPage ){ 
48471             rc = SQLITE_CORRUPT_BKPT;
48472             goto end_allocate_page;
48473           }
48474           testcase( iNewTrunk==mxPage );
48475           rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
48476           if( rc!=SQLITE_OK ){
48477             goto end_allocate_page;
48478           }
48479           rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
48480           if( rc!=SQLITE_OK ){
48481             releasePage(pNewTrunk);
48482             goto end_allocate_page;
48483           }
48484           memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
48485           put4byte(&pNewTrunk->aData[4], k-1);
48486           memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
48487           releasePage(pNewTrunk);
48488           if( !pPrevTrunk ){
48489             assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
48490             put4byte(&pPage1->aData[32], iNewTrunk);
48491           }else{
48492             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
48493             if( rc ){
48494               goto end_allocate_page;
48495             }
48496             put4byte(&pPrevTrunk->aData[0], iNewTrunk);
48497           }
48498         }
48499         pTrunk = 0;
48500         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
48501 #endif
48502       }else if( k>0 ){
48503         /* Extract a leaf from the trunk */
48504         u32 closest;
48505         Pgno iPage;
48506         unsigned char *aData = pTrunk->aData;
48507         rc = sqlite3PagerWrite(pTrunk->pDbPage);
48508         if( rc ){
48509           goto end_allocate_page;
48510         }
48511         if( nearby>0 ){
48512           u32 i;
48513           int dist;
48514           closest = 0;
48515           dist = get4byte(&aData[8]) - nearby;
48516           if( dist<0 ) dist = -dist;
48517           for(i=1; i<k; i++){
48518             int d2 = get4byte(&aData[8+i*4]) - nearby;
48519             if( d2<0 ) d2 = -d2;
48520             if( d2<dist ){
48521               closest = i;
48522               dist = d2;
48523             }
48524           }
48525         }else{
48526           closest = 0;
48527         }
48528
48529         iPage = get4byte(&aData[8+closest*4]);
48530         testcase( iPage==mxPage );
48531         if( iPage>mxPage ){
48532           rc = SQLITE_CORRUPT_BKPT;
48533           goto end_allocate_page;
48534         }
48535         testcase( iPage==mxPage );
48536         if( !searchList || iPage==nearby ){
48537           int noContent;
48538           *pPgno = iPage;
48539           TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
48540                  ": %d more free pages\n",
48541                  *pPgno, closest+1, k, pTrunk->pgno, n-1));
48542           if( closest<k-1 ){
48543             memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
48544           }
48545           put4byte(&aData[4], k-1);
48546           assert( sqlite3PagerIswriteable(pTrunk->pDbPage) );
48547           noContent = !btreeGetHasContent(pBt, *pPgno);
48548           rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
48549           if( rc==SQLITE_OK ){
48550             rc = sqlite3PagerWrite((*ppPage)->pDbPage);
48551             if( rc!=SQLITE_OK ){
48552               releasePage(*ppPage);
48553             }
48554           }
48555           searchList = 0;
48556         }
48557       }
48558       releasePage(pPrevTrunk);
48559       pPrevTrunk = 0;
48560     }while( searchList );
48561   }else{
48562     /* There are no pages on the freelist, so create a new page at the
48563     ** end of the file */
48564     rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
48565     if( rc ) return rc;
48566     pBt->nPage++;
48567     if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
48568
48569 #ifndef SQLITE_OMIT_AUTOVACUUM
48570     if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
48571       /* If *pPgno refers to a pointer-map page, allocate two new pages
48572       ** at the end of the file instead of one. The first allocated page
48573       ** becomes a new pointer-map page, the second is used by the caller.
48574       */
48575       MemPage *pPg = 0;
48576       TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
48577       assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
48578       rc = btreeGetPage(pBt, pBt->nPage, &pPg, 1);
48579       if( rc==SQLITE_OK ){
48580         rc = sqlite3PagerWrite(pPg->pDbPage);
48581         releasePage(pPg);
48582       }
48583       if( rc ) return rc;
48584       pBt->nPage++;
48585       if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
48586     }
48587 #endif
48588     put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
48589     *pPgno = pBt->nPage;
48590
48591     assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
48592     rc = btreeGetPage(pBt, *pPgno, ppPage, 1);
48593     if( rc ) return rc;
48594     rc = sqlite3PagerWrite((*ppPage)->pDbPage);
48595     if( rc!=SQLITE_OK ){
48596       releasePage(*ppPage);
48597     }
48598     TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
48599   }
48600
48601   assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
48602
48603 end_allocate_page:
48604   releasePage(pTrunk);
48605   releasePage(pPrevTrunk);
48606   if( rc==SQLITE_OK ){
48607     if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
48608       releasePage(*ppPage);
48609       return SQLITE_CORRUPT_BKPT;
48610     }
48611     (*ppPage)->isInit = 0;
48612   }else{
48613     *ppPage = 0;
48614   }
48615   return rc;
48616 }
48617
48618 /*
48619 ** This function is used to add page iPage to the database file free-list. 
48620 ** It is assumed that the page is not already a part of the free-list.
48621 **
48622 ** The value passed as the second argument to this function is optional.
48623 ** If the caller happens to have a pointer to the MemPage object 
48624 ** corresponding to page iPage handy, it may pass it as the second value. 
48625 ** Otherwise, it may pass NULL.
48626 **
48627 ** If a pointer to a MemPage object is passed as the second argument,
48628 ** its reference count is not altered by this function.
48629 */
48630 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
48631   MemPage *pTrunk = 0;                /* Free-list trunk page */
48632   Pgno iTrunk = 0;                    /* Page number of free-list trunk page */ 
48633   MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
48634   MemPage *pPage;                     /* Page being freed. May be NULL. */
48635   int rc;                             /* Return Code */
48636   int nFree;                          /* Initial number of pages on free-list */
48637
48638   assert( sqlite3_mutex_held(pBt->mutex) );
48639   assert( iPage>1 );
48640   assert( !pMemPage || pMemPage->pgno==iPage );
48641
48642   if( pMemPage ){
48643     pPage = pMemPage;
48644     sqlite3PagerRef(pPage->pDbPage);
48645   }else{
48646     pPage = btreePageLookup(pBt, iPage);
48647   }
48648
48649   /* Increment the free page count on pPage1 */
48650   rc = sqlite3PagerWrite(pPage1->pDbPage);
48651   if( rc ) goto freepage_out;
48652   nFree = get4byte(&pPage1->aData[36]);
48653   put4byte(&pPage1->aData[36], nFree+1);
48654
48655   if( pBt->secureDelete ){
48656     /* If the secure_delete option is enabled, then
48657     ** always fully overwrite deleted information with zeros.
48658     */
48659     if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
48660      ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
48661     ){
48662       goto freepage_out;
48663     }
48664     memset(pPage->aData, 0, pPage->pBt->pageSize);
48665   }
48666
48667   /* If the database supports auto-vacuum, write an entry in the pointer-map
48668   ** to indicate that the page is free.
48669   */
48670   if( ISAUTOVACUUM ){
48671     ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
48672     if( rc ) goto freepage_out;
48673   }
48674
48675   /* Now manipulate the actual database free-list structure. There are two
48676   ** possibilities. If the free-list is currently empty, or if the first
48677   ** trunk page in the free-list is full, then this page will become a
48678   ** new free-list trunk page. Otherwise, it will become a leaf of the
48679   ** first trunk page in the current free-list. This block tests if it
48680   ** is possible to add the page as a new free-list leaf.
48681   */
48682   if( nFree!=0 ){
48683     u32 nLeaf;                /* Initial number of leaf cells on trunk page */
48684
48685     iTrunk = get4byte(&pPage1->aData[32]);
48686     rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
48687     if( rc!=SQLITE_OK ){
48688       goto freepage_out;
48689     }
48690
48691     nLeaf = get4byte(&pTrunk->aData[4]);
48692     assert( pBt->usableSize>32 );
48693     if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
48694       rc = SQLITE_CORRUPT_BKPT;
48695       goto freepage_out;
48696     }
48697     if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
48698       /* In this case there is room on the trunk page to insert the page
48699       ** being freed as a new leaf.
48700       **
48701       ** Note that the trunk page is not really full until it contains
48702       ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
48703       ** coded.  But due to a coding error in versions of SQLite prior to
48704       ** 3.6.0, databases with freelist trunk pages holding more than
48705       ** usableSize/4 - 8 entries will be reported as corrupt.  In order
48706       ** to maintain backwards compatibility with older versions of SQLite,
48707       ** we will continue to restrict the number of entries to usableSize/4 - 8
48708       ** for now.  At some point in the future (once everyone has upgraded
48709       ** to 3.6.0 or later) we should consider fixing the conditional above
48710       ** to read "usableSize/4-2" instead of "usableSize/4-8".
48711       */
48712       rc = sqlite3PagerWrite(pTrunk->pDbPage);
48713       if( rc==SQLITE_OK ){
48714         put4byte(&pTrunk->aData[4], nLeaf+1);
48715         put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
48716         if( pPage && !pBt->secureDelete ){
48717           sqlite3PagerDontWrite(pPage->pDbPage);
48718         }
48719         rc = btreeSetHasContent(pBt, iPage);
48720       }
48721       TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
48722       goto freepage_out;
48723     }
48724   }
48725
48726   /* If control flows to this point, then it was not possible to add the
48727   ** the page being freed as a leaf page of the first trunk in the free-list.
48728   ** Possibly because the free-list is empty, or possibly because the 
48729   ** first trunk in the free-list is full. Either way, the page being freed
48730   ** will become the new first trunk page in the free-list.
48731   */
48732   if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
48733     goto freepage_out;
48734   }
48735   rc = sqlite3PagerWrite(pPage->pDbPage);
48736   if( rc!=SQLITE_OK ){
48737     goto freepage_out;
48738   }
48739   put4byte(pPage->aData, iTrunk);
48740   put4byte(&pPage->aData[4], 0);
48741   put4byte(&pPage1->aData[32], iPage);
48742   TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
48743
48744 freepage_out:
48745   if( pPage ){
48746     pPage->isInit = 0;
48747   }
48748   releasePage(pPage);
48749   releasePage(pTrunk);
48750   return rc;
48751 }
48752 static void freePage(MemPage *pPage, int *pRC){
48753   if( (*pRC)==SQLITE_OK ){
48754     *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
48755   }
48756 }
48757
48758 /*
48759 ** Free any overflow pages associated with the given Cell.
48760 */
48761 static int clearCell(MemPage *pPage, unsigned char *pCell){
48762   BtShared *pBt = pPage->pBt;
48763   CellInfo info;
48764   Pgno ovflPgno;
48765   int rc;
48766   int nOvfl;
48767   u16 ovflPageSize;
48768
48769   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48770   btreeParseCellPtr(pPage, pCell, &info);
48771   if( info.iOverflow==0 ){
48772     return SQLITE_OK;  /* No overflow pages. Return without doing anything */
48773   }
48774   ovflPgno = get4byte(&pCell[info.iOverflow]);
48775   assert( pBt->usableSize > 4 );
48776   ovflPageSize = pBt->usableSize - 4;
48777   nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
48778   assert( ovflPgno==0 || nOvfl>0 );
48779   while( nOvfl-- ){
48780     Pgno iNext = 0;
48781     MemPage *pOvfl = 0;
48782     if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
48783       /* 0 is not a legal page number and page 1 cannot be an 
48784       ** overflow page. Therefore if ovflPgno<2 or past the end of the 
48785       ** file the database must be corrupt. */
48786       return SQLITE_CORRUPT_BKPT;
48787     }
48788     if( nOvfl ){
48789       rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
48790       if( rc ) return rc;
48791     }
48792
48793     if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
48794      && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
48795     ){
48796       /* There is no reason any cursor should have an outstanding reference 
48797       ** to an overflow page belonging to a cell that is being deleted/updated.
48798       ** So if there exists more than one reference to this page, then it 
48799       ** must not really be an overflow page and the database must be corrupt. 
48800       ** It is helpful to detect this before calling freePage2(), as 
48801       ** freePage2() may zero the page contents if secure-delete mode is
48802       ** enabled. If this 'overflow' page happens to be a page that the
48803       ** caller is iterating through or using in some other way, this
48804       ** can be problematic.
48805       */
48806       rc = SQLITE_CORRUPT_BKPT;
48807     }else{
48808       rc = freePage2(pBt, pOvfl, ovflPgno);
48809     }
48810
48811     if( pOvfl ){
48812       sqlite3PagerUnref(pOvfl->pDbPage);
48813     }
48814     if( rc ) return rc;
48815     ovflPgno = iNext;
48816   }
48817   return SQLITE_OK;
48818 }
48819
48820 /*
48821 ** Create the byte sequence used to represent a cell on page pPage
48822 ** and write that byte sequence into pCell[].  Overflow pages are
48823 ** allocated and filled in as necessary.  The calling procedure
48824 ** is responsible for making sure sufficient space has been allocated
48825 ** for pCell[].
48826 **
48827 ** Note that pCell does not necessary need to point to the pPage->aData
48828 ** area.  pCell might point to some temporary storage.  The cell will
48829 ** be constructed in this temporary area then copied into pPage->aData
48830 ** later.
48831 */
48832 static int fillInCell(
48833   MemPage *pPage,                /* The page that contains the cell */
48834   unsigned char *pCell,          /* Complete text of the cell */
48835   const void *pKey, i64 nKey,    /* The key */
48836   const void *pData,int nData,   /* The data */
48837   int nZero,                     /* Extra zero bytes to append to pData */
48838   int *pnSize                    /* Write cell size here */
48839 ){
48840   int nPayload;
48841   const u8 *pSrc;
48842   int nSrc, n, rc;
48843   int spaceLeft;
48844   MemPage *pOvfl = 0;
48845   MemPage *pToRelease = 0;
48846   unsigned char *pPrior;
48847   unsigned char *pPayload;
48848   BtShared *pBt = pPage->pBt;
48849   Pgno pgnoOvfl = 0;
48850   int nHeader;
48851   CellInfo info;
48852
48853   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48854
48855   /* pPage is not necessarily writeable since pCell might be auxiliary
48856   ** buffer space that is separate from the pPage buffer area */
48857   assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
48858             || sqlite3PagerIswriteable(pPage->pDbPage) );
48859
48860   /* Fill in the header. */
48861   nHeader = 0;
48862   if( !pPage->leaf ){
48863     nHeader += 4;
48864   }
48865   if( pPage->hasData ){
48866     nHeader += putVarint(&pCell[nHeader], nData+nZero);
48867   }else{
48868     nData = nZero = 0;
48869   }
48870   nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
48871   btreeParseCellPtr(pPage, pCell, &info);
48872   assert( info.nHeader==nHeader );
48873   assert( info.nKey==nKey );
48874   assert( info.nData==(u32)(nData+nZero) );
48875   
48876   /* Fill in the payload */
48877   nPayload = nData + nZero;
48878   if( pPage->intKey ){
48879     pSrc = pData;
48880     nSrc = nData;
48881     nData = 0;
48882   }else{ 
48883     if( NEVER(nKey>0x7fffffff || pKey==0) ){
48884       return SQLITE_CORRUPT_BKPT;
48885     }
48886     nPayload += (int)nKey;
48887     pSrc = pKey;
48888     nSrc = (int)nKey;
48889   }
48890   *pnSize = info.nSize;
48891   spaceLeft = info.nLocal;
48892   pPayload = &pCell[nHeader];
48893   pPrior = &pCell[info.iOverflow];
48894
48895   while( nPayload>0 ){
48896     if( spaceLeft==0 ){
48897 #ifndef SQLITE_OMIT_AUTOVACUUM
48898       Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
48899       if( pBt->autoVacuum ){
48900         do{
48901           pgnoOvfl++;
48902         } while( 
48903           PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt) 
48904         );
48905       }
48906 #endif
48907       rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
48908 #ifndef SQLITE_OMIT_AUTOVACUUM
48909       /* If the database supports auto-vacuum, and the second or subsequent
48910       ** overflow page is being allocated, add an entry to the pointer-map
48911       ** for that page now. 
48912       **
48913       ** If this is the first overflow page, then write a partial entry 
48914       ** to the pointer-map. If we write nothing to this pointer-map slot,
48915       ** then the optimistic overflow chain processing in clearCell()
48916       ** may misinterpret the uninitialised values and delete the
48917       ** wrong pages from the database.
48918       */
48919       if( pBt->autoVacuum && rc==SQLITE_OK ){
48920         u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
48921         ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
48922         if( rc ){
48923           releasePage(pOvfl);
48924         }
48925       }
48926 #endif
48927       if( rc ){
48928         releasePage(pToRelease);
48929         return rc;
48930       }
48931
48932       /* If pToRelease is not zero than pPrior points into the data area
48933       ** of pToRelease.  Make sure pToRelease is still writeable. */
48934       assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
48935
48936       /* If pPrior is part of the data area of pPage, then make sure pPage
48937       ** is still writeable */
48938       assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
48939             || sqlite3PagerIswriteable(pPage->pDbPage) );
48940
48941       put4byte(pPrior, pgnoOvfl);
48942       releasePage(pToRelease);
48943       pToRelease = pOvfl;
48944       pPrior = pOvfl->aData;
48945       put4byte(pPrior, 0);
48946       pPayload = &pOvfl->aData[4];
48947       spaceLeft = pBt->usableSize - 4;
48948     }
48949     n = nPayload;
48950     if( n>spaceLeft ) n = spaceLeft;
48951
48952     /* If pToRelease is not zero than pPayload points into the data area
48953     ** of pToRelease.  Make sure pToRelease is still writeable. */
48954     assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
48955
48956     /* If pPayload is part of the data area of pPage, then make sure pPage
48957     ** is still writeable */
48958     assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
48959             || sqlite3PagerIswriteable(pPage->pDbPage) );
48960
48961     if( nSrc>0 ){
48962       if( n>nSrc ) n = nSrc;
48963       assert( pSrc );
48964       memcpy(pPayload, pSrc, n);
48965     }else{
48966       memset(pPayload, 0, n);
48967     }
48968     nPayload -= n;
48969     pPayload += n;
48970     pSrc += n;
48971     nSrc -= n;
48972     spaceLeft -= n;
48973     if( nSrc==0 ){
48974       nSrc = nData;
48975       pSrc = pData;
48976     }
48977   }
48978   releasePage(pToRelease);
48979   return SQLITE_OK;
48980 }
48981
48982 /*
48983 ** Remove the i-th cell from pPage.  This routine effects pPage only.
48984 ** The cell content is not freed or deallocated.  It is assumed that
48985 ** the cell content has been copied someplace else.  This routine just
48986 ** removes the reference to the cell from pPage.
48987 **
48988 ** "sz" must be the number of bytes in the cell.
48989 */
48990 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
48991   int i;          /* Loop counter */
48992   int pc;         /* Offset to cell content of cell being deleted */
48993   u8 *data;       /* pPage->aData */
48994   u8 *ptr;        /* Used to move bytes around within data[] */
48995   int rc;         /* The return code */
48996   int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
48997
48998   if( *pRC ) return;
48999
49000   assert( idx>=0 && idx<pPage->nCell );
49001   assert( sz==cellSize(pPage, idx) );
49002   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
49003   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49004   data = pPage->aData;
49005   ptr = &data[pPage->cellOffset + 2*idx];
49006   pc = get2byte(ptr);
49007   hdr = pPage->hdrOffset;
49008   testcase( pc==get2byte(&data[hdr+5]) );
49009   testcase( pc+sz==pPage->pBt->usableSize );
49010   if( pc < get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
49011     *pRC = SQLITE_CORRUPT_BKPT;
49012     return;
49013   }
49014   rc = freeSpace(pPage, pc, sz);
49015   if( rc ){
49016     *pRC = rc;
49017     return;
49018   }
49019   for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
49020     ptr[0] = ptr[2];
49021     ptr[1] = ptr[3];
49022   }
49023   pPage->nCell--;
49024   put2byte(&data[hdr+3], pPage->nCell);
49025   pPage->nFree += 2;
49026 }
49027
49028 /*
49029 ** Insert a new cell on pPage at cell index "i".  pCell points to the
49030 ** content of the cell.
49031 **
49032 ** If the cell content will fit on the page, then put it there.  If it
49033 ** will not fit, then make a copy of the cell content into pTemp if
49034 ** pTemp is not null.  Regardless of pTemp, allocate a new entry
49035 ** in pPage->aOvfl[] and make it point to the cell content (either
49036 ** in pTemp or the original pCell) and also record its index. 
49037 ** Allocating a new entry in pPage->aCell[] implies that 
49038 ** pPage->nOverflow is incremented.
49039 **
49040 ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
49041 ** cell. The caller will overwrite them after this function returns. If
49042 ** nSkip is non-zero, then pCell may not point to an invalid memory location 
49043 ** (but pCell+nSkip is always valid).
49044 */
49045 static void insertCell(
49046   MemPage *pPage,   /* Page into which we are copying */
49047   int i,            /* New cell becomes the i-th cell of the page */
49048   u8 *pCell,        /* Content of the new cell */
49049   int sz,           /* Bytes of content in pCell */
49050   u8 *pTemp,        /* Temp storage space for pCell, if needed */
49051   Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
49052   int *pRC          /* Read and write return code from here */
49053 ){
49054   int idx = 0;      /* Where to write new cell content in data[] */
49055   int j;            /* Loop counter */
49056   int end;          /* First byte past the last cell pointer in data[] */
49057   int ins;          /* Index in data[] where new cell pointer is inserted */
49058   int cellOffset;   /* Address of first cell pointer in data[] */
49059   u8 *data;         /* The content of the whole page */
49060   u8 *ptr;          /* Used for moving information around in data[] */
49061
49062   int nSkip = (iChild ? 4 : 0);
49063
49064   if( *pRC ) return;
49065
49066   assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
49067   assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=5460 );
49068   assert( pPage->nOverflow<=ArraySize(pPage->aOvfl) );
49069   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49070   /* The cell should normally be sized correctly.  However, when moving a
49071   ** malformed cell from a leaf page to an interior page, if the cell size
49072   ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
49073   ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
49074   ** the term after the || in the following assert(). */
49075   assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
49076   if( pPage->nOverflow || sz+2>pPage->nFree ){
49077     if( pTemp ){
49078       memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
49079       pCell = pTemp;
49080     }
49081     if( iChild ){
49082       put4byte(pCell, iChild);
49083     }
49084     j = pPage->nOverflow++;
49085     assert( j<(int)(sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0])) );
49086     pPage->aOvfl[j].pCell = pCell;
49087     pPage->aOvfl[j].idx = (u16)i;
49088   }else{
49089     int rc = sqlite3PagerWrite(pPage->pDbPage);
49090     if( rc!=SQLITE_OK ){
49091       *pRC = rc;
49092       return;
49093     }
49094     assert( sqlite3PagerIswriteable(pPage->pDbPage) );
49095     data = pPage->aData;
49096     cellOffset = pPage->cellOffset;
49097     end = cellOffset + 2*pPage->nCell;
49098     ins = cellOffset + 2*i;
49099     rc = allocateSpace(pPage, sz, &idx);
49100     if( rc ){ *pRC = rc; return; }
49101     /* The allocateSpace() routine guarantees the following two properties
49102     ** if it returns success */
49103     assert( idx >= end+2 );
49104     assert( idx+sz <= pPage->pBt->usableSize );
49105     pPage->nCell++;
49106     pPage->nFree -= (u16)(2 + sz);
49107     memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
49108     if( iChild ){
49109       put4byte(&data[idx], iChild);
49110     }
49111     for(j=end, ptr=&data[j]; j>ins; j-=2, ptr-=2){
49112       ptr[0] = ptr[-2];
49113       ptr[1] = ptr[-1];
49114     }
49115     put2byte(&data[ins], idx);
49116     put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
49117 #ifndef SQLITE_OMIT_AUTOVACUUM
49118     if( pPage->pBt->autoVacuum ){
49119       /* The cell may contain a pointer to an overflow page. If so, write
49120       ** the entry for the overflow page into the pointer map.
49121       */
49122       ptrmapPutOvflPtr(pPage, pCell, pRC);
49123     }
49124 #endif
49125   }
49126 }
49127
49128 /*
49129 ** Add a list of cells to a page.  The page should be initially empty.
49130 ** The cells are guaranteed to fit on the page.
49131 */
49132 static void assemblePage(
49133   MemPage *pPage,   /* The page to be assemblied */
49134   int nCell,        /* The number of cells to add to this page */
49135   u8 **apCell,      /* Pointers to cell bodies */
49136   u16 *aSize        /* Sizes of the cells */
49137 ){
49138   int i;            /* Loop counter */
49139   u8 *pCellptr;     /* Address of next cell pointer */
49140   int cellbody;     /* Address of next cell body */
49141   u8 * const data = pPage->aData;             /* Pointer to data for pPage */
49142   const int hdr = pPage->hdrOffset;           /* Offset of header on pPage */
49143   const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
49144
49145   assert( pPage->nOverflow==0 );
49146   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49147   assert( nCell>=0 && nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=5460 );
49148   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
49149
49150   /* Check that the page has just been zeroed by zeroPage() */
49151   assert( pPage->nCell==0 );
49152   assert( get2byte(&data[hdr+5])==nUsable );
49153
49154   pCellptr = &data[pPage->cellOffset + nCell*2];
49155   cellbody = nUsable;
49156   for(i=nCell-1; i>=0; i--){
49157     pCellptr -= 2;
49158     cellbody -= aSize[i];
49159     put2byte(pCellptr, cellbody);
49160     memcpy(&data[cellbody], apCell[i], aSize[i]);
49161   }
49162   put2byte(&data[hdr+3], nCell);
49163   put2byte(&data[hdr+5], cellbody);
49164   pPage->nFree -= (nCell*2 + nUsable - cellbody);
49165   pPage->nCell = (u16)nCell;
49166 }
49167
49168 /*
49169 ** The following parameters determine how many adjacent pages get involved
49170 ** in a balancing operation.  NN is the number of neighbors on either side
49171 ** of the page that participate in the balancing operation.  NB is the
49172 ** total number of pages that participate, including the target page and
49173 ** NN neighbors on either side.
49174 **
49175 ** The minimum value of NN is 1 (of course).  Increasing NN above 1
49176 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
49177 ** in exchange for a larger degradation in INSERT and UPDATE performance.
49178 ** The value of NN appears to give the best results overall.
49179 */
49180 #define NN 1             /* Number of neighbors on either side of pPage */
49181 #define NB (NN*2+1)      /* Total pages involved in the balance */
49182
49183
49184 #ifndef SQLITE_OMIT_QUICKBALANCE
49185 /*
49186 ** This version of balance() handles the common special case where
49187 ** a new entry is being inserted on the extreme right-end of the
49188 ** tree, in other words, when the new entry will become the largest
49189 ** entry in the tree.
49190 **
49191 ** Instead of trying to balance the 3 right-most leaf pages, just add
49192 ** a new page to the right-hand side and put the one new entry in
49193 ** that page.  This leaves the right side of the tree somewhat
49194 ** unbalanced.  But odds are that we will be inserting new entries
49195 ** at the end soon afterwards so the nearly empty page will quickly
49196 ** fill up.  On average.
49197 **
49198 ** pPage is the leaf page which is the right-most page in the tree.
49199 ** pParent is its parent.  pPage must have a single overflow entry
49200 ** which is also the right-most entry on the page.
49201 **
49202 ** The pSpace buffer is used to store a temporary copy of the divider
49203 ** cell that will be inserted into pParent. Such a cell consists of a 4
49204 ** byte page number followed by a variable length integer. In other
49205 ** words, at most 13 bytes. Hence the pSpace buffer must be at
49206 ** least 13 bytes in size.
49207 */
49208 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
49209   BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
49210   MemPage *pNew;                       /* Newly allocated page */
49211   int rc;                              /* Return Code */
49212   Pgno pgnoNew;                        /* Page number of pNew */
49213
49214   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49215   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
49216   assert( pPage->nOverflow==1 );
49217
49218   if( pPage->nCell<=0 ) return SQLITE_CORRUPT_BKPT;
49219
49220   /* Allocate a new page. This page will become the right-sibling of 
49221   ** pPage. Make the parent page writable, so that the new divider cell
49222   ** may be inserted. If both these operations are successful, proceed.
49223   */
49224   rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
49225
49226   if( rc==SQLITE_OK ){
49227
49228     u8 *pOut = &pSpace[4];
49229     u8 *pCell = pPage->aOvfl[0].pCell;
49230     u16 szCell = cellSizePtr(pPage, pCell);
49231     u8 *pStop;
49232
49233     assert( sqlite3PagerIswriteable(pNew->pDbPage) );
49234     assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
49235     zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
49236     assemblePage(pNew, 1, &pCell, &szCell);
49237
49238     /* If this is an auto-vacuum database, update the pointer map
49239     ** with entries for the new page, and any pointer from the 
49240     ** cell on the page to an overflow page. If either of these
49241     ** operations fails, the return code is set, but the contents
49242     ** of the parent page are still manipulated by thh code below.
49243     ** That is Ok, at this point the parent page is guaranteed to
49244     ** be marked as dirty. Returning an error code will cause a
49245     ** rollback, undoing any changes made to the parent page.
49246     */
49247     if( ISAUTOVACUUM ){
49248       ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
49249       if( szCell>pNew->minLocal ){
49250         ptrmapPutOvflPtr(pNew, pCell, &rc);
49251       }
49252     }
49253   
49254     /* Create a divider cell to insert into pParent. The divider cell
49255     ** consists of a 4-byte page number (the page number of pPage) and
49256     ** a variable length key value (which must be the same value as the
49257     ** largest key on pPage).
49258     **
49259     ** To find the largest key value on pPage, first find the right-most 
49260     ** cell on pPage. The first two fields of this cell are the 
49261     ** record-length (a variable length integer at most 32-bits in size)
49262     ** and the key value (a variable length integer, may have any value).
49263     ** The first of the while(...) loops below skips over the record-length
49264     ** field. The second while(...) loop copies the key value from the
49265     ** cell on pPage into the pSpace buffer.
49266     */
49267     pCell = findCell(pPage, pPage->nCell-1);
49268     pStop = &pCell[9];
49269     while( (*(pCell++)&0x80) && pCell<pStop );
49270     pStop = &pCell[9];
49271     while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
49272
49273     /* Insert the new divider cell into pParent. */
49274     insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
49275                0, pPage->pgno, &rc);
49276
49277     /* Set the right-child pointer of pParent to point to the new page. */
49278     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
49279   
49280     /* Release the reference to the new page. */
49281     releasePage(pNew);
49282   }
49283
49284   return rc;
49285 }
49286 #endif /* SQLITE_OMIT_QUICKBALANCE */
49287
49288 #if 0
49289 /*
49290 ** This function does not contribute anything to the operation of SQLite.
49291 ** it is sometimes activated temporarily while debugging code responsible 
49292 ** for setting pointer-map entries.
49293 */
49294 static int ptrmapCheckPages(MemPage **apPage, int nPage){
49295   int i, j;
49296   for(i=0; i<nPage; i++){
49297     Pgno n;
49298     u8 e;
49299     MemPage *pPage = apPage[i];
49300     BtShared *pBt = pPage->pBt;
49301     assert( pPage->isInit );
49302
49303     for(j=0; j<pPage->nCell; j++){
49304       CellInfo info;
49305       u8 *z;
49306      
49307       z = findCell(pPage, j);
49308       btreeParseCellPtr(pPage, z, &info);
49309       if( info.iOverflow ){
49310         Pgno ovfl = get4byte(&z[info.iOverflow]);
49311         ptrmapGet(pBt, ovfl, &e, &n);
49312         assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
49313       }
49314       if( !pPage->leaf ){
49315         Pgno child = get4byte(z);
49316         ptrmapGet(pBt, child, &e, &n);
49317         assert( n==pPage->pgno && e==PTRMAP_BTREE );
49318       }
49319     }
49320     if( !pPage->leaf ){
49321       Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
49322       ptrmapGet(pBt, child, &e, &n);
49323       assert( n==pPage->pgno && e==PTRMAP_BTREE );
49324     }
49325   }
49326   return 1;
49327 }
49328 #endif
49329
49330 /*
49331 ** This function is used to copy the contents of the b-tree node stored 
49332 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
49333 ** the pointer-map entries for each child page are updated so that the
49334 ** parent page stored in the pointer map is page pTo. If pFrom contained
49335 ** any cells with overflow page pointers, then the corresponding pointer
49336 ** map entries are also updated so that the parent page is page pTo.
49337 **
49338 ** If pFrom is currently carrying any overflow cells (entries in the
49339 ** MemPage.aOvfl[] array), they are not copied to pTo. 
49340 **
49341 ** Before returning, page pTo is reinitialized using btreeInitPage().
49342 **
49343 ** The performance of this function is not critical. It is only used by 
49344 ** the balance_shallower() and balance_deeper() procedures, neither of
49345 ** which are called often under normal circumstances.
49346 */
49347 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
49348   if( (*pRC)==SQLITE_OK ){
49349     BtShared * const pBt = pFrom->pBt;
49350     u8 * const aFrom = pFrom->aData;
49351     u8 * const aTo = pTo->aData;
49352     int const iFromHdr = pFrom->hdrOffset;
49353     int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
49354     int rc;
49355     int iData;
49356   
49357   
49358     assert( pFrom->isInit );
49359     assert( pFrom->nFree>=iToHdr );
49360     assert( get2byte(&aFrom[iFromHdr+5])<=pBt->usableSize );
49361   
49362     /* Copy the b-tree node content from page pFrom to page pTo. */
49363     iData = get2byte(&aFrom[iFromHdr+5]);
49364     memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
49365     memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
49366   
49367     /* Reinitialize page pTo so that the contents of the MemPage structure
49368     ** match the new data. The initialization of pTo can actually fail under
49369     ** fairly obscure circumstances, even though it is a copy of initialized 
49370     ** page pFrom.
49371     */
49372     pTo->isInit = 0;
49373     rc = btreeInitPage(pTo);
49374     if( rc!=SQLITE_OK ){
49375       *pRC = rc;
49376       return;
49377     }
49378   
49379     /* If this is an auto-vacuum database, update the pointer-map entries
49380     ** for any b-tree or overflow pages that pTo now contains the pointers to.
49381     */
49382     if( ISAUTOVACUUM ){
49383       *pRC = setChildPtrmaps(pTo);
49384     }
49385   }
49386 }
49387
49388 /*
49389 ** This routine redistributes cells on the iParentIdx'th child of pParent
49390 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
49391 ** same amount of free space. Usually a single sibling on either side of the
49392 ** page are used in the balancing, though both siblings might come from one
49393 ** side if the page is the first or last child of its parent. If the page 
49394 ** has fewer than 2 siblings (something which can only happen if the page
49395 ** is a root page or a child of a root page) then all available siblings
49396 ** participate in the balancing.
49397 **
49398 ** The number of siblings of the page might be increased or decreased by 
49399 ** one or two in an effort to keep pages nearly full but not over full. 
49400 **
49401 ** Note that when this routine is called, some of the cells on the page
49402 ** might not actually be stored in MemPage.aData[]. This can happen
49403 ** if the page is overfull. This routine ensures that all cells allocated
49404 ** to the page and its siblings fit into MemPage.aData[] before returning.
49405 **
49406 ** In the course of balancing the page and its siblings, cells may be
49407 ** inserted into or removed from the parent page (pParent). Doing so
49408 ** may cause the parent page to become overfull or underfull. If this
49409 ** happens, it is the responsibility of the caller to invoke the correct
49410 ** balancing routine to fix this problem (see the balance() routine). 
49411 **
49412 ** If this routine fails for any reason, it might leave the database
49413 ** in a corrupted state. So if this routine fails, the database should
49414 ** be rolled back.
49415 **
49416 ** The third argument to this function, aOvflSpace, is a pointer to a
49417 ** buffer big enough to hold one page. If while inserting cells into the parent
49418 ** page (pParent) the parent page becomes overfull, this buffer is
49419 ** used to store the parent's overflow cells. Because this function inserts
49420 ** a maximum of four divider cells into the parent page, and the maximum
49421 ** size of a cell stored within an internal node is always less than 1/4
49422 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
49423 ** enough for all overflow cells.
49424 **
49425 ** If aOvflSpace is set to a null pointer, this function returns 
49426 ** SQLITE_NOMEM.
49427 */
49428 static int balance_nonroot(
49429   MemPage *pParent,               /* Parent page of siblings being balanced */
49430   int iParentIdx,                 /* Index of "the page" in pParent */
49431   u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
49432   int isRoot                      /* True if pParent is a root-page */
49433 ){
49434   BtShared *pBt;               /* The whole database */
49435   int nCell = 0;               /* Number of cells in apCell[] */
49436   int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
49437   int nNew = 0;                /* Number of pages in apNew[] */
49438   int nOld;                    /* Number of pages in apOld[] */
49439   int i, j, k;                 /* Loop counters */
49440   int nxDiv;                   /* Next divider slot in pParent->aCell[] */
49441   int rc = SQLITE_OK;          /* The return code */
49442   u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
49443   int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
49444   int usableSpace;             /* Bytes in pPage beyond the header */
49445   int pageFlags;               /* Value of pPage->aData[0] */
49446   int subtotal;                /* Subtotal of bytes in cells on one page */
49447   int iSpace1 = 0;             /* First unused byte of aSpace1[] */
49448   int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
49449   int szScratch;               /* Size of scratch memory requested */
49450   MemPage *apOld[NB];          /* pPage and up to two siblings */
49451   MemPage *apCopy[NB];         /* Private copies of apOld[] pages */
49452   MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
49453   u8 *pRight;                  /* Location in parent of right-sibling pointer */
49454   u8 *apDiv[NB-1];             /* Divider cells in pParent */
49455   int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
49456   int szNew[NB+2];             /* Combined size of cells place on i-th page */
49457   u8 **apCell = 0;             /* All cells begin balanced */
49458   u16 *szCell;                 /* Local size of all cells in apCell[] */
49459   u8 *aSpace1;                 /* Space for copies of dividers cells */
49460   Pgno pgno;                   /* Temp var to store a page number in */
49461
49462   pBt = pParent->pBt;
49463   assert( sqlite3_mutex_held(pBt->mutex) );
49464   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
49465
49466 #if 0
49467   TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
49468 #endif
49469
49470   /* At this point pParent may have at most one overflow cell. And if
49471   ** this overflow cell is present, it must be the cell with 
49472   ** index iParentIdx. This scenario comes about when this function
49473   ** is called (indirectly) from sqlite3BtreeDelete().
49474   */
49475   assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
49476   assert( pParent->nOverflow==0 || pParent->aOvfl[0].idx==iParentIdx );
49477
49478   if( !aOvflSpace ){
49479     return SQLITE_NOMEM;
49480   }
49481
49482   /* Find the sibling pages to balance. Also locate the cells in pParent 
49483   ** that divide the siblings. An attempt is made to find NN siblings on 
49484   ** either side of pPage. More siblings are taken from one side, however, 
49485   ** if there are fewer than NN siblings on the other side. If pParent
49486   ** has NB or fewer children then all children of pParent are taken.  
49487   **
49488   ** This loop also drops the divider cells from the parent page. This
49489   ** way, the remainder of the function does not have to deal with any
49490   ** overflow cells in the parent page, since if any existed they will
49491   ** have already been removed.
49492   */
49493   i = pParent->nOverflow + pParent->nCell;
49494   if( i<2 ){
49495     nxDiv = 0;
49496     nOld = i+1;
49497   }else{
49498     nOld = 3;
49499     if( iParentIdx==0 ){                 
49500       nxDiv = 0;
49501     }else if( iParentIdx==i ){
49502       nxDiv = i-2;
49503     }else{
49504       nxDiv = iParentIdx-1;
49505     }
49506     i = 2;
49507   }
49508   if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
49509     pRight = &pParent->aData[pParent->hdrOffset+8];
49510   }else{
49511     pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
49512   }
49513   pgno = get4byte(pRight);
49514   while( 1 ){
49515     rc = getAndInitPage(pBt, pgno, &apOld[i]);
49516     if( rc ){
49517       memset(apOld, 0, (i+1)*sizeof(MemPage*));
49518       goto balance_cleanup;
49519     }
49520     nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
49521     if( (i--)==0 ) break;
49522
49523     if( i+nxDiv==pParent->aOvfl[0].idx && pParent->nOverflow ){
49524       apDiv[i] = pParent->aOvfl[0].pCell;
49525       pgno = get4byte(apDiv[i]);
49526       szNew[i] = cellSizePtr(pParent, apDiv[i]);
49527       pParent->nOverflow = 0;
49528     }else{
49529       apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
49530       pgno = get4byte(apDiv[i]);
49531       szNew[i] = cellSizePtr(pParent, apDiv[i]);
49532
49533       /* Drop the cell from the parent page. apDiv[i] still points to
49534       ** the cell within the parent, even though it has been dropped.
49535       ** This is safe because dropping a cell only overwrites the first
49536       ** four bytes of it, and this function does not need the first
49537       ** four bytes of the divider cell. So the pointer is safe to use
49538       ** later on.  
49539       **
49540       ** Unless SQLite is compiled in secure-delete mode. In this case,
49541       ** the dropCell() routine will overwrite the entire cell with zeroes.
49542       ** In this case, temporarily copy the cell into the aOvflSpace[]
49543       ** buffer. It will be copied out again as soon as the aSpace[] buffer
49544       ** is allocated.  */
49545       if( pBt->secureDelete ){
49546         int iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
49547         if( (iOff+szNew[i])>pBt->usableSize ){
49548           rc = SQLITE_CORRUPT_BKPT;
49549           memset(apOld, 0, (i+1)*sizeof(MemPage*));
49550           goto balance_cleanup;
49551         }else{
49552           memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
49553           apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
49554         }
49555       }
49556       dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
49557     }
49558   }
49559
49560   /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
49561   ** alignment */
49562   nMaxCells = (nMaxCells + 3)&~3;
49563
49564   /*
49565   ** Allocate space for memory structures
49566   */
49567   k = pBt->pageSize + ROUND8(sizeof(MemPage));
49568   szScratch =
49569        nMaxCells*sizeof(u8*)                       /* apCell */
49570      + nMaxCells*sizeof(u16)                       /* szCell */
49571      + pBt->pageSize                               /* aSpace1 */
49572      + k*nOld;                                     /* Page copies (apCopy) */
49573   apCell = sqlite3ScratchMalloc( szScratch ); 
49574   if( apCell==0 ){
49575     rc = SQLITE_NOMEM;
49576     goto balance_cleanup;
49577   }
49578   szCell = (u16*)&apCell[nMaxCells];
49579   aSpace1 = (u8*)&szCell[nMaxCells];
49580   assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
49581
49582   /*
49583   ** Load pointers to all cells on sibling pages and the divider cells
49584   ** into the local apCell[] array.  Make copies of the divider cells
49585   ** into space obtained from aSpace1[] and remove the the divider Cells
49586   ** from pParent.
49587   **
49588   ** If the siblings are on leaf pages, then the child pointers of the
49589   ** divider cells are stripped from the cells before they are copied
49590   ** into aSpace1[].  In this way, all cells in apCell[] are without
49591   ** child pointers.  If siblings are not leaves, then all cell in
49592   ** apCell[] include child pointers.  Either way, all cells in apCell[]
49593   ** are alike.
49594   **
49595   ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
49596   **       leafData:  1 if pPage holds key+data and pParent holds only keys.
49597   */
49598   leafCorrection = apOld[0]->leaf*4;
49599   leafData = apOld[0]->hasData;
49600   for(i=0; i<nOld; i++){
49601     int limit;
49602     
49603     /* Before doing anything else, take a copy of the i'th original sibling
49604     ** The rest of this function will use data from the copies rather
49605     ** that the original pages since the original pages will be in the
49606     ** process of being overwritten.  */
49607     MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
49608     memcpy(pOld, apOld[i], sizeof(MemPage));
49609     pOld->aData = (void*)&pOld[1];
49610     memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
49611
49612     limit = pOld->nCell+pOld->nOverflow;
49613     for(j=0; j<limit; j++){
49614       assert( nCell<nMaxCells );
49615       apCell[nCell] = findOverflowCell(pOld, j);
49616       szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
49617       nCell++;
49618     }
49619     if( i<nOld-1 && !leafData){
49620       u16 sz = (u16)szNew[i];
49621       u8 *pTemp;
49622       assert( nCell<nMaxCells );
49623       szCell[nCell] = sz;
49624       pTemp = &aSpace1[iSpace1];
49625       iSpace1 += sz;
49626       assert( sz<=pBt->pageSize/4 );
49627       assert( iSpace1<=pBt->pageSize );
49628       memcpy(pTemp, apDiv[i], sz);
49629       apCell[nCell] = pTemp+leafCorrection;
49630       assert( leafCorrection==0 || leafCorrection==4 );
49631       szCell[nCell] = szCell[nCell] - leafCorrection;
49632       if( !pOld->leaf ){
49633         assert( leafCorrection==0 );
49634         assert( pOld->hdrOffset==0 );
49635         /* The right pointer of the child page pOld becomes the left
49636         ** pointer of the divider cell */
49637         memcpy(apCell[nCell], &pOld->aData[8], 4);
49638       }else{
49639         assert( leafCorrection==4 );
49640         if( szCell[nCell]<4 ){
49641           /* Do not allow any cells smaller than 4 bytes. */
49642           szCell[nCell] = 4;
49643         }
49644       }
49645       nCell++;
49646     }
49647   }
49648
49649   /*
49650   ** Figure out the number of pages needed to hold all nCell cells.
49651   ** Store this number in "k".  Also compute szNew[] which is the total
49652   ** size of all cells on the i-th page and cntNew[] which is the index
49653   ** in apCell[] of the cell that divides page i from page i+1.  
49654   ** cntNew[k] should equal nCell.
49655   **
49656   ** Values computed by this block:
49657   **
49658   **           k: The total number of sibling pages
49659   **    szNew[i]: Spaced used on the i-th sibling page.
49660   **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to
49661   **              the right of the i-th sibling page.
49662   ** usableSpace: Number of bytes of space available on each sibling.
49663   ** 
49664   */
49665   usableSpace = pBt->usableSize - 12 + leafCorrection;
49666   for(subtotal=k=i=0; i<nCell; i++){
49667     assert( i<nMaxCells );
49668     subtotal += szCell[i] + 2;
49669     if( subtotal > usableSpace ){
49670       szNew[k] = subtotal - szCell[i];
49671       cntNew[k] = i;
49672       if( leafData ){ i--; }
49673       subtotal = 0;
49674       k++;
49675       if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
49676     }
49677   }
49678   szNew[k] = subtotal;
49679   cntNew[k] = nCell;
49680   k++;
49681
49682   /*
49683   ** The packing computed by the previous block is biased toward the siblings
49684   ** on the left side.  The left siblings are always nearly full, while the
49685   ** right-most sibling might be nearly empty.  This block of code attempts
49686   ** to adjust the packing of siblings to get a better balance.
49687   **
49688   ** This adjustment is more than an optimization.  The packing above might
49689   ** be so out of balance as to be illegal.  For example, the right-most
49690   ** sibling might be completely empty.  This adjustment is not optional.
49691   */
49692   for(i=k-1; i>0; i--){
49693     int szRight = szNew[i];  /* Size of sibling on the right */
49694     int szLeft = szNew[i-1]; /* Size of sibling on the left */
49695     int r;              /* Index of right-most cell in left sibling */
49696     int d;              /* Index of first cell to the left of right sibling */
49697
49698     r = cntNew[i-1] - 1;
49699     d = r + 1 - leafData;
49700     assert( d<nMaxCells );
49701     assert( r<nMaxCells );
49702     while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
49703       szRight += szCell[d] + 2;
49704       szLeft -= szCell[r] + 2;
49705       cntNew[i-1]--;
49706       r = cntNew[i-1] - 1;
49707       d = r + 1 - leafData;
49708     }
49709     szNew[i] = szRight;
49710     szNew[i-1] = szLeft;
49711   }
49712
49713   /* Either we found one or more cells (cntnew[0])>0) or pPage is
49714   ** a virtual root page.  A virtual root page is when the real root
49715   ** page is page 1 and we are the only child of that page.
49716   */
49717   assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
49718
49719   TRACE(("BALANCE: old: %d %d %d  ",
49720     apOld[0]->pgno, 
49721     nOld>=2 ? apOld[1]->pgno : 0,
49722     nOld>=3 ? apOld[2]->pgno : 0
49723   ));
49724
49725   /*
49726   ** Allocate k new pages.  Reuse old pages where possible.
49727   */
49728   if( apOld[0]->pgno<=1 ){
49729     rc = SQLITE_CORRUPT_BKPT;
49730     goto balance_cleanup;
49731   }
49732   pageFlags = apOld[0]->aData[0];
49733   for(i=0; i<k; i++){
49734     MemPage *pNew;
49735     if( i<nOld ){
49736       pNew = apNew[i] = apOld[i];
49737       apOld[i] = 0;
49738       rc = sqlite3PagerWrite(pNew->pDbPage);
49739       nNew++;
49740       if( rc ) goto balance_cleanup;
49741     }else{
49742       assert( i>0 );
49743       rc = allocateBtreePage(pBt, &pNew, &pgno, pgno, 0);
49744       if( rc ) goto balance_cleanup;
49745       apNew[i] = pNew;
49746       nNew++;
49747
49748       /* Set the pointer-map entry for the new sibling page. */
49749       if( ISAUTOVACUUM ){
49750         ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
49751         if( rc!=SQLITE_OK ){
49752           goto balance_cleanup;
49753         }
49754       }
49755     }
49756   }
49757
49758   /* Free any old pages that were not reused as new pages.
49759   */
49760   while( i<nOld ){
49761     freePage(apOld[i], &rc);
49762     if( rc ) goto balance_cleanup;
49763     releasePage(apOld[i]);
49764     apOld[i] = 0;
49765     i++;
49766   }
49767
49768   /*
49769   ** Put the new pages in accending order.  This helps to
49770   ** keep entries in the disk file in order so that a scan
49771   ** of the table is a linear scan through the file.  That
49772   ** in turn helps the operating system to deliver pages
49773   ** from the disk more rapidly.
49774   **
49775   ** An O(n^2) insertion sort algorithm is used, but since
49776   ** n is never more than NB (a small constant), that should
49777   ** not be a problem.
49778   **
49779   ** When NB==3, this one optimization makes the database
49780   ** about 25% faster for large insertions and deletions.
49781   */
49782   for(i=0; i<k-1; i++){
49783     int minV = apNew[i]->pgno;
49784     int minI = i;
49785     for(j=i+1; j<k; j++){
49786       if( apNew[j]->pgno<(unsigned)minV ){
49787         minI = j;
49788         minV = apNew[j]->pgno;
49789       }
49790     }
49791     if( minI>i ){
49792       int t;
49793       MemPage *pT;
49794       t = apNew[i]->pgno;
49795       pT = apNew[i];
49796       apNew[i] = apNew[minI];
49797       apNew[minI] = pT;
49798     }
49799   }
49800   TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
49801     apNew[0]->pgno, szNew[0],
49802     nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
49803     nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
49804     nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
49805     nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
49806
49807   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
49808   put4byte(pRight, apNew[nNew-1]->pgno);
49809
49810   /*
49811   ** Evenly distribute the data in apCell[] across the new pages.
49812   ** Insert divider cells into pParent as necessary.
49813   */
49814   j = 0;
49815   for(i=0; i<nNew; i++){
49816     /* Assemble the new sibling page. */
49817     MemPage *pNew = apNew[i];
49818     assert( j<nMaxCells );
49819     zeroPage(pNew, pageFlags);
49820     assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
49821     assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
49822     assert( pNew->nOverflow==0 );
49823
49824     j = cntNew[i];
49825
49826     /* If the sibling page assembled above was not the right-most sibling,
49827     ** insert a divider cell into the parent page.
49828     */
49829     assert( i<nNew-1 || j==nCell );
49830     if( j<nCell ){
49831       u8 *pCell;
49832       u8 *pTemp;
49833       int sz;
49834
49835       assert( j<nMaxCells );
49836       pCell = apCell[j];
49837       sz = szCell[j] + leafCorrection;
49838       pTemp = &aOvflSpace[iOvflSpace];
49839       if( !pNew->leaf ){
49840         memcpy(&pNew->aData[8], pCell, 4);
49841       }else if( leafData ){
49842         /* If the tree is a leaf-data tree, and the siblings are leaves, 
49843         ** then there is no divider cell in apCell[]. Instead, the divider 
49844         ** cell consists of the integer key for the right-most cell of 
49845         ** the sibling-page assembled above only.
49846         */
49847         CellInfo info;
49848         j--;
49849         btreeParseCellPtr(pNew, apCell[j], &info);
49850         pCell = pTemp;
49851         sz = 4 + putVarint(&pCell[4], info.nKey);
49852         pTemp = 0;
49853       }else{
49854         pCell -= 4;
49855         /* Obscure case for non-leaf-data trees: If the cell at pCell was
49856         ** previously stored on a leaf node, and its reported size was 4
49857         ** bytes, then it may actually be smaller than this 
49858         ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
49859         ** any cell). But it is important to pass the correct size to 
49860         ** insertCell(), so reparse the cell now.
49861         **
49862         ** Note that this can never happen in an SQLite data file, as all
49863         ** cells are at least 4 bytes. It only happens in b-trees used
49864         ** to evaluate "IN (SELECT ...)" and similar clauses.
49865         */
49866         if( szCell[j]==4 ){
49867           assert(leafCorrection==4);
49868           sz = cellSizePtr(pParent, pCell);
49869         }
49870       }
49871       iOvflSpace += sz;
49872       assert( sz<=pBt->pageSize/4 );
49873       assert( iOvflSpace<=pBt->pageSize );
49874       insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
49875       if( rc!=SQLITE_OK ) goto balance_cleanup;
49876       assert( sqlite3PagerIswriteable(pParent->pDbPage) );
49877
49878       j++;
49879       nxDiv++;
49880     }
49881   }
49882   assert( j==nCell );
49883   assert( nOld>0 );
49884   assert( nNew>0 );
49885   if( (pageFlags & PTF_LEAF)==0 ){
49886     u8 *zChild = &apCopy[nOld-1]->aData[8];
49887     memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
49888   }
49889
49890   if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
49891     /* The root page of the b-tree now contains no cells. The only sibling
49892     ** page is the right-child of the parent. Copy the contents of the
49893     ** child page into the parent, decreasing the overall height of the
49894     ** b-tree structure by one. This is described as the "balance-shallower"
49895     ** sub-algorithm in some documentation.
49896     **
49897     ** If this is an auto-vacuum database, the call to copyNodeContent() 
49898     ** sets all pointer-map entries corresponding to database image pages 
49899     ** for which the pointer is stored within the content being copied.
49900     **
49901     ** The second assert below verifies that the child page is defragmented
49902     ** (it must be, as it was just reconstructed using assemblePage()). This
49903     ** is important if the parent page happens to be page 1 of the database
49904     ** image.  */
49905     assert( nNew==1 );
49906     assert( apNew[0]->nFree == 
49907         (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2) 
49908     );
49909     copyNodeContent(apNew[0], pParent, &rc);
49910     freePage(apNew[0], &rc);
49911   }else if( ISAUTOVACUUM ){
49912     /* Fix the pointer-map entries for all the cells that were shifted around. 
49913     ** There are several different types of pointer-map entries that need to
49914     ** be dealt with by this routine. Some of these have been set already, but
49915     ** many have not. The following is a summary:
49916     **
49917     **   1) The entries associated with new sibling pages that were not
49918     **      siblings when this function was called. These have already
49919     **      been set. We don't need to worry about old siblings that were
49920     **      moved to the free-list - the freePage() code has taken care
49921     **      of those.
49922     **
49923     **   2) The pointer-map entries associated with the first overflow
49924     **      page in any overflow chains used by new divider cells. These 
49925     **      have also already been taken care of by the insertCell() code.
49926     **
49927     **   3) If the sibling pages are not leaves, then the child pages of
49928     **      cells stored on the sibling pages may need to be updated.
49929     **
49930     **   4) If the sibling pages are not internal intkey nodes, then any
49931     **      overflow pages used by these cells may need to be updated
49932     **      (internal intkey nodes never contain pointers to overflow pages).
49933     **
49934     **   5) If the sibling pages are not leaves, then the pointer-map
49935     **      entries for the right-child pages of each sibling may need
49936     **      to be updated.
49937     **
49938     ** Cases 1 and 2 are dealt with above by other code. The next
49939     ** block deals with cases 3 and 4 and the one after that, case 5. Since
49940     ** setting a pointer map entry is a relatively expensive operation, this
49941     ** code only sets pointer map entries for child or overflow pages that have
49942     ** actually moved between pages.  */
49943     MemPage *pNew = apNew[0];
49944     MemPage *pOld = apCopy[0];
49945     int nOverflow = pOld->nOverflow;
49946     int iNextOld = pOld->nCell + nOverflow;
49947     int iOverflow = (nOverflow ? pOld->aOvfl[0].idx : -1);
49948     j = 0;                             /* Current 'old' sibling page */
49949     k = 0;                             /* Current 'new' sibling page */
49950     for(i=0; i<nCell; i++){
49951       int isDivider = 0;
49952       while( i==iNextOld ){
49953         /* Cell i is the cell immediately following the last cell on old
49954         ** sibling page j. If the siblings are not leaf pages of an
49955         ** intkey b-tree, then cell i was a divider cell. */
49956         pOld = apCopy[++j];
49957         iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
49958         if( pOld->nOverflow ){
49959           nOverflow = pOld->nOverflow;
49960           iOverflow = i + !leafData + pOld->aOvfl[0].idx;
49961         }
49962         isDivider = !leafData;  
49963       }
49964
49965       assert(nOverflow>0 || iOverflow<i );
49966       assert(nOverflow<2 || pOld->aOvfl[0].idx==pOld->aOvfl[1].idx-1);
49967       assert(nOverflow<3 || pOld->aOvfl[1].idx==pOld->aOvfl[2].idx-1);
49968       if( i==iOverflow ){
49969         isDivider = 1;
49970         if( (--nOverflow)>0 ){
49971           iOverflow++;
49972         }
49973       }
49974
49975       if( i==cntNew[k] ){
49976         /* Cell i is the cell immediately following the last cell on new
49977         ** sibling page k. If the siblings are not leaf pages of an
49978         ** intkey b-tree, then cell i is a divider cell.  */
49979         pNew = apNew[++k];
49980         if( !leafData ) continue;
49981       }
49982       assert( j<nOld );
49983       assert( k<nNew );
49984
49985       /* If the cell was originally divider cell (and is not now) or
49986       ** an overflow cell, or if the cell was located on a different sibling
49987       ** page before the balancing, then the pointer map entries associated
49988       ** with any child or overflow pages need to be updated.  */
49989       if( isDivider || pOld->pgno!=pNew->pgno ){
49990         if( !leafCorrection ){
49991           ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
49992         }
49993         if( szCell[i]>pNew->minLocal ){
49994           ptrmapPutOvflPtr(pNew, apCell[i], &rc);
49995         }
49996       }
49997     }
49998
49999     if( !leafCorrection ){
50000       for(i=0; i<nNew; i++){
50001         u32 key = get4byte(&apNew[i]->aData[8]);
50002         ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
50003       }
50004     }
50005
50006 #if 0
50007     /* The ptrmapCheckPages() contains assert() statements that verify that
50008     ** all pointer map pages are set correctly. This is helpful while 
50009     ** debugging. This is usually disabled because a corrupt database may
50010     ** cause an assert() statement to fail.  */
50011     ptrmapCheckPages(apNew, nNew);
50012     ptrmapCheckPages(&pParent, 1);
50013 #endif
50014   }
50015
50016   assert( pParent->isInit );
50017   TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
50018           nOld, nNew, nCell));
50019
50020   /*
50021   ** Cleanup before returning.
50022   */
50023 balance_cleanup:
50024   sqlite3ScratchFree(apCell);
50025   for(i=0; i<nOld; i++){
50026     releasePage(apOld[i]);
50027   }
50028   for(i=0; i<nNew; i++){
50029     releasePage(apNew[i]);
50030   }
50031
50032   return rc;
50033 }
50034
50035
50036 /*
50037 ** This function is called when the root page of a b-tree structure is
50038 ** overfull (has one or more overflow pages).
50039 **
50040 ** A new child page is allocated and the contents of the current root
50041 ** page, including overflow cells, are copied into the child. The root
50042 ** page is then overwritten to make it an empty page with the right-child 
50043 ** pointer pointing to the new page.
50044 **
50045 ** Before returning, all pointer-map entries corresponding to pages 
50046 ** that the new child-page now contains pointers to are updated. The
50047 ** entry corresponding to the new right-child pointer of the root
50048 ** page is also updated.
50049 **
50050 ** If successful, *ppChild is set to contain a reference to the child 
50051 ** page and SQLITE_OK is returned. In this case the caller is required
50052 ** to call releasePage() on *ppChild exactly once. If an error occurs,
50053 ** an error code is returned and *ppChild is set to 0.
50054 */
50055 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
50056   int rc;                        /* Return value from subprocedures */
50057   MemPage *pChild = 0;           /* Pointer to a new child page */
50058   Pgno pgnoChild = 0;            /* Page number of the new child page */
50059   BtShared *pBt = pRoot->pBt;    /* The BTree */
50060
50061   assert( pRoot->nOverflow>0 );
50062   assert( sqlite3_mutex_held(pBt->mutex) );
50063
50064   /* Make pRoot, the root page of the b-tree, writable. Allocate a new 
50065   ** page that will become the new right-child of pPage. Copy the contents
50066   ** of the node stored on pRoot into the new child page.
50067   */
50068   rc = sqlite3PagerWrite(pRoot->pDbPage);
50069   if( rc==SQLITE_OK ){
50070     rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
50071     copyNodeContent(pRoot, pChild, &rc);
50072     if( ISAUTOVACUUM ){
50073       ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
50074     }
50075   }
50076   if( rc ){
50077     *ppChild = 0;
50078     releasePage(pChild);
50079     return rc;
50080   }
50081   assert( sqlite3PagerIswriteable(pChild->pDbPage) );
50082   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
50083   assert( pChild->nCell==pRoot->nCell );
50084
50085   TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
50086
50087   /* Copy the overflow cells from pRoot to pChild */
50088   memcpy(pChild->aOvfl, pRoot->aOvfl, pRoot->nOverflow*sizeof(pRoot->aOvfl[0]));
50089   pChild->nOverflow = pRoot->nOverflow;
50090
50091   /* Zero the contents of pRoot. Then install pChild as the right-child. */
50092   zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
50093   put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
50094
50095   *ppChild = pChild;
50096   return SQLITE_OK;
50097 }
50098
50099 /*
50100 ** The page that pCur currently points to has just been modified in
50101 ** some way. This function figures out if this modification means the
50102 ** tree needs to be balanced, and if so calls the appropriate balancing 
50103 ** routine. Balancing routines are:
50104 **
50105 **   balance_quick()
50106 **   balance_deeper()
50107 **   balance_nonroot()
50108 */
50109 static int balance(BtCursor *pCur){
50110   int rc = SQLITE_OK;
50111   const int nMin = pCur->pBt->usableSize * 2 / 3;
50112   u8 aBalanceQuickSpace[13];
50113   u8 *pFree = 0;
50114
50115   TESTONLY( int balance_quick_called = 0 );
50116   TESTONLY( int balance_deeper_called = 0 );
50117
50118   do {
50119     int iPage = pCur->iPage;
50120     MemPage *pPage = pCur->apPage[iPage];
50121
50122     if( iPage==0 ){
50123       if( pPage->nOverflow ){
50124         /* The root page of the b-tree is overfull. In this case call the
50125         ** balance_deeper() function to create a new child for the root-page
50126         ** and copy the current contents of the root-page to it. The
50127         ** next iteration of the do-loop will balance the child page.
50128         */ 
50129         assert( (balance_deeper_called++)==0 );
50130         rc = balance_deeper(pPage, &pCur->apPage[1]);
50131         if( rc==SQLITE_OK ){
50132           pCur->iPage = 1;
50133           pCur->aiIdx[0] = 0;
50134           pCur->aiIdx[1] = 0;
50135           assert( pCur->apPage[1]->nOverflow );
50136         }
50137       }else{
50138         break;
50139       }
50140     }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
50141       break;
50142     }else{
50143       MemPage * const pParent = pCur->apPage[iPage-1];
50144       int const iIdx = pCur->aiIdx[iPage-1];
50145
50146       rc = sqlite3PagerWrite(pParent->pDbPage);
50147       if( rc==SQLITE_OK ){
50148 #ifndef SQLITE_OMIT_QUICKBALANCE
50149         if( pPage->hasData
50150          && pPage->nOverflow==1
50151          && pPage->aOvfl[0].idx==pPage->nCell
50152          && pParent->pgno!=1
50153          && pParent->nCell==iIdx
50154         ){
50155           /* Call balance_quick() to create a new sibling of pPage on which
50156           ** to store the overflow cell. balance_quick() inserts a new cell
50157           ** into pParent, which may cause pParent overflow. If this
50158           ** happens, the next interation of the do-loop will balance pParent 
50159           ** use either balance_nonroot() or balance_deeper(). Until this
50160           ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
50161           ** buffer. 
50162           **
50163           ** The purpose of the following assert() is to check that only a
50164           ** single call to balance_quick() is made for each call to this
50165           ** function. If this were not verified, a subtle bug involving reuse
50166           ** of the aBalanceQuickSpace[] might sneak in.
50167           */
50168           assert( (balance_quick_called++)==0 );
50169           rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
50170         }else
50171 #endif
50172         {
50173           /* In this case, call balance_nonroot() to redistribute cells
50174           ** between pPage and up to 2 of its sibling pages. This involves
50175           ** modifying the contents of pParent, which may cause pParent to
50176           ** become overfull or underfull. The next iteration of the do-loop
50177           ** will balance the parent page to correct this.
50178           ** 
50179           ** If the parent page becomes overfull, the overflow cell or cells
50180           ** are stored in the pSpace buffer allocated immediately below. 
50181           ** A subsequent iteration of the do-loop will deal with this by
50182           ** calling balance_nonroot() (balance_deeper() may be called first,
50183           ** but it doesn't deal with overflow cells - just moves them to a
50184           ** different page). Once this subsequent call to balance_nonroot() 
50185           ** has completed, it is safe to release the pSpace buffer used by
50186           ** the previous call, as the overflow cell data will have been 
50187           ** copied either into the body of a database page or into the new
50188           ** pSpace buffer passed to the latter call to balance_nonroot().
50189           */
50190           u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
50191           rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1);
50192           if( pFree ){
50193             /* If pFree is not NULL, it points to the pSpace buffer used 
50194             ** by a previous call to balance_nonroot(). Its contents are
50195             ** now stored either on real database pages or within the 
50196             ** new pSpace buffer, so it may be safely freed here. */
50197             sqlite3PageFree(pFree);
50198           }
50199
50200           /* The pSpace buffer will be freed after the next call to
50201           ** balance_nonroot(), or just before this function returns, whichever
50202           ** comes first. */
50203           pFree = pSpace;
50204         }
50205       }
50206
50207       pPage->nOverflow = 0;
50208
50209       /* The next iteration of the do-loop balances the parent page. */
50210       releasePage(pPage);
50211       pCur->iPage--;
50212     }
50213   }while( rc==SQLITE_OK );
50214
50215   if( pFree ){
50216     sqlite3PageFree(pFree);
50217   }
50218   return rc;
50219 }
50220
50221
50222 /*
50223 ** Insert a new record into the BTree.  The key is given by (pKey,nKey)
50224 ** and the data is given by (pData,nData).  The cursor is used only to
50225 ** define what table the record should be inserted into.  The cursor
50226 ** is left pointing at a random location.
50227 **
50228 ** For an INTKEY table, only the nKey value of the key is used.  pKey is
50229 ** ignored.  For a ZERODATA table, the pData and nData are both ignored.
50230 **
50231 ** If the seekResult parameter is non-zero, then a successful call to
50232 ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
50233 ** been performed. seekResult is the search result returned (a negative
50234 ** number if pCur points at an entry that is smaller than (pKey, nKey), or
50235 ** a positive value if pCur points at an etry that is larger than 
50236 ** (pKey, nKey)). 
50237 **
50238 ** If the seekResult parameter is non-zero, then the caller guarantees that
50239 ** cursor pCur is pointing at the existing copy of a row that is to be
50240 ** overwritten.  If the seekResult parameter is 0, then cursor pCur may
50241 ** point to any entry or to no entry at all and so this function has to seek
50242 ** the cursor before the new key can be inserted.
50243 */
50244 SQLITE_PRIVATE int sqlite3BtreeInsert(
50245   BtCursor *pCur,                /* Insert data into the table of this cursor */
50246   const void *pKey, i64 nKey,    /* The key of the new record */
50247   const void *pData, int nData,  /* The data of the new record */
50248   int nZero,                     /* Number of extra 0 bytes to append to data */
50249   int appendBias,                /* True if this is likely an append */
50250   int seekResult                 /* Result of prior MovetoUnpacked() call */
50251 ){
50252   int rc;
50253   int loc = seekResult;          /* -1: before desired location  +1: after */
50254   int szNew = 0;
50255   int idx;
50256   MemPage *pPage;
50257   Btree *p = pCur->pBtree;
50258   BtShared *pBt = p->pBt;
50259   unsigned char *oldCell;
50260   unsigned char *newCell = 0;
50261
50262   if( pCur->eState==CURSOR_FAULT ){
50263     assert( pCur->skipNext!=SQLITE_OK );
50264     return pCur->skipNext;
50265   }
50266
50267   assert( cursorHoldsMutex(pCur) );
50268   assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE && !pBt->readOnly );
50269   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
50270
50271   /* Assert that the caller has been consistent. If this cursor was opened
50272   ** expecting an index b-tree, then the caller should be inserting blob
50273   ** keys with no associated data. If the cursor was opened expecting an
50274   ** intkey table, the caller should be inserting integer keys with a
50275   ** blob of associated data.  */
50276   assert( (pKey==0)==(pCur->pKeyInfo==0) );
50277
50278   /* If this is an insert into a table b-tree, invalidate any incrblob 
50279   ** cursors open on the row being replaced (assuming this is a replace
50280   ** operation - if it is not, the following is a no-op).  */
50281   if( pCur->pKeyInfo==0 ){
50282     invalidateIncrblobCursors(p, nKey, 0);
50283   }
50284
50285   /* Save the positions of any other cursors open on this table.
50286   **
50287   ** In some cases, the call to btreeMoveto() below is a no-op. For
50288   ** example, when inserting data into a table with auto-generated integer
50289   ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the 
50290   ** integer key to use. It then calls this function to actually insert the 
50291   ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
50292   ** that the cursor is already where it needs to be and returns without
50293   ** doing any work. To avoid thwarting these optimizations, it is important
50294   ** not to clear the cursor here.
50295   */
50296   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
50297   if( rc ) return rc;
50298   if( !loc ){
50299     rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
50300     if( rc ) return rc;
50301   }
50302   assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
50303
50304   pPage = pCur->apPage[pCur->iPage];
50305   assert( pPage->intKey || nKey>=0 );
50306   assert( pPage->leaf || !pPage->intKey );
50307
50308   TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
50309           pCur->pgnoRoot, nKey, nData, pPage->pgno,
50310           loc==0 ? "overwrite" : "new entry"));
50311   assert( pPage->isInit );
50312   allocateTempSpace(pBt);
50313   newCell = pBt->pTmpSpace;
50314   if( newCell==0 ) return SQLITE_NOMEM;
50315   rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
50316   if( rc ) goto end_insert;
50317   assert( szNew==cellSizePtr(pPage, newCell) );
50318   assert( szNew<=MX_CELL_SIZE(pBt) );
50319   idx = pCur->aiIdx[pCur->iPage];
50320   if( loc==0 ){
50321     u16 szOld;
50322     assert( idx<pPage->nCell );
50323     rc = sqlite3PagerWrite(pPage->pDbPage);
50324     if( rc ){
50325       goto end_insert;
50326     }
50327     oldCell = findCell(pPage, idx);
50328     if( !pPage->leaf ){
50329       memcpy(newCell, oldCell, 4);
50330     }
50331     szOld = cellSizePtr(pPage, oldCell);
50332     rc = clearCell(pPage, oldCell);
50333     dropCell(pPage, idx, szOld, &rc);
50334     if( rc ) goto end_insert;
50335   }else if( loc<0 && pPage->nCell>0 ){
50336     assert( pPage->leaf );
50337     idx = ++pCur->aiIdx[pCur->iPage];
50338   }else{
50339     assert( pPage->leaf );
50340   }
50341   insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
50342   assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
50343
50344   /* If no error has occured and pPage has an overflow cell, call balance() 
50345   ** to redistribute the cells within the tree. Since balance() may move
50346   ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
50347   ** variables.
50348   **
50349   ** Previous versions of SQLite called moveToRoot() to move the cursor
50350   ** back to the root page as balance() used to invalidate the contents
50351   ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
50352   ** set the cursor state to "invalid". This makes common insert operations
50353   ** slightly faster.
50354   **
50355   ** There is a subtle but important optimization here too. When inserting
50356   ** multiple records into an intkey b-tree using a single cursor (as can
50357   ** happen while processing an "INSERT INTO ... SELECT" statement), it
50358   ** is advantageous to leave the cursor pointing to the last entry in
50359   ** the b-tree if possible. If the cursor is left pointing to the last
50360   ** entry in the table, and the next row inserted has an integer key
50361   ** larger than the largest existing key, it is possible to insert the
50362   ** row without seeking the cursor. This can be a big performance boost.
50363   */
50364   pCur->info.nSize = 0;
50365   pCur->validNKey = 0;
50366   if( rc==SQLITE_OK && pPage->nOverflow ){
50367     rc = balance(pCur);
50368
50369     /* Must make sure nOverflow is reset to zero even if the balance()
50370     ** fails. Internal data structure corruption will result otherwise. 
50371     ** Also, set the cursor state to invalid. This stops saveCursorPosition()
50372     ** from trying to save the current position of the cursor.  */
50373     pCur->apPage[pCur->iPage]->nOverflow = 0;
50374     pCur->eState = CURSOR_INVALID;
50375   }
50376   assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
50377
50378 end_insert:
50379   return rc;
50380 }
50381
50382 /*
50383 ** Delete the entry that the cursor is pointing to.  The cursor
50384 ** is left pointing at a arbitrary location.
50385 */
50386 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
50387   Btree *p = pCur->pBtree;
50388   BtShared *pBt = p->pBt;              
50389   int rc;                              /* Return code */
50390   MemPage *pPage;                      /* Page to delete cell from */
50391   unsigned char *pCell;                /* Pointer to cell to delete */
50392   int iCellIdx;                        /* Index of cell to delete */
50393   int iCellDepth;                      /* Depth of node containing pCell */ 
50394
50395   assert( cursorHoldsMutex(pCur) );
50396   assert( pBt->inTransaction==TRANS_WRITE );
50397   assert( !pBt->readOnly );
50398   assert( pCur->wrFlag );
50399   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
50400   assert( !hasReadConflicts(p, pCur->pgnoRoot) );
50401
50402   if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell) 
50403    || NEVER(pCur->eState!=CURSOR_VALID)
50404   ){
50405     return SQLITE_ERROR;  /* Something has gone awry. */
50406   }
50407
50408   /* If this is a delete operation to remove a row from a table b-tree,
50409   ** invalidate any incrblob cursors open on the row being deleted.  */
50410   if( pCur->pKeyInfo==0 ){
50411     invalidateIncrblobCursors(p, pCur->info.nKey, 0);
50412   }
50413
50414   iCellDepth = pCur->iPage;
50415   iCellIdx = pCur->aiIdx[iCellDepth];
50416   pPage = pCur->apPage[iCellDepth];
50417   pCell = findCell(pPage, iCellIdx);
50418
50419   /* If the page containing the entry to delete is not a leaf page, move
50420   ** the cursor to the largest entry in the tree that is smaller than
50421   ** the entry being deleted. This cell will replace the cell being deleted
50422   ** from the internal node. The 'previous' entry is used for this instead
50423   ** of the 'next' entry, as the previous entry is always a part of the
50424   ** sub-tree headed by the child page of the cell being deleted. This makes
50425   ** balancing the tree following the delete operation easier.  */
50426   if( !pPage->leaf ){
50427     int notUsed;
50428     rc = sqlite3BtreePrevious(pCur, &notUsed);
50429     if( rc ) return rc;
50430   }
50431
50432   /* Save the positions of any other cursors open on this table before
50433   ** making any modifications. Make the page containing the entry to be 
50434   ** deleted writable. Then free any overflow pages associated with the 
50435   ** entry and finally remove the cell itself from within the page.  
50436   */
50437   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
50438   if( rc ) return rc;
50439   rc = sqlite3PagerWrite(pPage->pDbPage);
50440   if( rc ) return rc;
50441   rc = clearCell(pPage, pCell);
50442   dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
50443   if( rc ) return rc;
50444
50445   /* If the cell deleted was not located on a leaf page, then the cursor
50446   ** is currently pointing to the largest entry in the sub-tree headed
50447   ** by the child-page of the cell that was just deleted from an internal
50448   ** node. The cell from the leaf node needs to be moved to the internal
50449   ** node to replace the deleted cell.  */
50450   if( !pPage->leaf ){
50451     MemPage *pLeaf = pCur->apPage[pCur->iPage];
50452     int nCell;
50453     Pgno n = pCur->apPage[iCellDepth+1]->pgno;
50454     unsigned char *pTmp;
50455
50456     pCell = findCell(pLeaf, pLeaf->nCell-1);
50457     nCell = cellSizePtr(pLeaf, pCell);
50458     assert( MX_CELL_SIZE(pBt)>=nCell );
50459
50460     allocateTempSpace(pBt);
50461     pTmp = pBt->pTmpSpace;
50462
50463     rc = sqlite3PagerWrite(pLeaf->pDbPage);
50464     insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
50465     dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
50466     if( rc ) return rc;
50467   }
50468
50469   /* Balance the tree. If the entry deleted was located on a leaf page,
50470   ** then the cursor still points to that page. In this case the first
50471   ** call to balance() repairs the tree, and the if(...) condition is
50472   ** never true.
50473   **
50474   ** Otherwise, if the entry deleted was on an internal node page, then
50475   ** pCur is pointing to the leaf page from which a cell was removed to
50476   ** replace the cell deleted from the internal node. This is slightly
50477   ** tricky as the leaf node may be underfull, and the internal node may
50478   ** be either under or overfull. In this case run the balancing algorithm
50479   ** on the leaf node first. If the balance proceeds far enough up the
50480   ** tree that we can be sure that any problem in the internal node has
50481   ** been corrected, so be it. Otherwise, after balancing the leaf node,
50482   ** walk the cursor up the tree to the internal node and balance it as 
50483   ** well.  */
50484   rc = balance(pCur);
50485   if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
50486     while( pCur->iPage>iCellDepth ){
50487       releasePage(pCur->apPage[pCur->iPage--]);
50488     }
50489     rc = balance(pCur);
50490   }
50491
50492   if( rc==SQLITE_OK ){
50493     moveToRoot(pCur);
50494   }
50495   return rc;
50496 }
50497
50498 /*
50499 ** Create a new BTree table.  Write into *piTable the page
50500 ** number for the root page of the new table.
50501 **
50502 ** The type of type is determined by the flags parameter.  Only the
50503 ** following values of flags are currently in use.  Other values for
50504 ** flags might not work:
50505 **
50506 **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
50507 **     BTREE_ZERODATA                  Used for SQL indices
50508 */
50509 static int btreeCreateTable(Btree *p, int *piTable, int flags){
50510   BtShared *pBt = p->pBt;
50511   MemPage *pRoot;
50512   Pgno pgnoRoot;
50513   int rc;
50514
50515   assert( sqlite3BtreeHoldsMutex(p) );
50516   assert( pBt->inTransaction==TRANS_WRITE );
50517   assert( !pBt->readOnly );
50518
50519 #ifdef SQLITE_OMIT_AUTOVACUUM
50520   rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
50521   if( rc ){
50522     return rc;
50523   }
50524 #else
50525   if( pBt->autoVacuum ){
50526     Pgno pgnoMove;      /* Move a page here to make room for the root-page */
50527     MemPage *pPageMove; /* The page to move to. */
50528
50529     /* Creating a new table may probably require moving an existing database
50530     ** to make room for the new tables root page. In case this page turns
50531     ** out to be an overflow page, delete all overflow page-map caches
50532     ** held by open cursors.
50533     */
50534     invalidateAllOverflowCache(pBt);
50535
50536     /* Read the value of meta[3] from the database to determine where the
50537     ** root page of the new table should go. meta[3] is the largest root-page
50538     ** created so far, so the new root-page is (meta[3]+1).
50539     */
50540     sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
50541     pgnoRoot++;
50542
50543     /* The new root-page may not be allocated on a pointer-map page, or the
50544     ** PENDING_BYTE page.
50545     */
50546     while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
50547         pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
50548       pgnoRoot++;
50549     }
50550     assert( pgnoRoot>=3 );
50551
50552     /* Allocate a page. The page that currently resides at pgnoRoot will
50553     ** be moved to the allocated page (unless the allocated page happens
50554     ** to reside at pgnoRoot).
50555     */
50556     rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
50557     if( rc!=SQLITE_OK ){
50558       return rc;
50559     }
50560
50561     if( pgnoMove!=pgnoRoot ){
50562       /* pgnoRoot is the page that will be used for the root-page of
50563       ** the new table (assuming an error did not occur). But we were
50564       ** allocated pgnoMove. If required (i.e. if it was not allocated
50565       ** by extending the file), the current page at position pgnoMove
50566       ** is already journaled.
50567       */
50568       u8 eType = 0;
50569       Pgno iPtrPage = 0;
50570
50571       releasePage(pPageMove);
50572
50573       /* Move the page currently at pgnoRoot to pgnoMove. */
50574       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
50575       if( rc!=SQLITE_OK ){
50576         return rc;
50577       }
50578       rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
50579       if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
50580         rc = SQLITE_CORRUPT_BKPT;
50581       }
50582       if( rc!=SQLITE_OK ){
50583         releasePage(pRoot);
50584         return rc;
50585       }
50586       assert( eType!=PTRMAP_ROOTPAGE );
50587       assert( eType!=PTRMAP_FREEPAGE );
50588       rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
50589       releasePage(pRoot);
50590
50591       /* Obtain the page at pgnoRoot */
50592       if( rc!=SQLITE_OK ){
50593         return rc;
50594       }
50595       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
50596       if( rc!=SQLITE_OK ){
50597         return rc;
50598       }
50599       rc = sqlite3PagerWrite(pRoot->pDbPage);
50600       if( rc!=SQLITE_OK ){
50601         releasePage(pRoot);
50602         return rc;
50603       }
50604     }else{
50605       pRoot = pPageMove;
50606     } 
50607
50608     /* Update the pointer-map and meta-data with the new root-page number. */
50609     ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
50610     if( rc ){
50611       releasePage(pRoot);
50612       return rc;
50613     }
50614
50615     /* When the new root page was allocated, page 1 was made writable in
50616     ** order either to increase the database filesize, or to decrement the
50617     ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
50618     */
50619     assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
50620     rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
50621     if( NEVER(rc) ){
50622       releasePage(pRoot);
50623       return rc;
50624     }
50625
50626   }else{
50627     rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
50628     if( rc ) return rc;
50629   }
50630 #endif
50631   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
50632   zeroPage(pRoot, flags | PTF_LEAF);
50633   sqlite3PagerUnref(pRoot->pDbPage);
50634   *piTable = (int)pgnoRoot;
50635   return SQLITE_OK;
50636 }
50637 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
50638   int rc;
50639   sqlite3BtreeEnter(p);
50640   rc = btreeCreateTable(p, piTable, flags);
50641   sqlite3BtreeLeave(p);
50642   return rc;
50643 }
50644
50645 /*
50646 ** Erase the given database page and all its children.  Return
50647 ** the page to the freelist.
50648 */
50649 static int clearDatabasePage(
50650   BtShared *pBt,           /* The BTree that contains the table */
50651   Pgno pgno,               /* Page number to clear */
50652   int freePageFlag,        /* Deallocate page if true */
50653   int *pnChange            /* Add number of Cells freed to this counter */
50654 ){
50655   MemPage *pPage;
50656   int rc;
50657   unsigned char *pCell;
50658   int i;
50659
50660   assert( sqlite3_mutex_held(pBt->mutex) );
50661   if( pgno>btreePagecount(pBt) ){
50662     return SQLITE_CORRUPT_BKPT;
50663   }
50664
50665   rc = getAndInitPage(pBt, pgno, &pPage);
50666   if( rc ) return rc;
50667   for(i=0; i<pPage->nCell; i++){
50668     pCell = findCell(pPage, i);
50669     if( !pPage->leaf ){
50670       rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
50671       if( rc ) goto cleardatabasepage_out;
50672     }
50673     rc = clearCell(pPage, pCell);
50674     if( rc ) goto cleardatabasepage_out;
50675   }
50676   if( !pPage->leaf ){
50677     rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
50678     if( rc ) goto cleardatabasepage_out;
50679   }else if( pnChange ){
50680     assert( pPage->intKey );
50681     *pnChange += pPage->nCell;
50682   }
50683   if( freePageFlag ){
50684     freePage(pPage, &rc);
50685   }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
50686     zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
50687   }
50688
50689 cleardatabasepage_out:
50690   releasePage(pPage);
50691   return rc;
50692 }
50693
50694 /*
50695 ** Delete all information from a single table in the database.  iTable is
50696 ** the page number of the root of the table.  After this routine returns,
50697 ** the root page is empty, but still exists.
50698 **
50699 ** This routine will fail with SQLITE_LOCKED if there are any open
50700 ** read cursors on the table.  Open write cursors are moved to the
50701 ** root of the table.
50702 **
50703 ** If pnChange is not NULL, then table iTable must be an intkey table. The
50704 ** integer value pointed to by pnChange is incremented by the number of
50705 ** entries in the table.
50706 */
50707 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
50708   int rc;
50709   BtShared *pBt = p->pBt;
50710   sqlite3BtreeEnter(p);
50711   assert( p->inTrans==TRANS_WRITE );
50712
50713   /* Invalidate all incrblob cursors open on table iTable (assuming iTable
50714   ** is the root of a table b-tree - if it is not, the following call is
50715   ** a no-op).  */
50716   invalidateIncrblobCursors(p, 0, 1);
50717
50718   rc = saveAllCursors(pBt, (Pgno)iTable, 0);
50719   if( SQLITE_OK==rc ){
50720     rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
50721   }
50722   sqlite3BtreeLeave(p);
50723   return rc;
50724 }
50725
50726 /*
50727 ** Erase all information in a table and add the root of the table to
50728 ** the freelist.  Except, the root of the principle table (the one on
50729 ** page 1) is never added to the freelist.
50730 **
50731 ** This routine will fail with SQLITE_LOCKED if there are any open
50732 ** cursors on the table.
50733 **
50734 ** If AUTOVACUUM is enabled and the page at iTable is not the last
50735 ** root page in the database file, then the last root page 
50736 ** in the database file is moved into the slot formerly occupied by
50737 ** iTable and that last slot formerly occupied by the last root page
50738 ** is added to the freelist instead of iTable.  In this say, all
50739 ** root pages are kept at the beginning of the database file, which
50740 ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the 
50741 ** page number that used to be the last root page in the file before
50742 ** the move.  If no page gets moved, *piMoved is set to 0.
50743 ** The last root page is recorded in meta[3] and the value of
50744 ** meta[3] is updated by this procedure.
50745 */
50746 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
50747   int rc;
50748   MemPage *pPage = 0;
50749   BtShared *pBt = p->pBt;
50750
50751   assert( sqlite3BtreeHoldsMutex(p) );
50752   assert( p->inTrans==TRANS_WRITE );
50753
50754   /* It is illegal to drop a table if any cursors are open on the
50755   ** database. This is because in auto-vacuum mode the backend may
50756   ** need to move another root-page to fill a gap left by the deleted
50757   ** root page. If an open cursor was using this page a problem would 
50758   ** occur.
50759   **
50760   ** This error is caught long before control reaches this point.
50761   */
50762   if( NEVER(pBt->pCursor) ){
50763     sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
50764     return SQLITE_LOCKED_SHAREDCACHE;
50765   }
50766
50767   rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
50768   if( rc ) return rc;
50769   rc = sqlite3BtreeClearTable(p, iTable, 0);
50770   if( rc ){
50771     releasePage(pPage);
50772     return rc;
50773   }
50774
50775   *piMoved = 0;
50776
50777   if( iTable>1 ){
50778 #ifdef SQLITE_OMIT_AUTOVACUUM
50779     freePage(pPage, &rc);
50780     releasePage(pPage);
50781 #else
50782     if( pBt->autoVacuum ){
50783       Pgno maxRootPgno;
50784       sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
50785
50786       if( iTable==maxRootPgno ){
50787         /* If the table being dropped is the table with the largest root-page
50788         ** number in the database, put the root page on the free list. 
50789         */
50790         freePage(pPage, &rc);
50791         releasePage(pPage);
50792         if( rc!=SQLITE_OK ){
50793           return rc;
50794         }
50795       }else{
50796         /* The table being dropped does not have the largest root-page
50797         ** number in the database. So move the page that does into the 
50798         ** gap left by the deleted root-page.
50799         */
50800         MemPage *pMove;
50801         releasePage(pPage);
50802         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
50803         if( rc!=SQLITE_OK ){
50804           return rc;
50805         }
50806         rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
50807         releasePage(pMove);
50808         if( rc!=SQLITE_OK ){
50809           return rc;
50810         }
50811         pMove = 0;
50812         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
50813         freePage(pMove, &rc);
50814         releasePage(pMove);
50815         if( rc!=SQLITE_OK ){
50816           return rc;
50817         }
50818         *piMoved = maxRootPgno;
50819       }
50820
50821       /* Set the new 'max-root-page' value in the database header. This
50822       ** is the old value less one, less one more if that happens to
50823       ** be a root-page number, less one again if that is the
50824       ** PENDING_BYTE_PAGE.
50825       */
50826       maxRootPgno--;
50827       while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
50828              || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
50829         maxRootPgno--;
50830       }
50831       assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
50832
50833       rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
50834     }else{
50835       freePage(pPage, &rc);
50836       releasePage(pPage);
50837     }
50838 #endif
50839   }else{
50840     /* If sqlite3BtreeDropTable was called on page 1.
50841     ** This really never should happen except in a corrupt
50842     ** database. 
50843     */
50844     zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
50845     releasePage(pPage);
50846   }
50847   return rc;  
50848 }
50849 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
50850   int rc;
50851   sqlite3BtreeEnter(p);
50852   rc = btreeDropTable(p, iTable, piMoved);
50853   sqlite3BtreeLeave(p);
50854   return rc;
50855 }
50856
50857
50858 /*
50859 ** This function may only be called if the b-tree connection already
50860 ** has a read or write transaction open on the database.
50861 **
50862 ** Read the meta-information out of a database file.  Meta[0]
50863 ** is the number of free pages currently in the database.  Meta[1]
50864 ** through meta[15] are available for use by higher layers.  Meta[0]
50865 ** is read-only, the others are read/write.
50866 ** 
50867 ** The schema layer numbers meta values differently.  At the schema
50868 ** layer (and the SetCookie and ReadCookie opcodes) the number of
50869 ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
50870 */
50871 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
50872   BtShared *pBt = p->pBt;
50873
50874   sqlite3BtreeEnter(p);
50875   assert( p->inTrans>TRANS_NONE );
50876   assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
50877   assert( pBt->pPage1 );
50878   assert( idx>=0 && idx<=15 );
50879
50880   *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
50881
50882   /* If auto-vacuum is disabled in this build and this is an auto-vacuum
50883   ** database, mark the database as read-only.  */
50884 #ifdef SQLITE_OMIT_AUTOVACUUM
50885   if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ) pBt->readOnly = 1;
50886 #endif
50887
50888   sqlite3BtreeLeave(p);
50889 }
50890
50891 /*
50892 ** Write meta-information back into the database.  Meta[0] is
50893 ** read-only and may not be written.
50894 */
50895 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
50896   BtShared *pBt = p->pBt;
50897   unsigned char *pP1;
50898   int rc;
50899   assert( idx>=1 && idx<=15 );
50900   sqlite3BtreeEnter(p);
50901   assert( p->inTrans==TRANS_WRITE );
50902   assert( pBt->pPage1!=0 );
50903   pP1 = pBt->pPage1->aData;
50904   rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
50905   if( rc==SQLITE_OK ){
50906     put4byte(&pP1[36 + idx*4], iMeta);
50907 #ifndef SQLITE_OMIT_AUTOVACUUM
50908     if( idx==BTREE_INCR_VACUUM ){
50909       assert( pBt->autoVacuum || iMeta==0 );
50910       assert( iMeta==0 || iMeta==1 );
50911       pBt->incrVacuum = (u8)iMeta;
50912     }
50913 #endif
50914   }
50915   sqlite3BtreeLeave(p);
50916   return rc;
50917 }
50918
50919 #ifndef SQLITE_OMIT_BTREECOUNT
50920 /*
50921 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
50922 ** number of entries in the b-tree and write the result to *pnEntry.
50923 **
50924 ** SQLITE_OK is returned if the operation is successfully executed. 
50925 ** Otherwise, if an error is encountered (i.e. an IO error or database
50926 ** corruption) an SQLite error code is returned.
50927 */
50928 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
50929   i64 nEntry = 0;                      /* Value to return in *pnEntry */
50930   int rc;                              /* Return code */
50931   rc = moveToRoot(pCur);
50932
50933   /* Unless an error occurs, the following loop runs one iteration for each
50934   ** page in the B-Tree structure (not including overflow pages). 
50935   */
50936   while( rc==SQLITE_OK ){
50937     int iIdx;                          /* Index of child node in parent */
50938     MemPage *pPage;                    /* Current page of the b-tree */
50939
50940     /* If this is a leaf page or the tree is not an int-key tree, then 
50941     ** this page contains countable entries. Increment the entry counter
50942     ** accordingly.
50943     */
50944     pPage = pCur->apPage[pCur->iPage];
50945     if( pPage->leaf || !pPage->intKey ){
50946       nEntry += pPage->nCell;
50947     }
50948
50949     /* pPage is a leaf node. This loop navigates the cursor so that it 
50950     ** points to the first interior cell that it points to the parent of
50951     ** the next page in the tree that has not yet been visited. The
50952     ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
50953     ** of the page, or to the number of cells in the page if the next page
50954     ** to visit is the right-child of its parent.
50955     **
50956     ** If all pages in the tree have been visited, return SQLITE_OK to the
50957     ** caller.
50958     */
50959     if( pPage->leaf ){
50960       do {
50961         if( pCur->iPage==0 ){
50962           /* All pages of the b-tree have been visited. Return successfully. */
50963           *pnEntry = nEntry;
50964           return SQLITE_OK;
50965         }
50966         moveToParent(pCur);
50967       }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
50968
50969       pCur->aiIdx[pCur->iPage]++;
50970       pPage = pCur->apPage[pCur->iPage];
50971     }
50972
50973     /* Descend to the child node of the cell that the cursor currently 
50974     ** points at. This is the right-child if (iIdx==pPage->nCell).
50975     */
50976     iIdx = pCur->aiIdx[pCur->iPage];
50977     if( iIdx==pPage->nCell ){
50978       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
50979     }else{
50980       rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
50981     }
50982   }
50983
50984   /* An error has occurred. Return an error code. */
50985   return rc;
50986 }
50987 #endif
50988
50989 /*
50990 ** Return the pager associated with a BTree.  This routine is used for
50991 ** testing and debugging only.
50992 */
50993 SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
50994   return p->pBt->pPager;
50995 }
50996
50997 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
50998 /*
50999 ** Append a message to the error message string.
51000 */
51001 static void checkAppendMsg(
51002   IntegrityCk *pCheck,
51003   char *zMsg1,
51004   const char *zFormat,
51005   ...
51006 ){
51007   va_list ap;
51008   if( !pCheck->mxErr ) return;
51009   pCheck->mxErr--;
51010   pCheck->nErr++;
51011   va_start(ap, zFormat);
51012   if( pCheck->errMsg.nChar ){
51013     sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
51014   }
51015   if( zMsg1 ){
51016     sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
51017   }
51018   sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
51019   va_end(ap);
51020   if( pCheck->errMsg.mallocFailed ){
51021     pCheck->mallocFailed = 1;
51022   }
51023 }
51024 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
51025
51026 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
51027 /*
51028 ** Add 1 to the reference count for page iPage.  If this is the second
51029 ** reference to the page, add an error message to pCheck->zErrMsg.
51030 ** Return 1 if there are 2 ore more references to the page and 0 if
51031 ** if this is the first reference to the page.
51032 **
51033 ** Also check that the page number is in bounds.
51034 */
51035 static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
51036   if( iPage==0 ) return 1;
51037   if( iPage>pCheck->nPage ){
51038     checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
51039     return 1;
51040   }
51041   if( pCheck->anRef[iPage]==1 ){
51042     checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
51043     return 1;
51044   }
51045   return  (pCheck->anRef[iPage]++)>1;
51046 }
51047
51048 #ifndef SQLITE_OMIT_AUTOVACUUM
51049 /*
51050 ** Check that the entry in the pointer-map for page iChild maps to 
51051 ** page iParent, pointer type ptrType. If not, append an error message
51052 ** to pCheck.
51053 */
51054 static void checkPtrmap(
51055   IntegrityCk *pCheck,   /* Integrity check context */
51056   Pgno iChild,           /* Child page number */
51057   u8 eType,              /* Expected pointer map type */
51058   Pgno iParent,          /* Expected pointer map parent page number */
51059   char *zContext         /* Context description (used for error msg) */
51060 ){
51061   int rc;
51062   u8 ePtrmapType;
51063   Pgno iPtrmapParent;
51064
51065   rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
51066   if( rc!=SQLITE_OK ){
51067     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
51068     checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
51069     return;
51070   }
51071
51072   if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
51073     checkAppendMsg(pCheck, zContext, 
51074       "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)", 
51075       iChild, eType, iParent, ePtrmapType, iPtrmapParent);
51076   }
51077 }
51078 #endif
51079
51080 /*
51081 ** Check the integrity of the freelist or of an overflow page list.
51082 ** Verify that the number of pages on the list is N.
51083 */
51084 static void checkList(
51085   IntegrityCk *pCheck,  /* Integrity checking context */
51086   int isFreeList,       /* True for a freelist.  False for overflow page list */
51087   int iPage,            /* Page number for first page in the list */
51088   int N,                /* Expected number of pages in the list */
51089   char *zContext        /* Context for error messages */
51090 ){
51091   int i;
51092   int expected = N;
51093   int iFirst = iPage;
51094   while( N-- > 0 && pCheck->mxErr ){
51095     DbPage *pOvflPage;
51096     unsigned char *pOvflData;
51097     if( iPage<1 ){
51098       checkAppendMsg(pCheck, zContext,
51099          "%d of %d pages missing from overflow list starting at %d",
51100           N+1, expected, iFirst);
51101       break;
51102     }
51103     if( checkRef(pCheck, iPage, zContext) ) break;
51104     if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
51105       checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
51106       break;
51107     }
51108     pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
51109     if( isFreeList ){
51110       int n = get4byte(&pOvflData[4]);
51111 #ifndef SQLITE_OMIT_AUTOVACUUM
51112       if( pCheck->pBt->autoVacuum ){
51113         checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
51114       }
51115 #endif
51116       if( n>pCheck->pBt->usableSize/4-2 ){
51117         checkAppendMsg(pCheck, zContext,
51118            "freelist leaf count too big on page %d", iPage);
51119         N--;
51120       }else{
51121         for(i=0; i<n; i++){
51122           Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
51123 #ifndef SQLITE_OMIT_AUTOVACUUM
51124           if( pCheck->pBt->autoVacuum ){
51125             checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
51126           }
51127 #endif
51128           checkRef(pCheck, iFreePage, zContext);
51129         }
51130         N -= n;
51131       }
51132     }
51133 #ifndef SQLITE_OMIT_AUTOVACUUM
51134     else{
51135       /* If this database supports auto-vacuum and iPage is not the last
51136       ** page in this overflow list, check that the pointer-map entry for
51137       ** the following page matches iPage.
51138       */
51139       if( pCheck->pBt->autoVacuum && N>0 ){
51140         i = get4byte(pOvflData);
51141         checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
51142       }
51143     }
51144 #endif
51145     iPage = get4byte(pOvflData);
51146     sqlite3PagerUnref(pOvflPage);
51147   }
51148 }
51149 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
51150
51151 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
51152 /*
51153 ** Do various sanity checks on a single page of a tree.  Return
51154 ** the tree depth.  Root pages return 0.  Parents of root pages
51155 ** return 1, and so forth.
51156 ** 
51157 ** These checks are done:
51158 **
51159 **      1.  Make sure that cells and freeblocks do not overlap
51160 **          but combine to completely cover the page.
51161 **  NO  2.  Make sure cell keys are in order.
51162 **  NO  3.  Make sure no key is less than or equal to zLowerBound.
51163 **  NO  4.  Make sure no key is greater than or equal to zUpperBound.
51164 **      5.  Check the integrity of overflow pages.
51165 **      6.  Recursively call checkTreePage on all children.
51166 **      7.  Verify that the depth of all children is the same.
51167 **      8.  Make sure this page is at least 33% full or else it is
51168 **          the root of the tree.
51169 */
51170 static int checkTreePage(
51171   IntegrityCk *pCheck,  /* Context for the sanity check */
51172   int iPage,            /* Page number of the page to check */
51173   char *zParentContext, /* Parent context */
51174   i64 *pnParentMinKey, 
51175   i64 *pnParentMaxKey
51176 ){
51177   MemPage *pPage;
51178   int i, rc, depth, d2, pgno, cnt;
51179   int hdr, cellStart;
51180   int nCell;
51181   u8 *data;
51182   BtShared *pBt;
51183   int usableSize;
51184   char zContext[100];
51185   char *hit = 0;
51186   i64 nMinKey = 0;
51187   i64 nMaxKey = 0;
51188
51189   sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
51190
51191   /* Check that the page exists
51192   */
51193   pBt = pCheck->pBt;
51194   usableSize = pBt->usableSize;
51195   if( iPage==0 ) return 0;
51196   if( checkRef(pCheck, iPage, zParentContext) ) return 0;
51197   if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
51198     checkAppendMsg(pCheck, zContext,
51199        "unable to get the page. error code=%d", rc);
51200     return 0;
51201   }
51202
51203   /* Clear MemPage.isInit to make sure the corruption detection code in
51204   ** btreeInitPage() is executed.  */
51205   pPage->isInit = 0;
51206   if( (rc = btreeInitPage(pPage))!=0 ){
51207     assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
51208     checkAppendMsg(pCheck, zContext, 
51209                    "btreeInitPage() returns error code %d", rc);
51210     releasePage(pPage);
51211     return 0;
51212   }
51213
51214   /* Check out all the cells.
51215   */
51216   depth = 0;
51217   for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
51218     u8 *pCell;
51219     u32 sz;
51220     CellInfo info;
51221
51222     /* Check payload overflow pages
51223     */
51224     sqlite3_snprintf(sizeof(zContext), zContext,
51225              "On tree page %d cell %d: ", iPage, i);
51226     pCell = findCell(pPage,i);
51227     btreeParseCellPtr(pPage, pCell, &info);
51228     sz = info.nData;
51229     if( !pPage->intKey ) sz += (int)info.nKey;
51230     /* For intKey pages, check that the keys are in order.
51231     */
51232     else if( i==0 ) nMinKey = nMaxKey = info.nKey;
51233     else{
51234       if( info.nKey <= nMaxKey ){
51235         checkAppendMsg(pCheck, zContext, 
51236             "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
51237       }
51238       nMaxKey = info.nKey;
51239     }
51240     assert( sz==info.nPayload );
51241     if( (sz>info.nLocal) 
51242      && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
51243     ){
51244       int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
51245       Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
51246 #ifndef SQLITE_OMIT_AUTOVACUUM
51247       if( pBt->autoVacuum ){
51248         checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
51249       }
51250 #endif
51251       checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
51252     }
51253
51254     /* Check sanity of left child page.
51255     */
51256     if( !pPage->leaf ){
51257       pgno = get4byte(pCell);
51258 #ifndef SQLITE_OMIT_AUTOVACUUM
51259       if( pBt->autoVacuum ){
51260         checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
51261       }
51262 #endif
51263       d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
51264       if( i>0 && d2!=depth ){
51265         checkAppendMsg(pCheck, zContext, "Child page depth differs");
51266       }
51267       depth = d2;
51268     }
51269   }
51270
51271   if( !pPage->leaf ){
51272     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
51273     sqlite3_snprintf(sizeof(zContext), zContext, 
51274                      "On page %d at right child: ", iPage);
51275 #ifndef SQLITE_OMIT_AUTOVACUUM
51276     if( pBt->autoVacuum ){
51277       checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
51278     }
51279 #endif
51280     checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
51281   }
51282  
51283   /* For intKey leaf pages, check that the min/max keys are in order
51284   ** with any left/parent/right pages.
51285   */
51286   if( pPage->leaf && pPage->intKey ){
51287     /* if we are a left child page */
51288     if( pnParentMinKey ){
51289       /* if we are the left most child page */
51290       if( !pnParentMaxKey ){
51291         if( nMaxKey > *pnParentMinKey ){
51292           checkAppendMsg(pCheck, zContext, 
51293               "Rowid %lld out of order (max larger than parent min of %lld)",
51294               nMaxKey, *pnParentMinKey);
51295         }
51296       }else{
51297         if( nMinKey <= *pnParentMinKey ){
51298           checkAppendMsg(pCheck, zContext, 
51299               "Rowid %lld out of order (min less than parent min of %lld)",
51300               nMinKey, *pnParentMinKey);
51301         }
51302         if( nMaxKey > *pnParentMaxKey ){
51303           checkAppendMsg(pCheck, zContext, 
51304               "Rowid %lld out of order (max larger than parent max of %lld)",
51305               nMaxKey, *pnParentMaxKey);
51306         }
51307         *pnParentMinKey = nMaxKey;
51308       }
51309     /* else if we're a right child page */
51310     } else if( pnParentMaxKey ){
51311       if( nMinKey <= *pnParentMaxKey ){
51312         checkAppendMsg(pCheck, zContext, 
51313             "Rowid %lld out of order (min less than parent max of %lld)",
51314             nMinKey, *pnParentMaxKey);
51315       }
51316     }
51317   }
51318
51319   /* Check for complete coverage of the page
51320   */
51321   data = pPage->aData;
51322   hdr = pPage->hdrOffset;
51323   hit = sqlite3PageMalloc( pBt->pageSize );
51324   if( hit==0 ){
51325     pCheck->mallocFailed = 1;
51326   }else{
51327     u16 contentOffset = get2byte(&data[hdr+5]);
51328     assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
51329     memset(hit+contentOffset, 0, usableSize-contentOffset);
51330     memset(hit, 1, contentOffset);
51331     nCell = get2byte(&data[hdr+3]);
51332     cellStart = hdr + 12 - 4*pPage->leaf;
51333     for(i=0; i<nCell; i++){
51334       int pc = get2byte(&data[cellStart+i*2]);
51335       u16 size = 1024;
51336       int j;
51337       if( pc<=usableSize-4 ){
51338         size = cellSizePtr(pPage, &data[pc]);
51339       }
51340       if( (pc+size-1)>=usableSize ){
51341         checkAppendMsg(pCheck, 0, 
51342             "Corruption detected in cell %d on page %d",i,iPage);
51343       }else{
51344         for(j=pc+size-1; j>=pc; j--) hit[j]++;
51345       }
51346     }
51347     i = get2byte(&data[hdr+1]);
51348     while( i>0 ){
51349       int size, j;
51350       assert( i<=usableSize-4 );     /* Enforced by btreeInitPage() */
51351       size = get2byte(&data[i+2]);
51352       assert( i+size<=usableSize );  /* Enforced by btreeInitPage() */
51353       for(j=i+size-1; j>=i; j--) hit[j]++;
51354       j = get2byte(&data[i]);
51355       assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
51356       assert( j<=usableSize-4 );   /* Enforced by btreeInitPage() */
51357       i = j;
51358     }
51359     for(i=cnt=0; i<usableSize; i++){
51360       if( hit[i]==0 ){
51361         cnt++;
51362       }else if( hit[i]>1 ){
51363         checkAppendMsg(pCheck, 0,
51364           "Multiple uses for byte %d of page %d", i, iPage);
51365         break;
51366       }
51367     }
51368     if( cnt!=data[hdr+7] ){
51369       checkAppendMsg(pCheck, 0, 
51370           "Fragmentation of %d bytes reported as %d on page %d",
51371           cnt, data[hdr+7], iPage);
51372     }
51373   }
51374   sqlite3PageFree(hit);
51375   releasePage(pPage);
51376   return depth+1;
51377 }
51378 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
51379
51380 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
51381 /*
51382 ** This routine does a complete check of the given BTree file.  aRoot[] is
51383 ** an array of pages numbers were each page number is the root page of
51384 ** a table.  nRoot is the number of entries in aRoot.
51385 **
51386 ** A read-only or read-write transaction must be opened before calling
51387 ** this function.
51388 **
51389 ** Write the number of error seen in *pnErr.  Except for some memory
51390 ** allocation errors,  an error message held in memory obtained from
51391 ** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
51392 ** returned.  If a memory allocation error occurs, NULL is returned.
51393 */
51394 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
51395   Btree *p,     /* The btree to be checked */
51396   int *aRoot,   /* An array of root pages numbers for individual trees */
51397   int nRoot,    /* Number of entries in aRoot[] */
51398   int mxErr,    /* Stop reporting errors after this many */
51399   int *pnErr    /* Write number of errors seen to this variable */
51400 ){
51401   Pgno i;
51402   int nRef;
51403   IntegrityCk sCheck;
51404   BtShared *pBt = p->pBt;
51405   char zErr[100];
51406
51407   sqlite3BtreeEnter(p);
51408   assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
51409   nRef = sqlite3PagerRefcount(pBt->pPager);
51410   sCheck.pBt = pBt;
51411   sCheck.pPager = pBt->pPager;
51412   sCheck.nPage = btreePagecount(sCheck.pBt);
51413   sCheck.mxErr = mxErr;
51414   sCheck.nErr = 0;
51415   sCheck.mallocFailed = 0;
51416   *pnErr = 0;
51417   if( sCheck.nPage==0 ){
51418     sqlite3BtreeLeave(p);
51419     return 0;
51420   }
51421   sCheck.anRef = sqlite3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
51422   if( !sCheck.anRef ){
51423     *pnErr = 1;
51424     sqlite3BtreeLeave(p);
51425     return 0;
51426   }
51427   for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
51428   i = PENDING_BYTE_PAGE(pBt);
51429   if( i<=sCheck.nPage ){
51430     sCheck.anRef[i] = 1;
51431   }
51432   sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
51433
51434   /* Check the integrity of the freelist
51435   */
51436   checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
51437             get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
51438
51439   /* Check all the tables.
51440   */
51441   for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
51442     if( aRoot[i]==0 ) continue;
51443 #ifndef SQLITE_OMIT_AUTOVACUUM
51444     if( pBt->autoVacuum && aRoot[i]>1 ){
51445       checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
51446     }
51447 #endif
51448     checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
51449   }
51450
51451   /* Make sure every page in the file is referenced
51452   */
51453   for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
51454 #ifdef SQLITE_OMIT_AUTOVACUUM
51455     if( sCheck.anRef[i]==0 ){
51456       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
51457     }
51458 #else
51459     /* If the database supports auto-vacuum, make sure no tables contain
51460     ** references to pointer-map pages.
51461     */
51462     if( sCheck.anRef[i]==0 && 
51463        (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
51464       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
51465     }
51466     if( sCheck.anRef[i]!=0 && 
51467        (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
51468       checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
51469     }
51470 #endif
51471   }
51472
51473   /* Make sure this analysis did not leave any unref() pages.
51474   ** This is an internal consistency check; an integrity check
51475   ** of the integrity check.
51476   */
51477   if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
51478     checkAppendMsg(&sCheck, 0, 
51479       "Outstanding page count goes from %d to %d during this analysis",
51480       nRef, sqlite3PagerRefcount(pBt->pPager)
51481     );
51482   }
51483
51484   /* Clean  up and report errors.
51485   */
51486   sqlite3BtreeLeave(p);
51487   sqlite3_free(sCheck.anRef);
51488   if( sCheck.mallocFailed ){
51489     sqlite3StrAccumReset(&sCheck.errMsg);
51490     *pnErr = sCheck.nErr+1;
51491     return 0;
51492   }
51493   *pnErr = sCheck.nErr;
51494   if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
51495   return sqlite3StrAccumFinish(&sCheck.errMsg);
51496 }
51497 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
51498
51499 /*
51500 ** Return the full pathname of the underlying database file.
51501 **
51502 ** The pager filename is invariant as long as the pager is
51503 ** open so it is safe to access without the BtShared mutex.
51504 */
51505 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
51506   assert( p->pBt->pPager!=0 );
51507   return sqlite3PagerFilename(p->pBt->pPager);
51508 }
51509
51510 /*
51511 ** Return the pathname of the journal file for this database. The return
51512 ** value of this routine is the same regardless of whether the journal file
51513 ** has been created or not.
51514 **
51515 ** The pager journal filename is invariant as long as the pager is
51516 ** open so it is safe to access without the BtShared mutex.
51517 */
51518 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
51519   assert( p->pBt->pPager!=0 );
51520   return sqlite3PagerJournalname(p->pBt->pPager);
51521 }
51522
51523 /*
51524 ** Return non-zero if a transaction is active.
51525 */
51526 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
51527   assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
51528   return (p && (p->inTrans==TRANS_WRITE));
51529 }
51530
51531 /*
51532 ** Return non-zero if a read (or write) transaction is active.
51533 */
51534 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
51535   assert( p );
51536   assert( sqlite3_mutex_held(p->db->mutex) );
51537   return p->inTrans!=TRANS_NONE;
51538 }
51539
51540 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
51541   assert( p );
51542   assert( sqlite3_mutex_held(p->db->mutex) );
51543   return p->nBackup!=0;
51544 }
51545
51546 /*
51547 ** This function returns a pointer to a blob of memory associated with
51548 ** a single shared-btree. The memory is used by client code for its own
51549 ** purposes (for example, to store a high-level schema associated with 
51550 ** the shared-btree). The btree layer manages reference counting issues.
51551 **
51552 ** The first time this is called on a shared-btree, nBytes bytes of memory
51553 ** are allocated, zeroed, and returned to the caller. For each subsequent 
51554 ** call the nBytes parameter is ignored and a pointer to the same blob
51555 ** of memory returned. 
51556 **
51557 ** If the nBytes parameter is 0 and the blob of memory has not yet been
51558 ** allocated, a null pointer is returned. If the blob has already been
51559 ** allocated, it is returned as normal.
51560 **
51561 ** Just before the shared-btree is closed, the function passed as the 
51562 ** xFree argument when the memory allocation was made is invoked on the 
51563 ** blob of allocated memory. This function should not call sqlite3_free()
51564 ** on the memory, the btree layer does that.
51565 */
51566 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
51567   BtShared *pBt = p->pBt;
51568   sqlite3BtreeEnter(p);
51569   if( !pBt->pSchema && nBytes ){
51570     pBt->pSchema = sqlite3MallocZero(nBytes);
51571     pBt->xFreeSchema = xFree;
51572   }
51573   sqlite3BtreeLeave(p);
51574   return pBt->pSchema;
51575 }
51576
51577 /*
51578 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared 
51579 ** btree as the argument handle holds an exclusive lock on the 
51580 ** sqlite_master table. Otherwise SQLITE_OK.
51581 */
51582 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
51583   int rc;
51584   assert( sqlite3_mutex_held(p->db->mutex) );
51585   sqlite3BtreeEnter(p);
51586   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
51587   assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
51588   sqlite3BtreeLeave(p);
51589   return rc;
51590 }
51591
51592
51593 #ifndef SQLITE_OMIT_SHARED_CACHE
51594 /*
51595 ** Obtain a lock on the table whose root page is iTab.  The
51596 ** lock is a write lock if isWritelock is true or a read lock
51597 ** if it is false.
51598 */
51599 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
51600   int rc = SQLITE_OK;
51601   assert( p->inTrans!=TRANS_NONE );
51602   if( p->sharable ){
51603     u8 lockType = READ_LOCK + isWriteLock;
51604     assert( READ_LOCK+1==WRITE_LOCK );
51605     assert( isWriteLock==0 || isWriteLock==1 );
51606
51607     sqlite3BtreeEnter(p);
51608     rc = querySharedCacheTableLock(p, iTab, lockType);
51609     if( rc==SQLITE_OK ){
51610       rc = setSharedCacheTableLock(p, iTab, lockType);
51611     }
51612     sqlite3BtreeLeave(p);
51613   }
51614   return rc;
51615 }
51616 #endif
51617
51618 #ifndef SQLITE_OMIT_INCRBLOB
51619 /*
51620 ** Argument pCsr must be a cursor opened for writing on an 
51621 ** INTKEY table currently pointing at a valid table entry. 
51622 ** This function modifies the data stored as part of that entry.
51623 **
51624 ** Only the data content may only be modified, it is not possible to 
51625 ** change the length of the data stored. If this function is called with
51626 ** parameters that attempt to write past the end of the existing data,
51627 ** no modifications are made and SQLITE_CORRUPT is returned.
51628 */
51629 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
51630   int rc;
51631   assert( cursorHoldsMutex(pCsr) );
51632   assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
51633   assert( pCsr->isIncrblobHandle );
51634
51635   rc = restoreCursorPosition(pCsr);
51636   if( rc!=SQLITE_OK ){
51637     return rc;
51638   }
51639   assert( pCsr->eState!=CURSOR_REQUIRESEEK );
51640   if( pCsr->eState!=CURSOR_VALID ){
51641     return SQLITE_ABORT;
51642   }
51643
51644   /* Check some assumptions: 
51645   **   (a) the cursor is open for writing,
51646   **   (b) there is a read/write transaction open,
51647   **   (c) the connection holds a write-lock on the table (if required),
51648   **   (d) there are no conflicting read-locks, and
51649   **   (e) the cursor points at a valid row of an intKey table.
51650   */
51651   if( !pCsr->wrFlag ){
51652     return SQLITE_READONLY;
51653   }
51654   assert( !pCsr->pBt->readOnly && pCsr->pBt->inTransaction==TRANS_WRITE );
51655   assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
51656   assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
51657   assert( pCsr->apPage[pCsr->iPage]->intKey );
51658
51659   return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
51660 }
51661
51662 /* 
51663 ** Set a flag on this cursor to cache the locations of pages from the 
51664 ** overflow list for the current row. This is used by cursors opened
51665 ** for incremental blob IO only.
51666 **
51667 ** This function sets a flag only. The actual page location cache
51668 ** (stored in BtCursor.aOverflow[]) is allocated and used by function
51669 ** accessPayload() (the worker function for sqlite3BtreeData() and
51670 ** sqlite3BtreePutData()).
51671 */
51672 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
51673   assert( cursorHoldsMutex(pCur) );
51674   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
51675   assert(!pCur->isIncrblobHandle);
51676   assert(!pCur->aOverflow);
51677   pCur->isIncrblobHandle = 1;
51678 }
51679 #endif
51680
51681 /*
51682 ** Set both the "read version" (single byte at byte offset 18) and 
51683 ** "write version" (single byte at byte offset 19) fields in the database
51684 ** header to iVersion.
51685 */
51686 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
51687   BtShared *pBt = pBtree->pBt;
51688   int rc;                         /* Return code */
51689  
51690   assert( pBtree->inTrans==TRANS_NONE );
51691   assert( iVersion==1 || iVersion==2 );
51692
51693   /* If setting the version fields to 1, do not automatically open the
51694   ** WAL connection, even if the version fields are currently set to 2.
51695   */
51696   pBt->doNotUseWAL = (u8)(iVersion==1);
51697
51698   rc = sqlite3BtreeBeginTrans(pBtree, 0);
51699   if( rc==SQLITE_OK ){
51700     u8 *aData = pBt->pPage1->aData;
51701     if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
51702       rc = sqlite3BtreeBeginTrans(pBtree, 2);
51703       if( rc==SQLITE_OK ){
51704         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
51705         if( rc==SQLITE_OK ){
51706           aData[18] = (u8)iVersion;
51707           aData[19] = (u8)iVersion;
51708         }
51709       }
51710     }
51711   }
51712
51713   pBt->doNotUseWAL = 0;
51714   return rc;
51715 }
51716
51717 /************** End of btree.c ***********************************************/
51718 /************** Begin file backup.c ******************************************/
51719 /*
51720 ** 2009 January 28
51721 **
51722 ** The author disclaims copyright to this source code.  In place of
51723 ** a legal notice, here is a blessing:
51724 **
51725 **    May you do good and not evil.
51726 **    May you find forgiveness for yourself and forgive others.
51727 **    May you share freely, never taking more than you give.
51728 **
51729 *************************************************************************
51730 ** This file contains the implementation of the sqlite3_backup_XXX() 
51731 ** API functions and the related features.
51732 */
51733
51734 /* Macro to find the minimum of two numeric values.
51735 */
51736 #ifndef MIN
51737 # define MIN(x,y) ((x)<(y)?(x):(y))
51738 #endif
51739
51740 /*
51741 ** Structure allocated for each backup operation.
51742 */
51743 struct sqlite3_backup {
51744   sqlite3* pDestDb;        /* Destination database handle */
51745   Btree *pDest;            /* Destination b-tree file */
51746   u32 iDestSchema;         /* Original schema cookie in destination */
51747   int bDestLocked;         /* True once a write-transaction is open on pDest */
51748
51749   Pgno iNext;              /* Page number of the next source page to copy */
51750   sqlite3* pSrcDb;         /* Source database handle */
51751   Btree *pSrc;             /* Source b-tree file */
51752
51753   int rc;                  /* Backup process error code */
51754
51755   /* These two variables are set by every call to backup_step(). They are
51756   ** read by calls to backup_remaining() and backup_pagecount().
51757   */
51758   Pgno nRemaining;         /* Number of pages left to copy */
51759   Pgno nPagecount;         /* Total number of pages to copy */
51760
51761   int isAttached;          /* True once backup has been registered with pager */
51762   sqlite3_backup *pNext;   /* Next backup associated with source pager */
51763 };
51764
51765 /*
51766 ** THREAD SAFETY NOTES:
51767 **
51768 **   Once it has been created using backup_init(), a single sqlite3_backup
51769 **   structure may be accessed via two groups of thread-safe entry points:
51770 **
51771 **     * Via the sqlite3_backup_XXX() API function backup_step() and 
51772 **       backup_finish(). Both these functions obtain the source database
51773 **       handle mutex and the mutex associated with the source BtShared 
51774 **       structure, in that order.
51775 **
51776 **     * Via the BackupUpdate() and BackupRestart() functions, which are
51777 **       invoked by the pager layer to report various state changes in
51778 **       the page cache associated with the source database. The mutex
51779 **       associated with the source database BtShared structure will always 
51780 **       be held when either of these functions are invoked.
51781 **
51782 **   The other sqlite3_backup_XXX() API functions, backup_remaining() and
51783 **   backup_pagecount() are not thread-safe functions. If they are called
51784 **   while some other thread is calling backup_step() or backup_finish(),
51785 **   the values returned may be invalid. There is no way for a call to
51786 **   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
51787 **   or backup_pagecount().
51788 **
51789 **   Depending on the SQLite configuration, the database handles and/or
51790 **   the Btree objects may have their own mutexes that require locking.
51791 **   Non-sharable Btrees (in-memory databases for example), do not have
51792 **   associated mutexes.
51793 */
51794
51795 /*
51796 ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
51797 ** in connection handle pDb. If such a database cannot be found, return
51798 ** a NULL pointer and write an error message to pErrorDb.
51799 **
51800 ** If the "temp" database is requested, it may need to be opened by this 
51801 ** function. If an error occurs while doing so, return 0 and write an 
51802 ** error message to pErrorDb.
51803 */
51804 static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
51805   int i = sqlite3FindDbName(pDb, zDb);
51806
51807   if( i==1 ){
51808     Parse *pParse;
51809     int rc = 0;
51810     pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
51811     if( pParse==0 ){
51812       sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
51813       rc = SQLITE_NOMEM;
51814     }else{
51815       pParse->db = pDb;
51816       if( sqlite3OpenTempDatabase(pParse) ){
51817         sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
51818         rc = SQLITE_ERROR;
51819       }
51820       sqlite3DbFree(pErrorDb, pParse->zErrMsg);
51821       sqlite3StackFree(pErrorDb, pParse);
51822     }
51823     if( rc ){
51824       return 0;
51825     }
51826   }
51827
51828   if( i<0 ){
51829     sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
51830     return 0;
51831   }
51832
51833   return pDb->aDb[i].pBt;
51834 }
51835
51836 /*
51837 ** Create an sqlite3_backup process to copy the contents of zSrcDb from
51838 ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
51839 ** a pointer to the new sqlite3_backup object.
51840 **
51841 ** If an error occurs, NULL is returned and an error code and error message
51842 ** stored in database handle pDestDb.
51843 */
51844 SQLITE_API sqlite3_backup *sqlite3_backup_init(
51845   sqlite3* pDestDb,                     /* Database to write to */
51846   const char *zDestDb,                  /* Name of database within pDestDb */
51847   sqlite3* pSrcDb,                      /* Database connection to read from */
51848   const char *zSrcDb                    /* Name of database within pSrcDb */
51849 ){
51850   sqlite3_backup *p;                    /* Value to return */
51851
51852   /* Lock the source database handle. The destination database
51853   ** handle is not locked in this routine, but it is locked in
51854   ** sqlite3_backup_step(). The user is required to ensure that no
51855   ** other thread accesses the destination handle for the duration
51856   ** of the backup operation.  Any attempt to use the destination
51857   ** database connection while a backup is in progress may cause
51858   ** a malfunction or a deadlock.
51859   */
51860   sqlite3_mutex_enter(pSrcDb->mutex);
51861   sqlite3_mutex_enter(pDestDb->mutex);
51862
51863   if( pSrcDb==pDestDb ){
51864     sqlite3Error(
51865         pDestDb, SQLITE_ERROR, "source and destination must be distinct"
51866     );
51867     p = 0;
51868   }else {
51869     /* Allocate space for a new sqlite3_backup object */
51870     p = (sqlite3_backup *)sqlite3_malloc(sizeof(sqlite3_backup));
51871     if( !p ){
51872       sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
51873     }
51874   }
51875
51876   /* If the allocation succeeded, populate the new object. */
51877   if( p ){
51878     memset(p, 0, sizeof(sqlite3_backup));
51879     p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
51880     p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
51881     p->pDestDb = pDestDb;
51882     p->pSrcDb = pSrcDb;
51883     p->iNext = 1;
51884     p->isAttached = 0;
51885
51886     if( 0==p->pSrc || 0==p->pDest ){
51887       /* One (or both) of the named databases did not exist. An error has
51888       ** already been written into the pDestDb handle. All that is left
51889       ** to do here is free the sqlite3_backup structure.
51890       */
51891       sqlite3_free(p);
51892       p = 0;
51893     }
51894   }
51895   if( p ){
51896     p->pSrc->nBackup++;
51897   }
51898
51899   sqlite3_mutex_leave(pDestDb->mutex);
51900   sqlite3_mutex_leave(pSrcDb->mutex);
51901   return p;
51902 }
51903
51904 /*
51905 ** Argument rc is an SQLite error code. Return true if this error is 
51906 ** considered fatal if encountered during a backup operation. All errors
51907 ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
51908 */
51909 static int isFatalError(int rc){
51910   return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
51911 }
51912
51913 /*
51914 ** Parameter zSrcData points to a buffer containing the data for 
51915 ** page iSrcPg from the source database. Copy this data into the 
51916 ** destination database.
51917 */
51918 static int backupOnePage(sqlite3_backup *p, Pgno iSrcPg, const u8 *zSrcData){
51919   Pager * const pDestPager = sqlite3BtreePager(p->pDest);
51920   const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
51921   int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
51922   const int nCopy = MIN(nSrcPgsz, nDestPgsz);
51923   const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
51924
51925   int rc = SQLITE_OK;
51926   i64 iOff;
51927
51928   assert( p->bDestLocked );
51929   assert( !isFatalError(p->rc) );
51930   assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
51931   assert( zSrcData );
51932
51933   /* Catch the case where the destination is an in-memory database and the
51934   ** page sizes of the source and destination differ. 
51935   */
51936   if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
51937     rc = SQLITE_READONLY;
51938   }
51939
51940   /* This loop runs once for each destination page spanned by the source 
51941   ** page. For each iteration, variable iOff is set to the byte offset
51942   ** of the destination page.
51943   */
51944   for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
51945     DbPage *pDestPg = 0;
51946     Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
51947     if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
51948     if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
51949      && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
51950     ){
51951       const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
51952       u8 *zDestData = sqlite3PagerGetData(pDestPg);
51953       u8 *zOut = &zDestData[iOff%nDestPgsz];
51954
51955       /* Copy the data from the source page into the destination page.
51956       ** Then clear the Btree layer MemPage.isInit flag. Both this module
51957       ** and the pager code use this trick (clearing the first byte
51958       ** of the page 'extra' space to invalidate the Btree layers
51959       ** cached parse of the page). MemPage.isInit is marked 
51960       ** "MUST BE FIRST" for this purpose.
51961       */
51962       memcpy(zOut, zIn, nCopy);
51963       ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
51964     }
51965     sqlite3PagerUnref(pDestPg);
51966   }
51967
51968   return rc;
51969 }
51970
51971 /*
51972 ** If pFile is currently larger than iSize bytes, then truncate it to
51973 ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
51974 ** this function is a no-op.
51975 **
51976 ** Return SQLITE_OK if everything is successful, or an SQLite error 
51977 ** code if an error occurs.
51978 */
51979 static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
51980   i64 iCurrent;
51981   int rc = sqlite3OsFileSize(pFile, &iCurrent);
51982   if( rc==SQLITE_OK && iCurrent>iSize ){
51983     rc = sqlite3OsTruncate(pFile, iSize);
51984   }
51985   return rc;
51986 }
51987
51988 /*
51989 ** Register this backup object with the associated source pager for
51990 ** callbacks when pages are changed or the cache invalidated.
51991 */
51992 static void attachBackupObject(sqlite3_backup *p){
51993   sqlite3_backup **pp;
51994   assert( sqlite3BtreeHoldsMutex(p->pSrc) );
51995   pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
51996   p->pNext = *pp;
51997   *pp = p;
51998   p->isAttached = 1;
51999 }
52000
52001 /*
52002 ** Copy nPage pages from the source b-tree to the destination.
52003 */
52004 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
52005   int rc;
52006   int destMode;       /* Destination journal mode */
52007   int pgszSrc = 0;    /* Source page size */
52008   int pgszDest = 0;   /* Destination page size */
52009
52010   sqlite3_mutex_enter(p->pSrcDb->mutex);
52011   sqlite3BtreeEnter(p->pSrc);
52012   if( p->pDestDb ){
52013     sqlite3_mutex_enter(p->pDestDb->mutex);
52014   }
52015
52016   rc = p->rc;
52017   if( !isFatalError(rc) ){
52018     Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
52019     Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
52020     int ii;                            /* Iterator variable */
52021     int nSrcPage = -1;                 /* Size of source db in pages */
52022     int bCloseTrans = 0;               /* True if src db requires unlocking */
52023
52024     /* If the source pager is currently in a write-transaction, return
52025     ** SQLITE_BUSY immediately.
52026     */
52027     if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
52028       rc = SQLITE_BUSY;
52029     }else{
52030       rc = SQLITE_OK;
52031     }
52032
52033     /* Lock the destination database, if it is not locked already. */
52034     if( SQLITE_OK==rc && p->bDestLocked==0
52035      && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2)) 
52036     ){
52037       p->bDestLocked = 1;
52038       sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
52039     }
52040
52041     /* If there is no open read-transaction on the source database, open
52042     ** one now. If a transaction is opened here, then it will be closed
52043     ** before this function exits.
52044     */
52045     if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
52046       rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
52047       bCloseTrans = 1;
52048     }
52049
52050     /* Do not allow backup if the destination database is in WAL mode
52051     ** and the page sizes are different between source and destination */
52052     pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
52053     pgszDest = sqlite3BtreeGetPageSize(p->pDest);
52054     destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
52055     if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
52056       rc = SQLITE_READONLY;
52057     }
52058   
52059     /* Now that there is a read-lock on the source database, query the
52060     ** source pager for the number of pages in the database.
52061     */
52062     nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
52063     assert( nSrcPage>=0 );
52064     for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
52065       const Pgno iSrcPg = p->iNext;                 /* Source page number */
52066       if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
52067         DbPage *pSrcPg;                             /* Source page object */
52068         rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
52069         if( rc==SQLITE_OK ){
52070           rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg));
52071           sqlite3PagerUnref(pSrcPg);
52072         }
52073       }
52074       p->iNext++;
52075     }
52076     if( rc==SQLITE_OK ){
52077       p->nPagecount = nSrcPage;
52078       p->nRemaining = nSrcPage+1-p->iNext;
52079       if( p->iNext>(Pgno)nSrcPage ){
52080         rc = SQLITE_DONE;
52081       }else if( !p->isAttached ){
52082         attachBackupObject(p);
52083       }
52084     }
52085   
52086     /* Update the schema version field in the destination database. This
52087     ** is to make sure that the schema-version really does change in
52088     ** the case where the source and destination databases have the
52089     ** same schema version.
52090     */
52091     if( rc==SQLITE_DONE 
52092      && (rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1))==SQLITE_OK
52093     ){
52094       int nDestTruncate;
52095   
52096       if( p->pDestDb ){
52097         sqlite3ResetInternalSchema(p->pDestDb, 0);
52098       }
52099
52100       /* Set nDestTruncate to the final number of pages in the destination
52101       ** database. The complication here is that the destination page
52102       ** size may be different to the source page size. 
52103       **
52104       ** If the source page size is smaller than the destination page size, 
52105       ** round up. In this case the call to sqlite3OsTruncate() below will
52106       ** fix the size of the file. However it is important to call
52107       ** sqlite3PagerTruncateImage() here so that any pages in the 
52108       ** destination file that lie beyond the nDestTruncate page mark are
52109       ** journalled by PagerCommitPhaseOne() before they are destroyed
52110       ** by the file truncation.
52111       */
52112       assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
52113       assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
52114       if( pgszSrc<pgszDest ){
52115         int ratio = pgszDest/pgszSrc;
52116         nDestTruncate = (nSrcPage+ratio-1)/ratio;
52117         if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
52118           nDestTruncate--;
52119         }
52120       }else{
52121         nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
52122       }
52123       sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
52124
52125       if( pgszSrc<pgszDest ){
52126         /* If the source page-size is smaller than the destination page-size,
52127         ** two extra things may need to happen:
52128         **
52129         **   * The destination may need to be truncated, and
52130         **
52131         **   * Data stored on the pages immediately following the 
52132         **     pending-byte page in the source database may need to be
52133         **     copied into the destination database.
52134         */
52135         const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
52136         sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
52137
52138         assert( pFile );
52139         assert( (i64)nDestTruncate*(i64)pgszDest >= iSize || (
52140               nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
52141            && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
52142         ));
52143         if( SQLITE_OK==(rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1))
52144          && SQLITE_OK==(rc = backupTruncateFile(pFile, iSize))
52145          && SQLITE_OK==(rc = sqlite3PagerSync(pDestPager))
52146         ){
52147           i64 iOff;
52148           i64 iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
52149           for(
52150             iOff=PENDING_BYTE+pgszSrc; 
52151             rc==SQLITE_OK && iOff<iEnd; 
52152             iOff+=pgszSrc
52153           ){
52154             PgHdr *pSrcPg = 0;
52155             const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
52156             rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
52157             if( rc==SQLITE_OK ){
52158               u8 *zData = sqlite3PagerGetData(pSrcPg);
52159               rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
52160             }
52161             sqlite3PagerUnref(pSrcPg);
52162           }
52163         }
52164       }else{
52165         rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
52166       }
52167   
52168       /* Finish committing the transaction to the destination database. */
52169       if( SQLITE_OK==rc
52170        && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest))
52171       ){
52172         rc = SQLITE_DONE;
52173       }
52174     }
52175   
52176     /* If bCloseTrans is true, then this function opened a read transaction
52177     ** on the source database. Close the read transaction here. There is
52178     ** no need to check the return values of the btree methods here, as
52179     ** "committing" a read-only transaction cannot fail.
52180     */
52181     if( bCloseTrans ){
52182       TESTONLY( int rc2 );
52183       TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
52184       TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc);
52185       assert( rc2==SQLITE_OK );
52186     }
52187   
52188     if( rc==SQLITE_IOERR_NOMEM ){
52189       rc = SQLITE_NOMEM;
52190     }
52191     p->rc = rc;
52192   }
52193   if( p->pDestDb ){
52194     sqlite3_mutex_leave(p->pDestDb->mutex);
52195   }
52196   sqlite3BtreeLeave(p->pSrc);
52197   sqlite3_mutex_leave(p->pSrcDb->mutex);
52198   return rc;
52199 }
52200
52201 /*
52202 ** Release all resources associated with an sqlite3_backup* handle.
52203 */
52204 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
52205   sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
52206   sqlite3_mutex *mutex;                /* Mutex to protect source database */
52207   int rc;                              /* Value to return */
52208
52209   /* Enter the mutexes */
52210   if( p==0 ) return SQLITE_OK;
52211   sqlite3_mutex_enter(p->pSrcDb->mutex);
52212   sqlite3BtreeEnter(p->pSrc);
52213   mutex = p->pSrcDb->mutex;
52214   if( p->pDestDb ){
52215     sqlite3_mutex_enter(p->pDestDb->mutex);
52216   }
52217
52218   /* Detach this backup from the source pager. */
52219   if( p->pDestDb ){
52220     p->pSrc->nBackup--;
52221   }
52222   if( p->isAttached ){
52223     pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
52224     while( *pp!=p ){
52225       pp = &(*pp)->pNext;
52226     }
52227     *pp = p->pNext;
52228   }
52229
52230   /* If a transaction is still open on the Btree, roll it back. */
52231   sqlite3BtreeRollback(p->pDest);
52232
52233   /* Set the error code of the destination database handle. */
52234   rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
52235   sqlite3Error(p->pDestDb, rc, 0);
52236
52237   /* Exit the mutexes and free the backup context structure. */
52238   if( p->pDestDb ){
52239     sqlite3_mutex_leave(p->pDestDb->mutex);
52240   }
52241   sqlite3BtreeLeave(p->pSrc);
52242   if( p->pDestDb ){
52243     sqlite3_free(p);
52244   }
52245   sqlite3_mutex_leave(mutex);
52246   return rc;
52247 }
52248
52249 /*
52250 ** Return the number of pages still to be backed up as of the most recent
52251 ** call to sqlite3_backup_step().
52252 */
52253 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
52254   return p->nRemaining;
52255 }
52256
52257 /*
52258 ** Return the total number of pages in the source database as of the most 
52259 ** recent call to sqlite3_backup_step().
52260 */
52261 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
52262   return p->nPagecount;
52263 }
52264
52265 /*
52266 ** This function is called after the contents of page iPage of the
52267 ** source database have been modified. If page iPage has already been 
52268 ** copied into the destination database, then the data written to the
52269 ** destination is now invalidated. The destination copy of iPage needs
52270 ** to be updated with the new data before the backup operation is
52271 ** complete.
52272 **
52273 ** It is assumed that the mutex associated with the BtShared object
52274 ** corresponding to the source database is held when this function is
52275 ** called.
52276 */
52277 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
52278   sqlite3_backup *p;                   /* Iterator variable */
52279   for(p=pBackup; p; p=p->pNext){
52280     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
52281     if( !isFatalError(p->rc) && iPage<p->iNext ){
52282       /* The backup process p has already copied page iPage. But now it
52283       ** has been modified by a transaction on the source pager. Copy
52284       ** the new data into the backup.
52285       */
52286       int rc = backupOnePage(p, iPage, aData);
52287       assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
52288       if( rc!=SQLITE_OK ){
52289         p->rc = rc;
52290       }
52291     }
52292   }
52293 }
52294
52295 /*
52296 ** Restart the backup process. This is called when the pager layer
52297 ** detects that the database has been modified by an external database
52298 ** connection. In this case there is no way of knowing which of the
52299 ** pages that have been copied into the destination database are still 
52300 ** valid and which are not, so the entire process needs to be restarted.
52301 **
52302 ** It is assumed that the mutex associated with the BtShared object
52303 ** corresponding to the source database is held when this function is
52304 ** called.
52305 */
52306 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
52307   sqlite3_backup *p;                   /* Iterator variable */
52308   for(p=pBackup; p; p=p->pNext){
52309     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
52310     p->iNext = 1;
52311   }
52312 }
52313
52314 #ifndef SQLITE_OMIT_VACUUM
52315 /*
52316 ** Copy the complete content of pBtFrom into pBtTo.  A transaction
52317 ** must be active for both files.
52318 **
52319 ** The size of file pTo may be reduced by this operation. If anything 
52320 ** goes wrong, the transaction on pTo is rolled back. If successful, the 
52321 ** transaction is committed before returning.
52322 */
52323 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
52324   int rc;
52325   sqlite3_backup b;
52326   sqlite3BtreeEnter(pTo);
52327   sqlite3BtreeEnter(pFrom);
52328
52329   /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
52330   ** to 0. This is used by the implementations of sqlite3_backup_step()
52331   ** and sqlite3_backup_finish() to detect that they are being called
52332   ** from this function, not directly by the user.
52333   */
52334   memset(&b, 0, sizeof(b));
52335   b.pSrcDb = pFrom->db;
52336   b.pSrc = pFrom;
52337   b.pDest = pTo;
52338   b.iNext = 1;
52339
52340   /* 0x7FFFFFFF is the hard limit for the number of pages in a database
52341   ** file. By passing this as the number of pages to copy to
52342   ** sqlite3_backup_step(), we can guarantee that the copy finishes 
52343   ** within a single call (unless an error occurs). The assert() statement
52344   ** checks this assumption - (p->rc) should be set to either SQLITE_DONE 
52345   ** or an error code.
52346   */
52347   sqlite3_backup_step(&b, 0x7FFFFFFF);
52348   assert( b.rc!=SQLITE_OK );
52349   rc = sqlite3_backup_finish(&b);
52350   if( rc==SQLITE_OK ){
52351     pTo->pBt->pageSizeFixed = 0;
52352   }
52353
52354   sqlite3BtreeLeave(pFrom);
52355   sqlite3BtreeLeave(pTo);
52356   return rc;
52357 }
52358 #endif /* SQLITE_OMIT_VACUUM */
52359
52360 /************** End of backup.c **********************************************/
52361 /************** Begin file vdbemem.c *****************************************/
52362 /*
52363 ** 2004 May 26
52364 **
52365 ** The author disclaims copyright to this source code.  In place of
52366 ** a legal notice, here is a blessing:
52367 **
52368 **    May you do good and not evil.
52369 **    May you find forgiveness for yourself and forgive others.
52370 **    May you share freely, never taking more than you give.
52371 **
52372 *************************************************************************
52373 **
52374 ** This file contains code use to manipulate "Mem" structure.  A "Mem"
52375 ** stores a single value in the VDBE.  Mem is an opaque structure visible
52376 ** only within the VDBE.  Interface routines refer to a Mem using the
52377 ** name sqlite_value
52378 */
52379
52380 /*
52381 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
52382 ** P if required.
52383 */
52384 #define expandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
52385
52386 /*
52387 ** If pMem is an object with a valid string representation, this routine
52388 ** ensures the internal encoding for the string representation is
52389 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
52390 **
52391 ** If pMem is not a string object, or the encoding of the string
52392 ** representation is already stored using the requested encoding, then this
52393 ** routine is a no-op.
52394 **
52395 ** SQLITE_OK is returned if the conversion is successful (or not required).
52396 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
52397 ** between formats.
52398 */
52399 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
52400   int rc;
52401   assert( (pMem->flags&MEM_RowSet)==0 );
52402   assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
52403            || desiredEnc==SQLITE_UTF16BE );
52404   if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
52405     return SQLITE_OK;
52406   }
52407   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
52408 #ifdef SQLITE_OMIT_UTF16
52409   return SQLITE_ERROR;
52410 #else
52411
52412   /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
52413   ** then the encoding of the value may not have changed.
52414   */
52415   rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
52416   assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
52417   assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
52418   assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
52419   return rc;
52420 #endif
52421 }
52422
52423 /*
52424 ** Make sure pMem->z points to a writable allocation of at least 
52425 ** n bytes.
52426 **
52427 ** If the memory cell currently contains string or blob data
52428 ** and the third argument passed to this function is true, the 
52429 ** current content of the cell is preserved. Otherwise, it may
52430 ** be discarded.  
52431 **
52432 ** This function sets the MEM_Dyn flag and clears any xDel callback.
52433 ** It also clears MEM_Ephem and MEM_Static. If the preserve flag is 
52434 ** not set, Mem.n is zeroed.
52435 */
52436 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
52437   assert( 1 >=
52438     ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
52439     (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) + 
52440     ((pMem->flags&MEM_Ephem) ? 1 : 0) + 
52441     ((pMem->flags&MEM_Static) ? 1 : 0)
52442   );
52443   assert( (pMem->flags&MEM_RowSet)==0 );
52444
52445   if( n<32 ) n = 32;
52446   if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
52447     if( preserve && pMem->z==pMem->zMalloc ){
52448       pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
52449       preserve = 0;
52450     }else{
52451       sqlite3DbFree(pMem->db, pMem->zMalloc);
52452       pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
52453     }
52454   }
52455
52456   if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
52457     memcpy(pMem->zMalloc, pMem->z, pMem->n);
52458   }
52459   if( pMem->flags&MEM_Dyn && pMem->xDel ){
52460     pMem->xDel((void *)(pMem->z));
52461   }
52462
52463   pMem->z = pMem->zMalloc;
52464   if( pMem->z==0 ){
52465     pMem->flags = MEM_Null;
52466   }else{
52467     pMem->flags &= ~(MEM_Ephem|MEM_Static);
52468   }
52469   pMem->xDel = 0;
52470   return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
52471 }
52472
52473 /*
52474 ** Make the given Mem object MEM_Dyn.  In other words, make it so
52475 ** that any TEXT or BLOB content is stored in memory obtained from
52476 ** malloc().  In this way, we know that the memory is safe to be
52477 ** overwritten or altered.
52478 **
52479 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
52480 */
52481 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
52482   int f;
52483   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
52484   assert( (pMem->flags&MEM_RowSet)==0 );
52485   expandBlob(pMem);
52486   f = pMem->flags;
52487   if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
52488     if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
52489       return SQLITE_NOMEM;
52490     }
52491     pMem->z[pMem->n] = 0;
52492     pMem->z[pMem->n+1] = 0;
52493     pMem->flags |= MEM_Term;
52494   }
52495
52496   return SQLITE_OK;
52497 }
52498
52499 /*
52500 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
52501 ** blob stored in dynamically allocated space.
52502 */
52503 #ifndef SQLITE_OMIT_INCRBLOB
52504 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
52505   if( pMem->flags & MEM_Zero ){
52506     int nByte;
52507     assert( pMem->flags&MEM_Blob );
52508     assert( (pMem->flags&MEM_RowSet)==0 );
52509     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
52510
52511     /* Set nByte to the number of bytes required to store the expanded blob. */
52512     nByte = pMem->n + pMem->u.nZero;
52513     if( nByte<=0 ){
52514       nByte = 1;
52515     }
52516     if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
52517       return SQLITE_NOMEM;
52518     }
52519
52520     memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
52521     pMem->n += pMem->u.nZero;
52522     pMem->flags &= ~(MEM_Zero|MEM_Term);
52523   }
52524   return SQLITE_OK;
52525 }
52526 #endif
52527
52528
52529 /*
52530 ** Make sure the given Mem is \u0000 terminated.
52531 */
52532 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
52533   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
52534   if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
52535     return SQLITE_OK;   /* Nothing to do */
52536   }
52537   if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
52538     return SQLITE_NOMEM;
52539   }
52540   pMem->z[pMem->n] = 0;
52541   pMem->z[pMem->n+1] = 0;
52542   pMem->flags |= MEM_Term;
52543   return SQLITE_OK;
52544 }
52545
52546 /*
52547 ** Add MEM_Str to the set of representations for the given Mem.  Numbers
52548 ** are converted using sqlite3_snprintf().  Converting a BLOB to a string
52549 ** is a no-op.
52550 **
52551 ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
52552 **
52553 ** A MEM_Null value will never be passed to this function. This function is
52554 ** used for converting values to text for returning to the user (i.e. via
52555 ** sqlite3_value_text()), or for ensuring that values to be used as btree
52556 ** keys are strings. In the former case a NULL pointer is returned the
52557 ** user and the later is an internal programming error.
52558 */
52559 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
52560   int rc = SQLITE_OK;
52561   int fg = pMem->flags;
52562   const int nByte = 32;
52563
52564   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
52565   assert( !(fg&MEM_Zero) );
52566   assert( !(fg&(MEM_Str|MEM_Blob)) );
52567   assert( fg&(MEM_Int|MEM_Real) );
52568   assert( (pMem->flags&MEM_RowSet)==0 );
52569   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
52570
52571
52572   if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
52573     return SQLITE_NOMEM;
52574   }
52575
52576   /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
52577   ** string representation of the value. Then, if the required encoding
52578   ** is UTF-16le or UTF-16be do a translation.
52579   ** 
52580   ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
52581   */
52582   if( fg & MEM_Int ){
52583     sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
52584   }else{
52585     assert( fg & MEM_Real );
52586     sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
52587   }
52588   pMem->n = sqlite3Strlen30(pMem->z);
52589   pMem->enc = SQLITE_UTF8;
52590   pMem->flags |= MEM_Str|MEM_Term;
52591   sqlite3VdbeChangeEncoding(pMem, enc);
52592   return rc;
52593 }
52594
52595 /*
52596 ** Memory cell pMem contains the context of an aggregate function.
52597 ** This routine calls the finalize method for that function.  The
52598 ** result of the aggregate is stored back into pMem.
52599 **
52600 ** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
52601 ** otherwise.
52602 */
52603 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
52604   int rc = SQLITE_OK;
52605   if( ALWAYS(pFunc && pFunc->xFinalize) ){
52606     sqlite3_context ctx;
52607     assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
52608     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
52609     memset(&ctx, 0, sizeof(ctx));
52610     ctx.s.flags = MEM_Null;
52611     ctx.s.db = pMem->db;
52612     ctx.pMem = pMem;
52613     ctx.pFunc = pFunc;
52614     pFunc->xFinalize(&ctx);
52615     assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
52616     sqlite3DbFree(pMem->db, pMem->zMalloc);
52617     memcpy(pMem, &ctx.s, sizeof(ctx.s));
52618     rc = ctx.isError;
52619   }
52620   return rc;
52621 }
52622
52623 /*
52624 ** If the memory cell contains a string value that must be freed by
52625 ** invoking an external callback, free it now. Calling this function
52626 ** does not free any Mem.zMalloc buffer.
52627 */
52628 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
52629   assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
52630   testcase( p->flags & MEM_Agg );
52631   testcase( p->flags & MEM_Dyn );
52632   testcase( p->flags & MEM_RowSet );
52633   testcase( p->flags & MEM_Frame );
52634   if( p->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame) ){
52635     if( p->flags&MEM_Agg ){
52636       sqlite3VdbeMemFinalize(p, p->u.pDef);
52637       assert( (p->flags & MEM_Agg)==0 );
52638       sqlite3VdbeMemRelease(p);
52639     }else if( p->flags&MEM_Dyn && p->xDel ){
52640       assert( (p->flags&MEM_RowSet)==0 );
52641       p->xDel((void *)p->z);
52642       p->xDel = 0;
52643     }else if( p->flags&MEM_RowSet ){
52644       sqlite3RowSetClear(p->u.pRowSet);
52645     }else if( p->flags&MEM_Frame ){
52646       sqlite3VdbeMemSetNull(p);
52647     }
52648   }
52649 }
52650
52651 /*
52652 ** Release any memory held by the Mem. This may leave the Mem in an
52653 ** inconsistent state, for example with (Mem.z==0) and
52654 ** (Mem.type==SQLITE_TEXT).
52655 */
52656 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
52657   sqlite3VdbeMemReleaseExternal(p);
52658   sqlite3DbFree(p->db, p->zMalloc);
52659   p->z = 0;
52660   p->zMalloc = 0;
52661   p->xDel = 0;
52662 }
52663
52664 /*
52665 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
52666 ** If the double is too large, return 0x8000000000000000.
52667 **
52668 ** Most systems appear to do this simply by assigning
52669 ** variables and without the extra range tests.  But
52670 ** there are reports that windows throws an expection
52671 ** if the floating point value is out of range. (See ticket #2880.)
52672 ** Because we do not completely understand the problem, we will
52673 ** take the conservative approach and always do range tests
52674 ** before attempting the conversion.
52675 */
52676 static i64 doubleToInt64(double r){
52677 #ifdef SQLITE_OMIT_FLOATING_POINT
52678   /* When floating-point is omitted, double and int64 are the same thing */
52679   return r;
52680 #else
52681   /*
52682   ** Many compilers we encounter do not define constants for the
52683   ** minimum and maximum 64-bit integers, or they define them
52684   ** inconsistently.  And many do not understand the "LL" notation.
52685   ** So we define our own static constants here using nothing
52686   ** larger than a 32-bit integer constant.
52687   */
52688   static const i64 maxInt = LARGEST_INT64;
52689   static const i64 minInt = SMALLEST_INT64;
52690
52691   if( r<(double)minInt ){
52692     return minInt;
52693   }else if( r>(double)maxInt ){
52694     /* minInt is correct here - not maxInt.  It turns out that assigning
52695     ** a very large positive number to an integer results in a very large
52696     ** negative integer.  This makes no sense, but it is what x86 hardware
52697     ** does so for compatibility we will do the same in software. */
52698     return minInt;
52699   }else{
52700     return (i64)r;
52701   }
52702 #endif
52703 }
52704
52705 /*
52706 ** Return some kind of integer value which is the best we can do
52707 ** at representing the value that *pMem describes as an integer.
52708 ** If pMem is an integer, then the value is exact.  If pMem is
52709 ** a floating-point then the value returned is the integer part.
52710 ** If pMem is a string or blob, then we make an attempt to convert
52711 ** it into a integer and return that.  If pMem represents an
52712 ** an SQL-NULL value, return 0.
52713 **
52714 ** If pMem represents a string value, its encoding might be changed.
52715 */
52716 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
52717   int flags;
52718   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
52719   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
52720   flags = pMem->flags;
52721   if( flags & MEM_Int ){
52722     return pMem->u.i;
52723   }else if( flags & MEM_Real ){
52724     return doubleToInt64(pMem->r);
52725   }else if( flags & (MEM_Str|MEM_Blob) ){
52726     i64 value;
52727     pMem->flags |= MEM_Str;
52728     if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8)
52729        || sqlite3VdbeMemNulTerminate(pMem) ){
52730       return 0;
52731     }
52732     assert( pMem->z );
52733     sqlite3Atoi64(pMem->z, &value);
52734     return value;
52735   }else{
52736     return 0;
52737   }
52738 }
52739
52740 /*
52741 ** Return the best representation of pMem that we can get into a
52742 ** double.  If pMem is already a double or an integer, return its
52743 ** value.  If it is a string or blob, try to convert it to a double.
52744 ** If it is a NULL, return 0.0.
52745 */
52746 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
52747   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
52748   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
52749   if( pMem->flags & MEM_Real ){
52750     return pMem->r;
52751   }else if( pMem->flags & MEM_Int ){
52752     return (double)pMem->u.i;
52753   }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
52754     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
52755     double val = (double)0;
52756     pMem->flags |= MEM_Str;
52757     if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8)
52758        || sqlite3VdbeMemNulTerminate(pMem) ){
52759       /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
52760       return (double)0;
52761     }
52762     assert( pMem->z );
52763     sqlite3AtoF(pMem->z, &val);
52764     return val;
52765   }else{
52766     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
52767     return (double)0;
52768   }
52769 }
52770
52771 /*
52772 ** The MEM structure is already a MEM_Real.  Try to also make it a
52773 ** MEM_Int if we can.
52774 */
52775 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
52776   assert( pMem->flags & MEM_Real );
52777   assert( (pMem->flags & MEM_RowSet)==0 );
52778   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
52779   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
52780
52781   pMem->u.i = doubleToInt64(pMem->r);
52782
52783   /* Only mark the value as an integer if
52784   **
52785   **    (1) the round-trip conversion real->int->real is a no-op, and
52786   **    (2) The integer is neither the largest nor the smallest
52787   **        possible integer (ticket #3922)
52788   **
52789   ** The second and third terms in the following conditional enforces
52790   ** the second condition under the assumption that addition overflow causes
52791   ** values to wrap around.  On x86 hardware, the third term is always
52792   ** true and could be omitted.  But we leave it in because other
52793   ** architectures might behave differently.
52794   */
52795   if( pMem->r==(double)pMem->u.i && pMem->u.i>SMALLEST_INT64
52796       && ALWAYS(pMem->u.i<LARGEST_INT64) ){
52797     pMem->flags |= MEM_Int;
52798   }
52799 }
52800
52801 /*
52802 ** Convert pMem to type integer.  Invalidate any prior representations.
52803 */
52804 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
52805   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
52806   assert( (pMem->flags & MEM_RowSet)==0 );
52807   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
52808
52809   pMem->u.i = sqlite3VdbeIntValue(pMem);
52810   MemSetTypeFlag(pMem, MEM_Int);
52811   return SQLITE_OK;
52812 }
52813
52814 /*
52815 ** Convert pMem so that it is of type MEM_Real.
52816 ** Invalidate any prior representations.
52817 */
52818 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
52819   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
52820   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
52821
52822   pMem->r = sqlite3VdbeRealValue(pMem);
52823   MemSetTypeFlag(pMem, MEM_Real);
52824   return SQLITE_OK;
52825 }
52826
52827 /*
52828 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
52829 ** Invalidate any prior representations.
52830 **
52831 ** Every effort is made to force the conversion, even if the input
52832 ** is a string that does not look completely like a number.  Convert
52833 ** as much of the string as we can and ignore the rest.
52834 */
52835 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
52836   int rc;
52837   assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 );
52838   assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
52839   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
52840   rc = sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8);
52841   if( rc ) return rc;
52842   rc = sqlite3VdbeMemNulTerminate(pMem);
52843   if( rc ) return rc;
52844   if( sqlite3Atoi64(pMem->z, &pMem->u.i) ){
52845     MemSetTypeFlag(pMem, MEM_Int);
52846   }else{
52847     pMem->r = sqlite3VdbeRealValue(pMem);
52848     MemSetTypeFlag(pMem, MEM_Real);
52849     sqlite3VdbeIntegerAffinity(pMem);
52850   }
52851   return SQLITE_OK;
52852 }
52853
52854 /*
52855 ** Delete any previous value and set the value stored in *pMem to NULL.
52856 */
52857 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
52858   if( pMem->flags & MEM_Frame ){
52859     sqlite3VdbeFrameDelete(pMem->u.pFrame);
52860   }
52861   if( pMem->flags & MEM_RowSet ){
52862     sqlite3RowSetClear(pMem->u.pRowSet);
52863   }
52864   MemSetTypeFlag(pMem, MEM_Null);
52865   pMem->type = SQLITE_NULL;
52866 }
52867
52868 /*
52869 ** Delete any previous value and set the value to be a BLOB of length
52870 ** n containing all zeros.
52871 */
52872 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
52873   sqlite3VdbeMemRelease(pMem);
52874   pMem->flags = MEM_Blob|MEM_Zero;
52875   pMem->type = SQLITE_BLOB;
52876   pMem->n = 0;
52877   if( n<0 ) n = 0;
52878   pMem->u.nZero = n;
52879   pMem->enc = SQLITE_UTF8;
52880
52881 #ifdef SQLITE_OMIT_INCRBLOB
52882   sqlite3VdbeMemGrow(pMem, n, 0);
52883   if( pMem->z ){
52884     pMem->n = n;
52885     memset(pMem->z, 0, n);
52886   }
52887 #endif
52888 }
52889
52890 /*
52891 ** Delete any previous value and set the value stored in *pMem to val,
52892 ** manifest type INTEGER.
52893 */
52894 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
52895   sqlite3VdbeMemRelease(pMem);
52896   pMem->u.i = val;
52897   pMem->flags = MEM_Int;
52898   pMem->type = SQLITE_INTEGER;
52899 }
52900
52901 #ifndef SQLITE_OMIT_FLOATING_POINT
52902 /*
52903 ** Delete any previous value and set the value stored in *pMem to val,
52904 ** manifest type REAL.
52905 */
52906 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
52907   if( sqlite3IsNaN(val) ){
52908     sqlite3VdbeMemSetNull(pMem);
52909   }else{
52910     sqlite3VdbeMemRelease(pMem);
52911     pMem->r = val;
52912     pMem->flags = MEM_Real;
52913     pMem->type = SQLITE_FLOAT;
52914   }
52915 }
52916 #endif
52917
52918 /*
52919 ** Delete any previous value and set the value of pMem to be an
52920 ** empty boolean index.
52921 */
52922 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
52923   sqlite3 *db = pMem->db;
52924   assert( db!=0 );
52925   assert( (pMem->flags & MEM_RowSet)==0 );
52926   sqlite3VdbeMemRelease(pMem);
52927   pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
52928   if( db->mallocFailed ){
52929     pMem->flags = MEM_Null;
52930   }else{
52931     assert( pMem->zMalloc );
52932     pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, 
52933                                        sqlite3DbMallocSize(db, pMem->zMalloc));
52934     assert( pMem->u.pRowSet!=0 );
52935     pMem->flags = MEM_RowSet;
52936   }
52937 }
52938
52939 /*
52940 ** Return true if the Mem object contains a TEXT or BLOB that is
52941 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
52942 */
52943 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
52944   assert( p->db!=0 );
52945   if( p->flags & (MEM_Str|MEM_Blob) ){
52946     int n = p->n;
52947     if( p->flags & MEM_Zero ){
52948       n += p->u.nZero;
52949     }
52950     return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
52951   }
52952   return 0; 
52953 }
52954
52955 /*
52956 ** Size of struct Mem not including the Mem.zMalloc member.
52957 */
52958 #define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
52959
52960 /*
52961 ** Make an shallow copy of pFrom into pTo.  Prior contents of
52962 ** pTo are freed.  The pFrom->z field is not duplicated.  If
52963 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
52964 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
52965 */
52966 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
52967   assert( (pFrom->flags & MEM_RowSet)==0 );
52968   sqlite3VdbeMemReleaseExternal(pTo);
52969   memcpy(pTo, pFrom, MEMCELLSIZE);
52970   pTo->xDel = 0;
52971   if( (pFrom->flags&MEM_Static)==0 ){
52972     pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
52973     assert( srcType==MEM_Ephem || srcType==MEM_Static );
52974     pTo->flags |= srcType;
52975   }
52976 }
52977
52978 /*
52979 ** Make a full copy of pFrom into pTo.  Prior contents of pTo are
52980 ** freed before the copy is made.
52981 */
52982 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
52983   int rc = SQLITE_OK;
52984
52985   assert( (pFrom->flags & MEM_RowSet)==0 );
52986   sqlite3VdbeMemReleaseExternal(pTo);
52987   memcpy(pTo, pFrom, MEMCELLSIZE);
52988   pTo->flags &= ~MEM_Dyn;
52989
52990   if( pTo->flags&(MEM_Str|MEM_Blob) ){
52991     if( 0==(pFrom->flags&MEM_Static) ){
52992       pTo->flags |= MEM_Ephem;
52993       rc = sqlite3VdbeMemMakeWriteable(pTo);
52994     }
52995   }
52996
52997   return rc;
52998 }
52999
53000 /*
53001 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
53002 ** freed. If pFrom contains ephemeral data, a copy is made.
53003 **
53004 ** pFrom contains an SQL NULL when this routine returns.
53005 */
53006 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
53007   assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
53008   assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
53009   assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
53010
53011   sqlite3VdbeMemRelease(pTo);
53012   memcpy(pTo, pFrom, sizeof(Mem));
53013   pFrom->flags = MEM_Null;
53014   pFrom->xDel = 0;
53015   pFrom->zMalloc = 0;
53016 }
53017
53018 /*
53019 ** Change the value of a Mem to be a string or a BLOB.
53020 **
53021 ** The memory management strategy depends on the value of the xDel
53022 ** parameter. If the value passed is SQLITE_TRANSIENT, then the 
53023 ** string is copied into a (possibly existing) buffer managed by the 
53024 ** Mem structure. Otherwise, any existing buffer is freed and the
53025 ** pointer copied.
53026 **
53027 ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
53028 ** size limit) then no memory allocation occurs.  If the string can be
53029 ** stored without allocating memory, then it is.  If a memory allocation
53030 ** is required to store the string, then value of pMem is unchanged.  In
53031 ** either case, SQLITE_TOOBIG is returned.
53032 */
53033 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
53034   Mem *pMem,          /* Memory cell to set to string value */
53035   const char *z,      /* String pointer */
53036   int n,              /* Bytes in string, or negative */
53037   u8 enc,             /* Encoding of z.  0 for BLOBs */
53038   void (*xDel)(void*) /* Destructor function */
53039 ){
53040   int nByte = n;      /* New value for pMem->n */
53041   int iLimit;         /* Maximum allowed string or blob size */
53042   u16 flags = 0;      /* New value for pMem->flags */
53043
53044   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
53045   assert( (pMem->flags & MEM_RowSet)==0 );
53046
53047   /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
53048   if( !z ){
53049     sqlite3VdbeMemSetNull(pMem);
53050     return SQLITE_OK;
53051   }
53052
53053   if( pMem->db ){
53054     iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
53055   }else{
53056     iLimit = SQLITE_MAX_LENGTH;
53057   }
53058   flags = (enc==0?MEM_Blob:MEM_Str);
53059   if( nByte<0 ){
53060     assert( enc!=0 );
53061     if( enc==SQLITE_UTF8 ){
53062       for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
53063     }else{
53064       for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
53065     }
53066     flags |= MEM_Term;
53067   }
53068
53069   /* The following block sets the new values of Mem.z and Mem.xDel. It
53070   ** also sets a flag in local variable "flags" to indicate the memory
53071   ** management (one of MEM_Dyn or MEM_Static).
53072   */
53073   if( xDel==SQLITE_TRANSIENT ){
53074     int nAlloc = nByte;
53075     if( flags&MEM_Term ){
53076       nAlloc += (enc==SQLITE_UTF8?1:2);
53077     }
53078     if( nByte>iLimit ){
53079       return SQLITE_TOOBIG;
53080     }
53081     if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
53082       return SQLITE_NOMEM;
53083     }
53084     memcpy(pMem->z, z, nAlloc);
53085   }else if( xDel==SQLITE_DYNAMIC ){
53086     sqlite3VdbeMemRelease(pMem);
53087     pMem->zMalloc = pMem->z = (char *)z;
53088     pMem->xDel = 0;
53089   }else{
53090     sqlite3VdbeMemRelease(pMem);
53091     pMem->z = (char *)z;
53092     pMem->xDel = xDel;
53093     flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
53094   }
53095
53096   pMem->n = nByte;
53097   pMem->flags = flags;
53098   pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
53099   pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
53100
53101 #ifndef SQLITE_OMIT_UTF16
53102   if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
53103     return SQLITE_NOMEM;
53104   }
53105 #endif
53106
53107   if( nByte>iLimit ){
53108     return SQLITE_TOOBIG;
53109   }
53110
53111   return SQLITE_OK;
53112 }
53113
53114 /*
53115 ** Compare the values contained by the two memory cells, returning
53116 ** negative, zero or positive if pMem1 is less than, equal to, or greater
53117 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
53118 ** and reals) sorted numerically, followed by text ordered by the collating
53119 ** sequence pColl and finally blob's ordered by memcmp().
53120 **
53121 ** Two NULL values are considered equal by this function.
53122 */
53123 SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
53124   int rc;
53125   int f1, f2;
53126   int combined_flags;
53127
53128   f1 = pMem1->flags;
53129   f2 = pMem2->flags;
53130   combined_flags = f1|f2;
53131   assert( (combined_flags & MEM_RowSet)==0 );
53132  
53133   /* If one value is NULL, it is less than the other. If both values
53134   ** are NULL, return 0.
53135   */
53136   if( combined_flags&MEM_Null ){
53137     return (f2&MEM_Null) - (f1&MEM_Null);
53138   }
53139
53140   /* If one value is a number and the other is not, the number is less.
53141   ** If both are numbers, compare as reals if one is a real, or as integers
53142   ** if both values are integers.
53143   */
53144   if( combined_flags&(MEM_Int|MEM_Real) ){
53145     if( !(f1&(MEM_Int|MEM_Real)) ){
53146       return 1;
53147     }
53148     if( !(f2&(MEM_Int|MEM_Real)) ){
53149       return -1;
53150     }
53151     if( (f1 & f2 & MEM_Int)==0 ){
53152       double r1, r2;
53153       if( (f1&MEM_Real)==0 ){
53154         r1 = (double)pMem1->u.i;
53155       }else{
53156         r1 = pMem1->r;
53157       }
53158       if( (f2&MEM_Real)==0 ){
53159         r2 = (double)pMem2->u.i;
53160       }else{
53161         r2 = pMem2->r;
53162       }
53163       if( r1<r2 ) return -1;
53164       if( r1>r2 ) return 1;
53165       return 0;
53166     }else{
53167       assert( f1&MEM_Int );
53168       assert( f2&MEM_Int );
53169       if( pMem1->u.i < pMem2->u.i ) return -1;
53170       if( pMem1->u.i > pMem2->u.i ) return 1;
53171       return 0;
53172     }
53173   }
53174
53175   /* If one value is a string and the other is a blob, the string is less.
53176   ** If both are strings, compare using the collating functions.
53177   */
53178   if( combined_flags&MEM_Str ){
53179     if( (f1 & MEM_Str)==0 ){
53180       return 1;
53181     }
53182     if( (f2 & MEM_Str)==0 ){
53183       return -1;
53184     }
53185
53186     assert( pMem1->enc==pMem2->enc );
53187     assert( pMem1->enc==SQLITE_UTF8 || 
53188             pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
53189
53190     /* The collation sequence must be defined at this point, even if
53191     ** the user deletes the collation sequence after the vdbe program is
53192     ** compiled (this was not always the case).
53193     */
53194     assert( !pColl || pColl->xCmp );
53195
53196     if( pColl ){
53197       if( pMem1->enc==pColl->enc ){
53198         /* The strings are already in the correct encoding.  Call the
53199         ** comparison function directly */
53200         return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
53201       }else{
53202         const void *v1, *v2;
53203         int n1, n2;
53204         Mem c1;
53205         Mem c2;
53206         memset(&c1, 0, sizeof(c1));
53207         memset(&c2, 0, sizeof(c2));
53208         sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
53209         sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
53210         v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
53211         n1 = v1==0 ? 0 : c1.n;
53212         v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
53213         n2 = v2==0 ? 0 : c2.n;
53214         rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
53215         sqlite3VdbeMemRelease(&c1);
53216         sqlite3VdbeMemRelease(&c2);
53217         return rc;
53218       }
53219     }
53220     /* If a NULL pointer was passed as the collate function, fall through
53221     ** to the blob case and use memcmp().  */
53222   }
53223  
53224   /* Both values must be blobs.  Compare using memcmp().  */
53225   rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
53226   if( rc==0 ){
53227     rc = pMem1->n - pMem2->n;
53228   }
53229   return rc;
53230 }
53231
53232 /*
53233 ** Move data out of a btree key or data field and into a Mem structure.
53234 ** The data or key is taken from the entry that pCur is currently pointing
53235 ** to.  offset and amt determine what portion of the data or key to retrieve.
53236 ** key is true to get the key or false to get data.  The result is written
53237 ** into the pMem element.
53238 **
53239 ** The pMem structure is assumed to be uninitialized.  Any prior content
53240 ** is overwritten without being freed.
53241 **
53242 ** If this routine fails for any reason (malloc returns NULL or unable
53243 ** to read from the disk) then the pMem is left in an inconsistent state.
53244 */
53245 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
53246   BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
53247   int offset,       /* Offset from the start of data to return bytes from. */
53248   int amt,          /* Number of bytes to return. */
53249   int key,          /* If true, retrieve from the btree key, not data. */
53250   Mem *pMem         /* OUT: Return data in this Mem structure. */
53251 ){
53252   char *zData;        /* Data from the btree layer */
53253   int available = 0;  /* Number of bytes available on the local btree page */
53254   int rc = SQLITE_OK; /* Return code */
53255
53256   assert( sqlite3BtreeCursorIsValid(pCur) );
53257
53258   /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert() 
53259   ** that both the BtShared and database handle mutexes are held. */
53260   assert( (pMem->flags & MEM_RowSet)==0 );
53261   if( key ){
53262     zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
53263   }else{
53264     zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
53265   }
53266   assert( zData!=0 );
53267
53268   if( offset+amt<=available && (pMem->flags&MEM_Dyn)==0 ){
53269     sqlite3VdbeMemRelease(pMem);
53270     pMem->z = &zData[offset];
53271     pMem->flags = MEM_Blob|MEM_Ephem;
53272   }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
53273     pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
53274     pMem->enc = 0;
53275     pMem->type = SQLITE_BLOB;
53276     if( key ){
53277       rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
53278     }else{
53279       rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
53280     }
53281     pMem->z[amt] = 0;
53282     pMem->z[amt+1] = 0;
53283     if( rc!=SQLITE_OK ){
53284       sqlite3VdbeMemRelease(pMem);
53285     }
53286   }
53287   pMem->n = amt;
53288
53289   return rc;
53290 }
53291
53292 /* This function is only available internally, it is not part of the
53293 ** external API. It works in a similar way to sqlite3_value_text(),
53294 ** except the data returned is in the encoding specified by the second
53295 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
53296 ** SQLITE_UTF8.
53297 **
53298 ** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
53299 ** If that is the case, then the result must be aligned on an even byte
53300 ** boundary.
53301 */
53302 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
53303   if( !pVal ) return 0;
53304
53305   assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
53306   assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
53307   assert( (pVal->flags & MEM_RowSet)==0 );
53308
53309   if( pVal->flags&MEM_Null ){
53310     return 0;
53311   }
53312   assert( (MEM_Blob>>3) == MEM_Str );
53313   pVal->flags |= (pVal->flags & MEM_Blob)>>3;
53314   expandBlob(pVal);
53315   if( pVal->flags&MEM_Str ){
53316     sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
53317     if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
53318       assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
53319       if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
53320         return 0;
53321       }
53322     }
53323     sqlite3VdbeMemNulTerminate(pVal);
53324   }else{
53325     assert( (pVal->flags&MEM_Blob)==0 );
53326     sqlite3VdbeMemStringify(pVal, enc);
53327     assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
53328   }
53329   assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
53330               || pVal->db->mallocFailed );
53331   if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
53332     return pVal->z;
53333   }else{
53334     return 0;
53335   }
53336 }
53337
53338 /*
53339 ** Create a new sqlite3_value object.
53340 */
53341 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
53342   Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
53343   if( p ){
53344     p->flags = MEM_Null;
53345     p->type = SQLITE_NULL;
53346     p->db = db;
53347   }
53348   return p;
53349 }
53350
53351 /*
53352 ** Create a new sqlite3_value object, containing the value of pExpr.
53353 **
53354 ** This only works for very simple expressions that consist of one constant
53355 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
53356 ** be converted directly into a value, then the value is allocated and
53357 ** a pointer written to *ppVal. The caller is responsible for deallocating
53358 ** the value by passing it to sqlite3ValueFree() later on. If the expression
53359 ** cannot be converted to a value, then *ppVal is set to NULL.
53360 */
53361 SQLITE_PRIVATE int sqlite3ValueFromExpr(
53362   sqlite3 *db,              /* The database connection */
53363   Expr *pExpr,              /* The expression to evaluate */
53364   u8 enc,                   /* Encoding to use */
53365   u8 affinity,              /* Affinity to use */
53366   sqlite3_value **ppVal     /* Write the new value here */
53367 ){
53368   int op;
53369   char *zVal = 0;
53370   sqlite3_value *pVal = 0;
53371
53372   if( !pExpr ){
53373     *ppVal = 0;
53374     return SQLITE_OK;
53375   }
53376   op = pExpr->op;
53377
53378   /* op can only be TK_REGISTER is we have compiled with SQLITE_ENABLE_STAT2.
53379   ** The ifdef here is to enable us to achieve 100% branch test coverage even
53380   ** when SQLITE_ENABLE_STAT2 is omitted.
53381   */
53382 #ifdef SQLITE_ENABLE_STAT2
53383   if( op==TK_REGISTER ) op = pExpr->op2;
53384 #else
53385   if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
53386 #endif
53387
53388   if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
53389     pVal = sqlite3ValueNew(db);
53390     if( pVal==0 ) goto no_mem;
53391     if( ExprHasProperty(pExpr, EP_IntValue) ){
53392       sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue);
53393     }else{
53394       zVal = sqlite3DbStrDup(db, pExpr->u.zToken);
53395       if( zVal==0 ) goto no_mem;
53396       sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
53397       if( op==TK_FLOAT ) pVal->type = SQLITE_FLOAT;
53398     }
53399     if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
53400       sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
53401     }else{
53402       sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
53403     }
53404     if( enc!=SQLITE_UTF8 ){
53405       sqlite3VdbeChangeEncoding(pVal, enc);
53406     }
53407   }else if( op==TK_UMINUS ) {
53408     if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
53409       pVal->u.i = -1 * pVal->u.i;
53410       /* (double)-1 In case of SQLITE_OMIT_FLOATING_POINT... */
53411       pVal->r = (double)-1 * pVal->r;
53412     }
53413   }
53414 #ifndef SQLITE_OMIT_BLOB_LITERAL
53415   else if( op==TK_BLOB ){
53416     int nVal;
53417     assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
53418     assert( pExpr->u.zToken[1]=='\'' );
53419     pVal = sqlite3ValueNew(db);
53420     if( !pVal ) goto no_mem;
53421     zVal = &pExpr->u.zToken[2];
53422     nVal = sqlite3Strlen30(zVal)-1;
53423     assert( zVal[nVal]=='\'' );
53424     sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
53425                          0, SQLITE_DYNAMIC);
53426   }
53427 #endif
53428
53429   if( pVal ){
53430     sqlite3VdbeMemStoreType(pVal);
53431   }
53432   *ppVal = pVal;
53433   return SQLITE_OK;
53434
53435 no_mem:
53436   db->mallocFailed = 1;
53437   sqlite3DbFree(db, zVal);
53438   sqlite3ValueFree(pVal);
53439   *ppVal = 0;
53440   return SQLITE_NOMEM;
53441 }
53442
53443 /*
53444 ** Change the string value of an sqlite3_value object
53445 */
53446 SQLITE_PRIVATE void sqlite3ValueSetStr(
53447   sqlite3_value *v,     /* Value to be set */
53448   int n,                /* Length of string z */
53449   const void *z,        /* Text of the new string */
53450   u8 enc,               /* Encoding to use */
53451   void (*xDel)(void*)   /* Destructor for the string */
53452 ){
53453   if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
53454 }
53455
53456 /*
53457 ** Free an sqlite3_value object
53458 */
53459 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
53460   if( !v ) return;
53461   sqlite3VdbeMemRelease((Mem *)v);
53462   sqlite3DbFree(((Mem*)v)->db, v);
53463 }
53464
53465 /*
53466 ** Return the number of bytes in the sqlite3_value object assuming
53467 ** that it uses the encoding "enc"
53468 */
53469 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
53470   Mem *p = (Mem*)pVal;
53471   if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
53472     if( p->flags & MEM_Zero ){
53473       return p->n + p->u.nZero;
53474     }else{
53475       return p->n;
53476     }
53477   }
53478   return 0;
53479 }
53480
53481 /************** End of vdbemem.c *********************************************/
53482 /************** Begin file vdbeaux.c *****************************************/
53483 /*
53484 ** 2003 September 6
53485 **
53486 ** The author disclaims copyright to this source code.  In place of
53487 ** a legal notice, here is a blessing:
53488 **
53489 **    May you do good and not evil.
53490 **    May you find forgiveness for yourself and forgive others.
53491 **    May you share freely, never taking more than you give.
53492 **
53493 *************************************************************************
53494 ** This file contains code used for creating, destroying, and populating
53495 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
53496 ** to version 2.8.7, all this code was combined into the vdbe.c source file.
53497 ** But that file was getting too big so this subroutines were split out.
53498 */
53499
53500
53501
53502 /*
53503 ** When debugging the code generator in a symbolic debugger, one can
53504 ** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed
53505 ** as they are added to the instruction stream.
53506 */
53507 #ifdef SQLITE_DEBUG
53508 SQLITE_PRIVATE int sqlite3VdbeAddopTrace = 0;
53509 #endif
53510
53511
53512 /*
53513 ** Create a new virtual database engine.
53514 */
53515 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
53516   Vdbe *p;
53517   p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
53518   if( p==0 ) return 0;
53519   p->db = db;
53520   if( db->pVdbe ){
53521     db->pVdbe->pPrev = p;
53522   }
53523   p->pNext = db->pVdbe;
53524   p->pPrev = 0;
53525   db->pVdbe = p;
53526   p->magic = VDBE_MAGIC_INIT;
53527   return p;
53528 }
53529
53530 /*
53531 ** Remember the SQL string for a prepared statement.
53532 */
53533 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
53534   assert( isPrepareV2==1 || isPrepareV2==0 );
53535   if( p==0 ) return;
53536 #ifdef SQLITE_OMIT_TRACE
53537   if( !isPrepareV2 ) return;
53538 #endif
53539   assert( p->zSql==0 );
53540   p->zSql = sqlite3DbStrNDup(p->db, z, n);
53541   p->isPrepareV2 = (u8)isPrepareV2;
53542 }
53543
53544 /*
53545 ** Return the SQL associated with a prepared statement
53546 */
53547 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
53548   Vdbe *p = (Vdbe *)pStmt;
53549   return (p && p->isPrepareV2) ? p->zSql : 0;
53550 }
53551
53552 /*
53553 ** Swap all content between two VDBE structures.
53554 */
53555 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
53556   Vdbe tmp, *pTmp;
53557   char *zTmp;
53558   tmp = *pA;
53559   *pA = *pB;
53560   *pB = tmp;
53561   pTmp = pA->pNext;
53562   pA->pNext = pB->pNext;
53563   pB->pNext = pTmp;
53564   pTmp = pA->pPrev;
53565   pA->pPrev = pB->pPrev;
53566   pB->pPrev = pTmp;
53567   zTmp = pA->zSql;
53568   pA->zSql = pB->zSql;
53569   pB->zSql = zTmp;
53570   pB->isPrepareV2 = pA->isPrepareV2;
53571 }
53572
53573 #ifdef SQLITE_DEBUG
53574 /*
53575 ** Turn tracing on or off
53576 */
53577 SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
53578   p->trace = trace;
53579 }
53580 #endif
53581
53582 /*
53583 ** Resize the Vdbe.aOp array so that it is at least one op larger than 
53584 ** it was.
53585 **
53586 ** If an out-of-memory error occurs while resizing the array, return
53587 ** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain 
53588 ** unchanged (this is so that any opcodes already allocated can be 
53589 ** correctly deallocated along with the rest of the Vdbe).
53590 */
53591 static int growOpArray(Vdbe *p){
53592   VdbeOp *pNew;
53593   int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
53594   pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
53595   if( pNew ){
53596     p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
53597     p->aOp = pNew;
53598   }
53599   return (pNew ? SQLITE_OK : SQLITE_NOMEM);
53600 }
53601
53602 /*
53603 ** Add a new instruction to the list of instructions current in the
53604 ** VDBE.  Return the address of the new instruction.
53605 **
53606 ** Parameters:
53607 **
53608 **    p               Pointer to the VDBE
53609 **
53610 **    op              The opcode for this instruction
53611 **
53612 **    p1, p2, p3      Operands
53613 **
53614 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
53615 ** the sqlite3VdbeChangeP4() function to change the value of the P4
53616 ** operand.
53617 */
53618 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
53619   int i;
53620   VdbeOp *pOp;
53621
53622   i = p->nOp;
53623   assert( p->magic==VDBE_MAGIC_INIT );
53624   assert( op>0 && op<0xff );
53625   if( p->nOpAlloc<=i ){
53626     if( growOpArray(p) ){
53627       return 1;
53628     }
53629   }
53630   p->nOp++;
53631   pOp = &p->aOp[i];
53632   pOp->opcode = (u8)op;
53633   pOp->p5 = 0;
53634   pOp->p1 = p1;
53635   pOp->p2 = p2;
53636   pOp->p3 = p3;
53637   pOp->p4.p = 0;
53638   pOp->p4type = P4_NOTUSED;
53639   p->expired = 0;
53640 #ifdef SQLITE_DEBUG
53641   pOp->zComment = 0;
53642   if( sqlite3VdbeAddopTrace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
53643 #endif
53644 #ifdef VDBE_PROFILE
53645   pOp->cycles = 0;
53646   pOp->cnt = 0;
53647 #endif
53648   return i;
53649 }
53650 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
53651   return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
53652 }
53653 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
53654   return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
53655 }
53656 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
53657   return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
53658 }
53659
53660
53661 /*
53662 ** Add an opcode that includes the p4 value as a pointer.
53663 */
53664 SQLITE_PRIVATE int sqlite3VdbeAddOp4(
53665   Vdbe *p,            /* Add the opcode to this VM */
53666   int op,             /* The new opcode */
53667   int p1,             /* The P1 operand */
53668   int p2,             /* The P2 operand */
53669   int p3,             /* The P3 operand */
53670   const char *zP4,    /* The P4 operand */
53671   int p4type          /* P4 operand type */
53672 ){
53673   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
53674   sqlite3VdbeChangeP4(p, addr, zP4, p4type);
53675   return addr;
53676 }
53677
53678 /*
53679 ** Add an opcode that includes the p4 value as an integer.
53680 */
53681 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
53682   Vdbe *p,            /* Add the opcode to this VM */
53683   int op,             /* The new opcode */
53684   int p1,             /* The P1 operand */
53685   int p2,             /* The P2 operand */
53686   int p3,             /* The P3 operand */
53687   int p4              /* The P4 operand as an integer */
53688 ){
53689   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
53690   sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
53691   return addr;
53692 }
53693
53694 /*
53695 ** Create a new symbolic label for an instruction that has yet to be
53696 ** coded.  The symbolic label is really just a negative number.  The
53697 ** label can be used as the P2 value of an operation.  Later, when
53698 ** the label is resolved to a specific address, the VDBE will scan
53699 ** through its operation list and change all values of P2 which match
53700 ** the label into the resolved address.
53701 **
53702 ** The VDBE knows that a P2 value is a label because labels are
53703 ** always negative and P2 values are suppose to be non-negative.
53704 ** Hence, a negative P2 value is a label that has yet to be resolved.
53705 **
53706 ** Zero is returned if a malloc() fails.
53707 */
53708 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
53709   int i;
53710   i = p->nLabel++;
53711   assert( p->magic==VDBE_MAGIC_INIT );
53712   if( i>=p->nLabelAlloc ){
53713     int n = p->nLabelAlloc*2 + 5;
53714     p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
53715                                        n*sizeof(p->aLabel[0]));
53716     p->nLabelAlloc = sqlite3DbMallocSize(p->db, p->aLabel)/sizeof(p->aLabel[0]);
53717   }
53718   if( p->aLabel ){
53719     p->aLabel[i] = -1;
53720   }
53721   return -1-i;
53722 }
53723
53724 /*
53725 ** Resolve label "x" to be the address of the next instruction to
53726 ** be inserted.  The parameter "x" must have been obtained from
53727 ** a prior call to sqlite3VdbeMakeLabel().
53728 */
53729 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
53730   int j = -1-x;
53731   assert( p->magic==VDBE_MAGIC_INIT );
53732   assert( j>=0 && j<p->nLabel );
53733   if( p->aLabel ){
53734     p->aLabel[j] = p->nOp;
53735   }
53736 }
53737
53738 /*
53739 ** Mark the VDBE as one that can only be run one time.
53740 */
53741 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
53742   p->runOnlyOnce = 1;
53743 }
53744
53745 #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
53746
53747 /*
53748 ** The following type and function are used to iterate through all opcodes
53749 ** in a Vdbe main program and each of the sub-programs (triggers) it may 
53750 ** invoke directly or indirectly. It should be used as follows:
53751 **
53752 **   Op *pOp;
53753 **   VdbeOpIter sIter;
53754 **
53755 **   memset(&sIter, 0, sizeof(sIter));
53756 **   sIter.v = v;                            // v is of type Vdbe* 
53757 **   while( (pOp = opIterNext(&sIter)) ){
53758 **     // Do something with pOp
53759 **   }
53760 **   sqlite3DbFree(v->db, sIter.apSub);
53761 ** 
53762 */
53763 typedef struct VdbeOpIter VdbeOpIter;
53764 struct VdbeOpIter {
53765   Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
53766   SubProgram **apSub;        /* Array of subprograms */
53767   int nSub;                  /* Number of entries in apSub */
53768   int iAddr;                 /* Address of next instruction to return */
53769   int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
53770 };
53771 static Op *opIterNext(VdbeOpIter *p){
53772   Vdbe *v = p->v;
53773   Op *pRet = 0;
53774   Op *aOp;
53775   int nOp;
53776
53777   if( p->iSub<=p->nSub ){
53778
53779     if( p->iSub==0 ){
53780       aOp = v->aOp;
53781       nOp = v->nOp;
53782     }else{
53783       aOp = p->apSub[p->iSub-1]->aOp;
53784       nOp = p->apSub[p->iSub-1]->nOp;
53785     }
53786     assert( p->iAddr<nOp );
53787
53788     pRet = &aOp[p->iAddr];
53789     p->iAddr++;
53790     if( p->iAddr==nOp ){
53791       p->iSub++;
53792       p->iAddr = 0;
53793     }
53794   
53795     if( pRet->p4type==P4_SUBPROGRAM ){
53796       int nByte = (p->nSub+1)*sizeof(SubProgram*);
53797       int j;
53798       for(j=0; j<p->nSub; j++){
53799         if( p->apSub[j]==pRet->p4.pProgram ) break;
53800       }
53801       if( j==p->nSub ){
53802         p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
53803         if( !p->apSub ){
53804           pRet = 0;
53805         }else{
53806           p->apSub[p->nSub++] = pRet->p4.pProgram;
53807         }
53808       }
53809     }
53810   }
53811
53812   return pRet;
53813 }
53814
53815 /*
53816 ** Check if the program stored in the VM associated with pParse may
53817 ** throw an ABORT exception (causing the statement, but not entire transaction
53818 ** to be rolled back). This condition is true if the main program or any
53819 ** sub-programs contains any of the following:
53820 **
53821 **   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
53822 **   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
53823 **   *  OP_Destroy
53824 **   *  OP_VUpdate
53825 **   *  OP_VRename
53826 **   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
53827 **
53828 ** Then check that the value of Parse.mayAbort is true if an
53829 ** ABORT may be thrown, or false otherwise. Return true if it does
53830 ** match, or false otherwise. This function is intended to be used as
53831 ** part of an assert statement in the compiler. Similar to:
53832 **
53833 **   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
53834 */
53835 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
53836   int hasAbort = 0;
53837   Op *pOp;
53838   VdbeOpIter sIter;
53839   memset(&sIter, 0, sizeof(sIter));
53840   sIter.v = v;
53841
53842   while( (pOp = opIterNext(&sIter))!=0 ){
53843     int opcode = pOp->opcode;
53844     if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename 
53845 #ifndef SQLITE_OMIT_FOREIGN_KEY
53846      || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1) 
53847 #endif
53848      || ((opcode==OP_Halt || opcode==OP_HaltIfNull) 
53849       && (pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
53850     ){
53851       hasAbort = 1;
53852       break;
53853     }
53854   }
53855   sqlite3DbFree(v->db, sIter.apSub);
53856
53857   /* Return true if hasAbort==mayAbort. Or if a malloc failure occured.
53858   ** If malloc failed, then the while() loop above may not have iterated
53859   ** through all opcodes and hasAbort may be set incorrectly. Return
53860   ** true for this case to prevent the assert() in the callers frame
53861   ** from failing.  */
53862   return ( v->db->mallocFailed || hasAbort==mayAbort );
53863 }
53864 #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
53865
53866 /*
53867 ** Loop through the program looking for P2 values that are negative
53868 ** on jump instructions.  Each such value is a label.  Resolve the
53869 ** label by setting the P2 value to its correct non-zero value.
53870 **
53871 ** This routine is called once after all opcodes have been inserted.
53872 **
53873 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument 
53874 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by 
53875 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
53876 **
53877 ** The Op.opflags field is set on all opcodes.
53878 */
53879 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
53880   int i;
53881   int nMaxArgs = *pMaxFuncArgs;
53882   Op *pOp;
53883   int *aLabel = p->aLabel;
53884   p->readOnly = 1;
53885   for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
53886     u8 opcode = pOp->opcode;
53887
53888     pOp->opflags = sqlite3OpcodeProperty[opcode];
53889     if( opcode==OP_Function || opcode==OP_AggStep ){
53890       if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
53891     }else if( opcode==OP_Transaction && pOp->p2!=0 ){
53892       p->readOnly = 0;
53893 #ifndef SQLITE_OMIT_VIRTUALTABLE
53894     }else if( opcode==OP_VUpdate ){
53895       if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
53896     }else if( opcode==OP_VFilter ){
53897       int n;
53898       assert( p->nOp - i >= 3 );
53899       assert( pOp[-1].opcode==OP_Integer );
53900       n = pOp[-1].p1;
53901       if( n>nMaxArgs ) nMaxArgs = n;
53902 #endif
53903     }
53904
53905     if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
53906       assert( -1-pOp->p2<p->nLabel );
53907       pOp->p2 = aLabel[-1-pOp->p2];
53908     }
53909   }
53910   sqlite3DbFree(p->db, p->aLabel);
53911   p->aLabel = 0;
53912
53913   *pMaxFuncArgs = nMaxArgs;
53914 }
53915
53916 /*
53917 ** Return the address of the next instruction to be inserted.
53918 */
53919 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
53920   assert( p->magic==VDBE_MAGIC_INIT );
53921   return p->nOp;
53922 }
53923
53924 /*
53925 ** This function returns a pointer to the array of opcodes associated with
53926 ** the Vdbe passed as the first argument. It is the callers responsibility
53927 ** to arrange for the returned array to be eventually freed using the 
53928 ** vdbeFreeOpArray() function.
53929 **
53930 ** Before returning, *pnOp is set to the number of entries in the returned
53931 ** array. Also, *pnMaxArg is set to the larger of its current value and 
53932 ** the number of entries in the Vdbe.apArg[] array required to execute the 
53933 ** returned program.
53934 */
53935 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
53936   VdbeOp *aOp = p->aOp;
53937   assert( aOp && !p->db->mallocFailed );
53938
53939   /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
53940   assert( p->aMutex.nMutex==0 );
53941
53942   resolveP2Values(p, pnMaxArg);
53943   *pnOp = p->nOp;
53944   p->aOp = 0;
53945   return aOp;
53946 }
53947
53948 /*
53949 ** Add a whole list of operations to the operation stack.  Return the
53950 ** address of the first operation added.
53951 */
53952 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
53953   int addr;
53954   assert( p->magic==VDBE_MAGIC_INIT );
53955   if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
53956     return 0;
53957   }
53958   addr = p->nOp;
53959   if( ALWAYS(nOp>0) ){
53960     int i;
53961     VdbeOpList const *pIn = aOp;
53962     for(i=0; i<nOp; i++, pIn++){
53963       int p2 = pIn->p2;
53964       VdbeOp *pOut = &p->aOp[i+addr];
53965       pOut->opcode = pIn->opcode;
53966       pOut->p1 = pIn->p1;
53967       if( p2<0 && (sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){
53968         pOut->p2 = addr + ADDR(p2);
53969       }else{
53970         pOut->p2 = p2;
53971       }
53972       pOut->p3 = pIn->p3;
53973       pOut->p4type = P4_NOTUSED;
53974       pOut->p4.p = 0;
53975       pOut->p5 = 0;
53976 #ifdef SQLITE_DEBUG
53977       pOut->zComment = 0;
53978       if( sqlite3VdbeAddopTrace ){
53979         sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
53980       }
53981 #endif
53982     }
53983     p->nOp += nOp;
53984   }
53985   return addr;
53986 }
53987
53988 /*
53989 ** Change the value of the P1 operand for a specific instruction.
53990 ** This routine is useful when a large program is loaded from a
53991 ** static array using sqlite3VdbeAddOpList but we want to make a
53992 ** few minor changes to the program.
53993 */
53994 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
53995   assert( p!=0 );
53996   assert( addr>=0 );
53997   if( p->nOp>addr ){
53998     p->aOp[addr].p1 = val;
53999   }
54000 }
54001
54002 /*
54003 ** Change the value of the P2 operand for a specific instruction.
54004 ** This routine is useful for setting a jump destination.
54005 */
54006 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
54007   assert( p!=0 );
54008   assert( addr>=0 );
54009   if( p->nOp>addr ){
54010     p->aOp[addr].p2 = val;
54011   }
54012 }
54013
54014 /*
54015 ** Change the value of the P3 operand for a specific instruction.
54016 */
54017 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, int addr, int val){
54018   assert( p!=0 );
54019   assert( addr>=0 );
54020   if( p->nOp>addr ){
54021     p->aOp[addr].p3 = val;
54022   }
54023 }
54024
54025 /*
54026 ** Change the value of the P5 operand for the most recently
54027 ** added operation.
54028 */
54029 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
54030   assert( p!=0 );
54031   if( p->aOp ){
54032     assert( p->nOp>0 );
54033     p->aOp[p->nOp-1].p5 = val;
54034   }
54035 }
54036
54037 /*
54038 ** Change the P2 operand of instruction addr so that it points to
54039 ** the address of the next instruction to be coded.
54040 */
54041 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
54042   sqlite3VdbeChangeP2(p, addr, p->nOp);
54043 }
54044
54045
54046 /*
54047 ** If the input FuncDef structure is ephemeral, then free it.  If
54048 ** the FuncDef is not ephermal, then do nothing.
54049 */
54050 static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
54051   if( ALWAYS(pDef) && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
54052     sqlite3DbFree(db, pDef);
54053   }
54054 }
54055
54056 /*
54057 ** Delete a P4 value if necessary.
54058 */
54059 static void freeP4(sqlite3 *db, int p4type, void *p4){
54060   if( p4 ){
54061     switch( p4type ){
54062       case P4_REAL:
54063       case P4_INT64:
54064       case P4_MPRINTF:
54065       case P4_DYNAMIC:
54066       case P4_KEYINFO:
54067       case P4_INTARRAY:
54068       case P4_KEYINFO_HANDOFF: {
54069         sqlite3DbFree(db, p4);
54070         break;
54071       }
54072       case P4_VDBEFUNC: {
54073         VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
54074         freeEphemeralFunction(db, pVdbeFunc->pFunc);
54075         sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
54076         sqlite3DbFree(db, pVdbeFunc);
54077         break;
54078       }
54079       case P4_FUNCDEF: {
54080         freeEphemeralFunction(db, (FuncDef*)p4);
54081         break;
54082       }
54083       case P4_MEM: {
54084         sqlite3ValueFree((sqlite3_value*)p4);
54085         break;
54086       }
54087       case P4_VTAB : {
54088         sqlite3VtabUnlock((VTable *)p4);
54089         break;
54090       }
54091       case P4_SUBPROGRAM : {
54092         sqlite3VdbeProgramDelete(db, (SubProgram *)p4, 1);
54093         break;
54094       }
54095     }
54096   }
54097 }
54098
54099 /*
54100 ** Free the space allocated for aOp and any p4 values allocated for the
54101 ** opcodes contained within. If aOp is not NULL it is assumed to contain 
54102 ** nOp entries. 
54103 */
54104 static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
54105   if( aOp ){
54106     Op *pOp;
54107     for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
54108       freeP4(db, pOp->p4type, pOp->p4.p);
54109 #ifdef SQLITE_DEBUG
54110       sqlite3DbFree(db, pOp->zComment);
54111 #endif     
54112     }
54113   }
54114   sqlite3DbFree(db, aOp);
54115 }
54116
54117 /*
54118 ** Decrement the ref-count on the SubProgram structure passed as the
54119 ** second argument. If the ref-count reaches zero, free the structure.
54120 **
54121 ** The array of VDBE opcodes stored as SubProgram.aOp is freed if
54122 ** either the ref-count reaches zero or parameter freeop is non-zero.
54123 **
54124 ** Since the array of opcodes pointed to by SubProgram.aOp may directly
54125 ** or indirectly contain a reference to the SubProgram structure itself.
54126 ** By passing a non-zero freeop parameter, the caller may ensure that all
54127 ** SubProgram structures and their aOp arrays are freed, even when there
54128 ** are such circular references.
54129 */
54130 SQLITE_PRIVATE void sqlite3VdbeProgramDelete(sqlite3 *db, SubProgram *p, int freeop){
54131   if( p ){
54132     assert( p->nRef>0 );
54133     if( freeop || p->nRef==1 ){
54134       Op *aOp = p->aOp;
54135       p->aOp = 0;
54136       vdbeFreeOpArray(db, aOp, p->nOp);
54137       p->nOp = 0;
54138     }
54139     p->nRef--;
54140     if( p->nRef==0 ){
54141       sqlite3DbFree(db, p);
54142     }
54143   }
54144 }
54145
54146
54147 /*
54148 ** Change N opcodes starting at addr to No-ops.
54149 */
54150 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr, int N){
54151   if( p->aOp ){
54152     VdbeOp *pOp = &p->aOp[addr];
54153     sqlite3 *db = p->db;
54154     while( N-- ){
54155       freeP4(db, pOp->p4type, pOp->p4.p);
54156       memset(pOp, 0, sizeof(pOp[0]));
54157       pOp->opcode = OP_Noop;
54158       pOp++;
54159     }
54160   }
54161 }
54162
54163 /*
54164 ** Change the value of the P4 operand for a specific instruction.
54165 ** This routine is useful when a large program is loaded from a
54166 ** static array using sqlite3VdbeAddOpList but we want to make a
54167 ** few minor changes to the program.
54168 **
54169 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
54170 ** the string is made into memory obtained from sqlite3_malloc().
54171 ** A value of n==0 means copy bytes of zP4 up to and including the
54172 ** first null byte.  If n>0 then copy n+1 bytes of zP4.
54173 **
54174 ** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
54175 ** A copy is made of the KeyInfo structure into memory obtained from
54176 ** sqlite3_malloc, to be freed when the Vdbe is finalized.
54177 ** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
54178 ** stored in memory that the caller has obtained from sqlite3_malloc. The 
54179 ** caller should not free the allocation, it will be freed when the Vdbe is
54180 ** finalized.
54181 ** 
54182 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
54183 ** to a string or structure that is guaranteed to exist for the lifetime of
54184 ** the Vdbe. In these cases we can just copy the pointer.
54185 **
54186 ** If addr<0 then change P4 on the most recently inserted instruction.
54187 */
54188 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
54189   Op *pOp;
54190   sqlite3 *db;
54191   assert( p!=0 );
54192   db = p->db;
54193   assert( p->magic==VDBE_MAGIC_INIT );
54194   if( p->aOp==0 || db->mallocFailed ){
54195     if ( n!=P4_KEYINFO && n!=P4_VTAB ) {
54196       freeP4(db, n, (void*)*(char**)&zP4);
54197     }
54198     return;
54199   }
54200   assert( p->nOp>0 );
54201   assert( addr<p->nOp );
54202   if( addr<0 ){
54203     addr = p->nOp - 1;
54204   }
54205   pOp = &p->aOp[addr];
54206   freeP4(db, pOp->p4type, pOp->p4.p);
54207   pOp->p4.p = 0;
54208   if( n==P4_INT32 ){
54209     /* Note: this cast is safe, because the origin data point was an int
54210     ** that was cast to a (const char *). */
54211     pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
54212     pOp->p4type = P4_INT32;
54213   }else if( zP4==0 ){
54214     pOp->p4.p = 0;
54215     pOp->p4type = P4_NOTUSED;
54216   }else if( n==P4_KEYINFO ){
54217     KeyInfo *pKeyInfo;
54218     int nField, nByte;
54219
54220     nField = ((KeyInfo*)zP4)->nField;
54221     nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
54222     pKeyInfo = sqlite3Malloc( nByte );
54223     pOp->p4.pKeyInfo = pKeyInfo;
54224     if( pKeyInfo ){
54225       u8 *aSortOrder;
54226       memcpy((char*)pKeyInfo, zP4, nByte - nField);
54227       aSortOrder = pKeyInfo->aSortOrder;
54228       if( aSortOrder ){
54229         pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
54230         memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
54231       }
54232       pOp->p4type = P4_KEYINFO;
54233     }else{
54234       p->db->mallocFailed = 1;
54235       pOp->p4type = P4_NOTUSED;
54236     }
54237   }else if( n==P4_KEYINFO_HANDOFF ){
54238     pOp->p4.p = (void*)zP4;
54239     pOp->p4type = P4_KEYINFO;
54240   }else if( n==P4_VTAB ){
54241     pOp->p4.p = (void*)zP4;
54242     pOp->p4type = P4_VTAB;
54243     sqlite3VtabLock((VTable *)zP4);
54244     assert( ((VTable *)zP4)->db==p->db );
54245   }else if( n<0 ){
54246     pOp->p4.p = (void*)zP4;
54247     pOp->p4type = (signed char)n;
54248   }else{
54249     if( n==0 ) n = sqlite3Strlen30(zP4);
54250     pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
54251     pOp->p4type = P4_DYNAMIC;
54252   }
54253 }
54254
54255 #ifndef NDEBUG
54256 /*
54257 ** Change the comment on the the most recently coded instruction.  Or
54258 ** insert a No-op and add the comment to that new instruction.  This
54259 ** makes the code easier to read during debugging.  None of this happens
54260 ** in a production build.
54261 */
54262 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
54263   va_list ap;
54264   if( !p ) return;
54265   assert( p->nOp>0 || p->aOp==0 );
54266   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
54267   if( p->nOp ){
54268     char **pz = &p->aOp[p->nOp-1].zComment;
54269     va_start(ap, zFormat);
54270     sqlite3DbFree(p->db, *pz);
54271     *pz = sqlite3VMPrintf(p->db, zFormat, ap);
54272     va_end(ap);
54273   }
54274 }
54275 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
54276   va_list ap;
54277   if( !p ) return;
54278   sqlite3VdbeAddOp0(p, OP_Noop);
54279   assert( p->nOp>0 || p->aOp==0 );
54280   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
54281   if( p->nOp ){
54282     char **pz = &p->aOp[p->nOp-1].zComment;
54283     va_start(ap, zFormat);
54284     sqlite3DbFree(p->db, *pz);
54285     *pz = sqlite3VMPrintf(p->db, zFormat, ap);
54286     va_end(ap);
54287   }
54288 }
54289 #endif  /* NDEBUG */
54290
54291 /*
54292 ** Return the opcode for a given address.  If the address is -1, then
54293 ** return the most recently inserted opcode.
54294 **
54295 ** If a memory allocation error has occurred prior to the calling of this
54296 ** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
54297 ** is readable but not writable, though it is cast to a writable value.
54298 ** The return of a dummy opcode allows the call to continue functioning
54299 ** after a OOM fault without having to check to see if the return from 
54300 ** this routine is a valid pointer.  But because the dummy.opcode is 0,
54301 ** dummy will never be written to.  This is verified by code inspection and
54302 ** by running with Valgrind.
54303 **
54304 ** About the #ifdef SQLITE_OMIT_TRACE:  Normally, this routine is never called
54305 ** unless p->nOp>0.  This is because in the absense of SQLITE_OMIT_TRACE,
54306 ** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
54307 ** a new VDBE is created.  So we are free to set addr to p->nOp-1 without
54308 ** having to double-check to make sure that the result is non-negative. But
54309 ** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
54310 ** check the value of p->nOp-1 before continuing.
54311 */
54312 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
54313   /* C89 specifies that the constant "dummy" will be initialized to all
54314   ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
54315   static const VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
54316   assert( p->magic==VDBE_MAGIC_INIT );
54317   if( addr<0 ){
54318 #ifdef SQLITE_OMIT_TRACE
54319     if( p->nOp==0 ) return (VdbeOp*)&dummy;
54320 #endif
54321     addr = p->nOp - 1;
54322   }
54323   assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
54324   if( p->db->mallocFailed ){
54325     return (VdbeOp*)&dummy;
54326   }else{
54327     return &p->aOp[addr];
54328   }
54329 }
54330
54331 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
54332      || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
54333 /*
54334 ** Compute a string that describes the P4 parameter for an opcode.
54335 ** Use zTemp for any required temporary buffer space.
54336 */
54337 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
54338   char *zP4 = zTemp;
54339   assert( nTemp>=20 );
54340   switch( pOp->p4type ){
54341     case P4_KEYINFO_STATIC:
54342     case P4_KEYINFO: {
54343       int i, j;
54344       KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
54345       sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
54346       i = sqlite3Strlen30(zTemp);
54347       for(j=0; j<pKeyInfo->nField; j++){
54348         CollSeq *pColl = pKeyInfo->aColl[j];
54349         if( pColl ){
54350           int n = sqlite3Strlen30(pColl->zName);
54351           if( i+n>nTemp-6 ){
54352             memcpy(&zTemp[i],",...",4);
54353             break;
54354           }
54355           zTemp[i++] = ',';
54356           if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
54357             zTemp[i++] = '-';
54358           }
54359           memcpy(&zTemp[i], pColl->zName,n+1);
54360           i += n;
54361         }else if( i+4<nTemp-6 ){
54362           memcpy(&zTemp[i],",nil",4);
54363           i += 4;
54364         }
54365       }
54366       zTemp[i++] = ')';
54367       zTemp[i] = 0;
54368       assert( i<nTemp );
54369       break;
54370     }
54371     case P4_COLLSEQ: {
54372       CollSeq *pColl = pOp->p4.pColl;
54373       sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
54374       break;
54375     }
54376     case P4_FUNCDEF: {
54377       FuncDef *pDef = pOp->p4.pFunc;
54378       sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
54379       break;
54380     }
54381     case P4_INT64: {
54382       sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
54383       break;
54384     }
54385     case P4_INT32: {
54386       sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
54387       break;
54388     }
54389     case P4_REAL: {
54390       sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
54391       break;
54392     }
54393     case P4_MEM: {
54394       Mem *pMem = pOp->p4.pMem;
54395       assert( (pMem->flags & MEM_Null)==0 );
54396       if( pMem->flags & MEM_Str ){
54397         zP4 = pMem->z;
54398       }else if( pMem->flags & MEM_Int ){
54399         sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
54400       }else if( pMem->flags & MEM_Real ){
54401         sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
54402       }else{
54403         assert( pMem->flags & MEM_Blob );
54404         zP4 = "(blob)";
54405       }
54406       break;
54407     }
54408 #ifndef SQLITE_OMIT_VIRTUALTABLE
54409     case P4_VTAB: {
54410       sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
54411       sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
54412       break;
54413     }
54414 #endif
54415     case P4_INTARRAY: {
54416       sqlite3_snprintf(nTemp, zTemp, "intarray");
54417       break;
54418     }
54419     case P4_SUBPROGRAM: {
54420       sqlite3_snprintf(nTemp, zTemp, "program");
54421       break;
54422     }
54423     default: {
54424       zP4 = pOp->p4.z;
54425       if( zP4==0 ){
54426         zP4 = zTemp;
54427         zTemp[0] = 0;
54428       }
54429     }
54430   }
54431   assert( zP4!=0 );
54432   return zP4;
54433 }
54434 #endif
54435
54436 /*
54437 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
54438 **
54439 ** The prepared statement has to know in advance which Btree objects
54440 ** will be used so that it can acquire mutexes on them all in sorted
54441 ** order (via sqlite3VdbeMutexArrayEnter().  Mutexes are acquired
54442 ** in order (and released in reverse order) to avoid deadlocks.
54443 */
54444 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
54445   int mask;
54446   assert( i>=0 && i<p->db->nDb && i<sizeof(u32)*8 );
54447   assert( i<(int)sizeof(p->btreeMask)*8 );
54448   mask = ((u32)1)<<i;
54449   if( (p->btreeMask & mask)==0 ){
54450     p->btreeMask |= mask;
54451     sqlite3BtreeMutexArrayInsert(&p->aMutex, p->db->aDb[i].pBt);
54452   }
54453 }
54454
54455
54456 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
54457 /*
54458 ** Print a single opcode.  This routine is used for debugging only.
54459 */
54460 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
54461   char *zP4;
54462   char zPtr[50];
54463   static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
54464   if( pOut==0 ) pOut = stdout;
54465   zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
54466   fprintf(pOut, zFormat1, pc, 
54467       sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
54468 #ifdef SQLITE_DEBUG
54469       pOp->zComment ? pOp->zComment : ""
54470 #else
54471       ""
54472 #endif
54473   );
54474   fflush(pOut);
54475 }
54476 #endif
54477
54478 /*
54479 ** Release an array of N Mem elements
54480 */
54481 static void releaseMemArray(Mem *p, int N){
54482   if( p && N ){
54483     Mem *pEnd;
54484     sqlite3 *db = p->db;
54485     u8 malloc_failed = db->mallocFailed;
54486     for(pEnd=&p[N]; p<pEnd; p++){
54487       assert( (&p[1])==pEnd || p[0].db==p[1].db );
54488
54489       /* This block is really an inlined version of sqlite3VdbeMemRelease()
54490       ** that takes advantage of the fact that the memory cell value is 
54491       ** being set to NULL after releasing any dynamic resources.
54492       **
54493       ** The justification for duplicating code is that according to 
54494       ** callgrind, this causes a certain test case to hit the CPU 4.7 
54495       ** percent less (x86 linux, gcc version 4.1.2, -O6) than if 
54496       ** sqlite3MemRelease() were called from here. With -O2, this jumps
54497       ** to 6.6 percent. The test case is inserting 1000 rows into a table 
54498       ** with no indexes using a single prepared INSERT statement, bind() 
54499       ** and reset(). Inserts are grouped into a transaction.
54500       */
54501       if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
54502         sqlite3VdbeMemRelease(p);
54503       }else if( p->zMalloc ){
54504         sqlite3DbFree(db, p->zMalloc);
54505         p->zMalloc = 0;
54506       }
54507
54508       p->flags = MEM_Null;
54509     }
54510     db->mallocFailed = malloc_failed;
54511   }
54512 }
54513
54514 /*
54515 ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
54516 ** allocated by the OP_Program opcode in sqlite3VdbeExec().
54517 */
54518 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
54519   int i;
54520   Mem *aMem = VdbeFrameMem(p);
54521   VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
54522   for(i=0; i<p->nChildCsr; i++){
54523     sqlite3VdbeFreeCursor(p->v, apCsr[i]);
54524   }
54525   releaseMemArray(aMem, p->nChildMem);
54526   sqlite3DbFree(p->v->db, p);
54527 }
54528
54529 #ifndef SQLITE_OMIT_EXPLAIN
54530 /*
54531 ** Give a listing of the program in the virtual machine.
54532 **
54533 ** The interface is the same as sqlite3VdbeExec().  But instead of
54534 ** running the code, it invokes the callback once for each instruction.
54535 ** This feature is used to implement "EXPLAIN".
54536 **
54537 ** When p->explain==1, each instruction is listed.  When
54538 ** p->explain==2, only OP_Explain instructions are listed and these
54539 ** are shown in a different format.  p->explain==2 is used to implement
54540 ** EXPLAIN QUERY PLAN.
54541 **
54542 ** When p->explain==1, first the main program is listed, then each of
54543 ** the trigger subprograms are listed one by one.
54544 */
54545 SQLITE_PRIVATE int sqlite3VdbeList(
54546   Vdbe *p                   /* The VDBE */
54547 ){
54548   int nRow;                            /* Stop when row count reaches this */
54549   int nSub = 0;                        /* Number of sub-vdbes seen so far */
54550   SubProgram **apSub = 0;              /* Array of sub-vdbes */
54551   Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
54552   sqlite3 *db = p->db;                 /* The database connection */
54553   int i;                               /* Loop counter */
54554   int rc = SQLITE_OK;                  /* Return code */
54555   Mem *pMem = p->pResultSet = &p->aMem[1];  /* First Mem of result set */
54556
54557   assert( p->explain );
54558   assert( p->magic==VDBE_MAGIC_RUN );
54559   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
54560
54561   /* Even though this opcode does not use dynamic strings for
54562   ** the result, result columns may become dynamic if the user calls
54563   ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
54564   */
54565   releaseMemArray(pMem, 8);
54566
54567   if( p->rc==SQLITE_NOMEM ){
54568     /* This happens if a malloc() inside a call to sqlite3_column_text() or
54569     ** sqlite3_column_text16() failed.  */
54570     db->mallocFailed = 1;
54571     return SQLITE_ERROR;
54572   }
54573
54574   /* When the number of output rows reaches nRow, that means the
54575   ** listing has finished and sqlite3_step() should return SQLITE_DONE.
54576   ** nRow is the sum of the number of rows in the main program, plus
54577   ** the sum of the number of rows in all trigger subprograms encountered
54578   ** so far.  The nRow value will increase as new trigger subprograms are
54579   ** encountered, but p->pc will eventually catch up to nRow.
54580   */
54581   nRow = p->nOp;
54582   if( p->explain==1 ){
54583     /* The first 8 memory cells are used for the result set.  So we will
54584     ** commandeer the 9th cell to use as storage for an array of pointers
54585     ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
54586     ** cells.  */
54587     assert( p->nMem>9 );
54588     pSub = &p->aMem[9];
54589     if( pSub->flags&MEM_Blob ){
54590       /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
54591       ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
54592       nSub = pSub->n/sizeof(Vdbe*);
54593       apSub = (SubProgram **)pSub->z;
54594     }
54595     for(i=0; i<nSub; i++){
54596       nRow += apSub[i]->nOp;
54597     }
54598   }
54599
54600   do{
54601     i = p->pc++;
54602   }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
54603   if( i>=nRow ){
54604     p->rc = SQLITE_OK;
54605     rc = SQLITE_DONE;
54606   }else if( db->u1.isInterrupted ){
54607     p->rc = SQLITE_INTERRUPT;
54608     rc = SQLITE_ERROR;
54609     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
54610   }else{
54611     char *z;
54612     Op *pOp;
54613     if( i<p->nOp ){
54614       /* The output line number is small enough that we are still in the
54615       ** main program. */
54616       pOp = &p->aOp[i];
54617     }else{
54618       /* We are currently listing subprograms.  Figure out which one and
54619       ** pick up the appropriate opcode. */
54620       int j;
54621       i -= p->nOp;
54622       for(j=0; i>=apSub[j]->nOp; j++){
54623         i -= apSub[j]->nOp;
54624       }
54625       pOp = &apSub[j]->aOp[i];
54626     }
54627     if( p->explain==1 ){
54628       pMem->flags = MEM_Int;
54629       pMem->type = SQLITE_INTEGER;
54630       pMem->u.i = i;                                /* Program counter */
54631       pMem++;
54632   
54633       pMem->flags = MEM_Static|MEM_Str|MEM_Term;
54634       pMem->z = (char*)sqlite3OpcodeName(pOp->opcode);  /* Opcode */
54635       assert( pMem->z!=0 );
54636       pMem->n = sqlite3Strlen30(pMem->z);
54637       pMem->type = SQLITE_TEXT;
54638       pMem->enc = SQLITE_UTF8;
54639       pMem++;
54640
54641       /* When an OP_Program opcode is encounter (the only opcode that has
54642       ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
54643       ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
54644       ** has not already been seen.
54645       */
54646       if( pOp->p4type==P4_SUBPROGRAM ){
54647         int nByte = (nSub+1)*sizeof(SubProgram*);
54648         int j;
54649         for(j=0; j<nSub; j++){
54650           if( apSub[j]==pOp->p4.pProgram ) break;
54651         }
54652         if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, 1) ){
54653           apSub = (SubProgram **)pSub->z;
54654           apSub[nSub++] = pOp->p4.pProgram;
54655           pSub->flags |= MEM_Blob;
54656           pSub->n = nSub*sizeof(SubProgram*);
54657         }
54658       }
54659     }
54660
54661     pMem->flags = MEM_Int;
54662     pMem->u.i = pOp->p1;                          /* P1 */
54663     pMem->type = SQLITE_INTEGER;
54664     pMem++;
54665
54666     pMem->flags = MEM_Int;
54667     pMem->u.i = pOp->p2;                          /* P2 */
54668     pMem->type = SQLITE_INTEGER;
54669     pMem++;
54670
54671     if( p->explain==1 ){
54672       pMem->flags = MEM_Int;
54673       pMem->u.i = pOp->p3;                          /* P3 */
54674       pMem->type = SQLITE_INTEGER;
54675       pMem++;
54676     }
54677
54678     if( sqlite3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
54679       assert( p->db->mallocFailed );
54680       return SQLITE_ERROR;
54681     }
54682     pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
54683     z = displayP4(pOp, pMem->z, 32);
54684     if( z!=pMem->z ){
54685       sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
54686     }else{
54687       assert( pMem->z!=0 );
54688       pMem->n = sqlite3Strlen30(pMem->z);
54689       pMem->enc = SQLITE_UTF8;
54690     }
54691     pMem->type = SQLITE_TEXT;
54692     pMem++;
54693
54694     if( p->explain==1 ){
54695       if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
54696         assert( p->db->mallocFailed );
54697         return SQLITE_ERROR;
54698       }
54699       pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
54700       pMem->n = 2;
54701       sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
54702       pMem->type = SQLITE_TEXT;
54703       pMem->enc = SQLITE_UTF8;
54704       pMem++;
54705   
54706 #ifdef SQLITE_DEBUG
54707       if( pOp->zComment ){
54708         pMem->flags = MEM_Str|MEM_Term;
54709         pMem->z = pOp->zComment;
54710         pMem->n = sqlite3Strlen30(pMem->z);
54711         pMem->enc = SQLITE_UTF8;
54712         pMem->type = SQLITE_TEXT;
54713       }else
54714 #endif
54715       {
54716         pMem->flags = MEM_Null;                       /* Comment */
54717         pMem->type = SQLITE_NULL;
54718       }
54719     }
54720
54721     p->nResColumn = 8 - 5*(p->explain-1);
54722     p->rc = SQLITE_OK;
54723     rc = SQLITE_ROW;
54724   }
54725   return rc;
54726 }
54727 #endif /* SQLITE_OMIT_EXPLAIN */
54728
54729 #ifdef SQLITE_DEBUG
54730 /*
54731 ** Print the SQL that was used to generate a VDBE program.
54732 */
54733 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
54734   int nOp = p->nOp;
54735   VdbeOp *pOp;
54736   if( nOp<1 ) return;
54737   pOp = &p->aOp[0];
54738   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
54739     const char *z = pOp->p4.z;
54740     while( sqlite3Isspace(*z) ) z++;
54741     printf("SQL: [%s]\n", z);
54742   }
54743 }
54744 #endif
54745
54746 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
54747 /*
54748 ** Print an IOTRACE message showing SQL content.
54749 */
54750 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
54751   int nOp = p->nOp;
54752   VdbeOp *pOp;
54753   if( sqlite3IoTrace==0 ) return;
54754   if( nOp<1 ) return;
54755   pOp = &p->aOp[0];
54756   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
54757     int i, j;
54758     char z[1000];
54759     sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
54760     for(i=0; sqlite3Isspace(z[i]); i++){}
54761     for(j=0; z[i]; i++){
54762       if( sqlite3Isspace(z[i]) ){
54763         if( z[i-1]!=' ' ){
54764           z[j++] = ' ';
54765         }
54766       }else{
54767         z[j++] = z[i];
54768       }
54769     }
54770     z[j] = 0;
54771     sqlite3IoTrace("SQL %s\n", z);
54772   }
54773 }
54774 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
54775
54776 /*
54777 ** Allocate space from a fixed size buffer and return a pointer to
54778 ** that space.  If insufficient space is available, return NULL.
54779 **
54780 ** The pBuf parameter is the initial value of a pointer which will
54781 ** receive the new memory.  pBuf is normally NULL.  If pBuf is not
54782 ** NULL, it means that memory space has already been allocated and that
54783 ** this routine should not allocate any new memory.  When pBuf is not
54784 ** NULL simply return pBuf.  Only allocate new memory space when pBuf
54785 ** is NULL.
54786 **
54787 ** nByte is the number of bytes of space needed.
54788 **
54789 ** *ppFrom points to available space and pEnd points to the end of the
54790 ** available space.  When space is allocated, *ppFrom is advanced past
54791 ** the end of the allocated space.
54792 **
54793 ** *pnByte is a counter of the number of bytes of space that have failed
54794 ** to allocate.  If there is insufficient space in *ppFrom to satisfy the
54795 ** request, then increment *pnByte by the amount of the request.
54796 */
54797 static void *allocSpace(
54798   void *pBuf,          /* Where return pointer will be stored */
54799   int nByte,           /* Number of bytes to allocate */
54800   u8 **ppFrom,         /* IN/OUT: Allocate from *ppFrom */
54801   u8 *pEnd,            /* Pointer to 1 byte past the end of *ppFrom buffer */
54802   int *pnByte          /* If allocation cannot be made, increment *pnByte */
54803 ){
54804   assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
54805   if( pBuf ) return pBuf;
54806   nByte = ROUND8(nByte);
54807   if( &(*ppFrom)[nByte] <= pEnd ){
54808     pBuf = (void*)*ppFrom;
54809     *ppFrom += nByte;
54810   }else{
54811     *pnByte += nByte;
54812   }
54813   return pBuf;
54814 }
54815
54816 /*
54817 ** Prepare a virtual machine for execution.  This involves things such
54818 ** as allocating stack space and initializing the program counter.
54819 ** After the VDBE has be prepped, it can be executed by one or more
54820 ** calls to sqlite3VdbeExec().  
54821 **
54822 ** This is the only way to move a VDBE from VDBE_MAGIC_INIT to
54823 ** VDBE_MAGIC_RUN.
54824 **
54825 ** This function may be called more than once on a single virtual machine.
54826 ** The first call is made while compiling the SQL statement. Subsequent
54827 ** calls are made as part of the process of resetting a statement to be
54828 ** re-executed (from a call to sqlite3_reset()). The nVar, nMem, nCursor 
54829 ** and isExplain parameters are only passed correct values the first time
54830 ** the function is called. On subsequent calls, from sqlite3_reset(), nVar
54831 ** is passed -1 and nMem, nCursor and isExplain are all passed zero.
54832 */
54833 SQLITE_PRIVATE void sqlite3VdbeMakeReady(
54834   Vdbe *p,                       /* The VDBE */
54835   int nVar,                      /* Number of '?' see in the SQL statement */
54836   int nMem,                      /* Number of memory cells to allocate */
54837   int nCursor,                   /* Number of cursors to allocate */
54838   int nArg,                      /* Maximum number of args in SubPrograms */
54839   int isExplain,                 /* True if the EXPLAIN keywords is present */
54840   int usesStmtJournal            /* True to set Vdbe.usesStmtJournal */
54841 ){
54842   int n;
54843   sqlite3 *db = p->db;
54844
54845   assert( p!=0 );
54846   assert( p->magic==VDBE_MAGIC_INIT );
54847
54848   /* There should be at least one opcode.
54849   */
54850   assert( p->nOp>0 );
54851
54852   /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
54853   p->magic = VDBE_MAGIC_RUN;
54854
54855   /* For each cursor required, also allocate a memory cell. Memory
54856   ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
54857   ** the vdbe program. Instead they are used to allocate space for
54858   ** VdbeCursor/BtCursor structures. The blob of memory associated with 
54859   ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
54860   ** stores the blob of memory associated with cursor 1, etc.
54861   **
54862   ** See also: allocateCursor().
54863   */
54864   nMem += nCursor;
54865
54866   /* Allocate space for memory registers, SQL variables, VDBE cursors and 
54867   ** an array to marshal SQL function arguments in. This is only done the
54868   ** first time this function is called for a given VDBE, not when it is
54869   ** being called from sqlite3_reset() to reset the virtual machine.
54870   */
54871   if( nVar>=0 && ALWAYS(db->mallocFailed==0) ){
54872     u8 *zCsr = (u8 *)&p->aOp[p->nOp];       /* Memory avaliable for alloation */
54873     u8 *zEnd = (u8 *)&p->aOp[p->nOpAlloc];  /* First byte past available mem */
54874     int nByte;                              /* How much extra memory needed */
54875
54876     resolveP2Values(p, &nArg);
54877     p->usesStmtJournal = (u8)usesStmtJournal;
54878     if( isExplain && nMem<10 ){
54879       nMem = 10;
54880     }
54881     memset(zCsr, 0, zEnd-zCsr);
54882     zCsr += (zCsr - (u8*)0)&7;
54883     assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
54884
54885     /* Memory for registers, parameters, cursor, etc, is allocated in two
54886     ** passes.  On the first pass, we try to reuse unused space at the 
54887     ** end of the opcode array.  If we are unable to satisfy all memory
54888     ** requirements by reusing the opcode array tail, then the second
54889     ** pass will fill in the rest using a fresh allocation.  
54890     **
54891     ** This two-pass approach that reuses as much memory as possible from
54892     ** the leftover space at the end of the opcode array can significantly
54893     ** reduce the amount of memory held by a prepared statement.
54894     */
54895     do {
54896       nByte = 0;
54897       p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
54898       p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
54899       p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
54900       p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
54901       p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
54902                             &zCsr, zEnd, &nByte);
54903       if( nByte ){
54904         p->pFree = sqlite3DbMallocZero(db, nByte);
54905       }
54906       zCsr = p->pFree;
54907       zEnd = &zCsr[nByte];
54908     }while( nByte && !db->mallocFailed );
54909
54910     p->nCursor = (u16)nCursor;
54911     if( p->aVar ){
54912       p->nVar = (ynVar)nVar;
54913       for(n=0; n<nVar; n++){
54914         p->aVar[n].flags = MEM_Null;
54915         p->aVar[n].db = db;
54916       }
54917     }
54918     if( p->aMem ){
54919       p->aMem--;                      /* aMem[] goes from 1..nMem */
54920       p->nMem = nMem;                 /*       not from 0..nMem-1 */
54921       for(n=1; n<=nMem; n++){
54922         p->aMem[n].flags = MEM_Null;
54923         p->aMem[n].db = db;
54924       }
54925     }
54926   }
54927 #ifdef SQLITE_DEBUG
54928   for(n=1; n<p->nMem; n++){
54929     assert( p->aMem[n].db==db );
54930   }
54931 #endif
54932
54933   p->pc = -1;
54934   p->rc = SQLITE_OK;
54935   p->errorAction = OE_Abort;
54936   p->explain |= isExplain;
54937   p->magic = VDBE_MAGIC_RUN;
54938   p->nChange = 0;
54939   p->cacheCtr = 1;
54940   p->minWriteFileFormat = 255;
54941   p->iStatement = 0;
54942   p->nFkConstraint = 0;
54943 #ifdef VDBE_PROFILE
54944   {
54945     int i;
54946     for(i=0; i<p->nOp; i++){
54947       p->aOp[i].cnt = 0;
54948       p->aOp[i].cycles = 0;
54949     }
54950   }
54951 #endif
54952 }
54953
54954 /*
54955 ** Close a VDBE cursor and release all the resources that cursor 
54956 ** happens to hold.
54957 */
54958 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
54959   if( pCx==0 ){
54960     return;
54961   }
54962   if( pCx->pBt ){
54963     sqlite3BtreeClose(pCx->pBt);
54964     /* The pCx->pCursor will be close automatically, if it exists, by
54965     ** the call above. */
54966   }else if( pCx->pCursor ){
54967     sqlite3BtreeCloseCursor(pCx->pCursor);
54968   }
54969 #ifndef SQLITE_OMIT_VIRTUALTABLE
54970   if( pCx->pVtabCursor ){
54971     sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
54972     const sqlite3_module *pModule = pCx->pModule;
54973     p->inVtabMethod = 1;
54974     pModule->xClose(pVtabCursor);
54975     p->inVtabMethod = 0;
54976   }
54977 #endif
54978 }
54979
54980 /*
54981 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
54982 ** is used, for example, when a trigger sub-program is halted to restore
54983 ** control to the main program.
54984 */
54985 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
54986   Vdbe *v = pFrame->v;
54987   v->aOp = pFrame->aOp;
54988   v->nOp = pFrame->nOp;
54989   v->aMem = pFrame->aMem;
54990   v->nMem = pFrame->nMem;
54991   v->apCsr = pFrame->apCsr;
54992   v->nCursor = pFrame->nCursor;
54993   v->db->lastRowid = pFrame->lastRowid;
54994   v->nChange = pFrame->nChange;
54995   return pFrame->pc;
54996 }
54997
54998 /*
54999 ** Close all cursors.
55000 **
55001 ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory 
55002 ** cell array. This is necessary as the memory cell array may contain
55003 ** pointers to VdbeFrame objects, which may in turn contain pointers to
55004 ** open cursors.
55005 */
55006 static void closeAllCursors(Vdbe *p){
55007   if( p->pFrame ){
55008     VdbeFrame *pFrame = p->pFrame;
55009     for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
55010     sqlite3VdbeFrameRestore(pFrame);
55011   }
55012   p->pFrame = 0;
55013   p->nFrame = 0;
55014
55015   if( p->apCsr ){
55016     int i;
55017     for(i=0; i<p->nCursor; i++){
55018       VdbeCursor *pC = p->apCsr[i];
55019       if( pC ){
55020         sqlite3VdbeFreeCursor(p, pC);
55021         p->apCsr[i] = 0;
55022       }
55023     }
55024   }
55025   if( p->aMem ){
55026     releaseMemArray(&p->aMem[1], p->nMem);
55027   }
55028 }
55029
55030 /*
55031 ** Clean up the VM after execution.
55032 **
55033 ** This routine will automatically close any cursors, lists, and/or
55034 ** sorters that were left open.  It also deletes the values of
55035 ** variables in the aVar[] array.
55036 */
55037 static void Cleanup(Vdbe *p){
55038   sqlite3 *db = p->db;
55039
55040 #ifdef SQLITE_DEBUG
55041   /* Execute assert() statements to ensure that the Vdbe.apCsr[] and 
55042   ** Vdbe.aMem[] arrays have already been cleaned up.  */
55043   int i;
55044   for(i=0; i<p->nCursor; i++) assert( p->apCsr==0 || p->apCsr[i]==0 );
55045   for(i=1; i<=p->nMem; i++) assert( p->aMem==0 || p->aMem[i].flags==MEM_Null );
55046 #endif
55047
55048   sqlite3DbFree(db, p->zErrMsg);
55049   p->zErrMsg = 0;
55050   p->pResultSet = 0;
55051 }
55052
55053 /*
55054 ** Set the number of result columns that will be returned by this SQL
55055 ** statement. This is now set at compile time, rather than during
55056 ** execution of the vdbe program so that sqlite3_column_count() can
55057 ** be called on an SQL statement before sqlite3_step().
55058 */
55059 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
55060   Mem *pColName;
55061   int n;
55062   sqlite3 *db = p->db;
55063
55064   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
55065   sqlite3DbFree(db, p->aColName);
55066   n = nResColumn*COLNAME_N;
55067   p->nResColumn = (u16)nResColumn;
55068   p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
55069   if( p->aColName==0 ) return;
55070   while( n-- > 0 ){
55071     pColName->flags = MEM_Null;
55072     pColName->db = p->db;
55073     pColName++;
55074   }
55075 }
55076
55077 /*
55078 ** Set the name of the idx'th column to be returned by the SQL statement.
55079 ** zName must be a pointer to a nul terminated string.
55080 **
55081 ** This call must be made after a call to sqlite3VdbeSetNumCols().
55082 **
55083 ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
55084 ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
55085 ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
55086 */
55087 SQLITE_PRIVATE int sqlite3VdbeSetColName(
55088   Vdbe *p,                         /* Vdbe being configured */
55089   int idx,                         /* Index of column zName applies to */
55090   int var,                         /* One of the COLNAME_* constants */
55091   const char *zName,               /* Pointer to buffer containing name */
55092   void (*xDel)(void*)              /* Memory management strategy for zName */
55093 ){
55094   int rc;
55095   Mem *pColName;
55096   assert( idx<p->nResColumn );
55097   assert( var<COLNAME_N );
55098   if( p->db->mallocFailed ){
55099     assert( !zName || xDel!=SQLITE_DYNAMIC );
55100     return SQLITE_NOMEM;
55101   }
55102   assert( p->aColName!=0 );
55103   pColName = &(p->aColName[idx+var*p->nResColumn]);
55104   rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
55105   assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
55106   return rc;
55107 }
55108
55109 /*
55110 ** A read or write transaction may or may not be active on database handle
55111 ** db. If a transaction is active, commit it. If there is a
55112 ** write-transaction spanning more than one database file, this routine
55113 ** takes care of the master journal trickery.
55114 */
55115 static int vdbeCommit(sqlite3 *db, Vdbe *p){
55116   int i;
55117   int nTrans = 0;  /* Number of databases with an active write-transaction */
55118   int rc = SQLITE_OK;
55119   int needXcommit = 0;
55120
55121 #ifdef SQLITE_OMIT_VIRTUALTABLE
55122   /* With this option, sqlite3VtabSync() is defined to be simply 
55123   ** SQLITE_OK so p is not used. 
55124   */
55125   UNUSED_PARAMETER(p);
55126 #endif
55127
55128   /* Before doing anything else, call the xSync() callback for any
55129   ** virtual module tables written in this transaction. This has to
55130   ** be done before determining whether a master journal file is 
55131   ** required, as an xSync() callback may add an attached database
55132   ** to the transaction.
55133   */
55134   rc = sqlite3VtabSync(db, &p->zErrMsg);
55135   if( rc!=SQLITE_OK ){
55136     return rc;
55137   }
55138
55139   /* This loop determines (a) if the commit hook should be invoked and
55140   ** (b) how many database files have open write transactions, not 
55141   ** including the temp database. (b) is important because if more than 
55142   ** one database file has an open write transaction, a master journal
55143   ** file is required for an atomic commit.
55144   */ 
55145   for(i=0; i<db->nDb; i++){ 
55146     Btree *pBt = db->aDb[i].pBt;
55147     if( sqlite3BtreeIsInTrans(pBt) ){
55148       needXcommit = 1;
55149       if( i!=1 ) nTrans++;
55150     }
55151   }
55152
55153   /* If there are any write-transactions at all, invoke the commit hook */
55154   if( needXcommit && db->xCommitCallback ){
55155     rc = db->xCommitCallback(db->pCommitArg);
55156     if( rc ){
55157       return SQLITE_CONSTRAINT;
55158     }
55159   }
55160
55161   /* The simple case - no more than one database file (not counting the
55162   ** TEMP database) has a transaction active.   There is no need for the
55163   ** master-journal.
55164   **
55165   ** If the return value of sqlite3BtreeGetFilename() is a zero length
55166   ** string, it means the main database is :memory: or a temp file.  In 
55167   ** that case we do not support atomic multi-file commits, so use the 
55168   ** simple case then too.
55169   */
55170   if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
55171    || nTrans<=1
55172   ){
55173     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
55174       Btree *pBt = db->aDb[i].pBt;
55175       if( pBt ){
55176         rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
55177       }
55178     }
55179
55180     /* Do the commit only if all databases successfully complete phase 1. 
55181     ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
55182     ** IO error while deleting or truncating a journal file. It is unlikely,
55183     ** but could happen. In this case abandon processing and return the error.
55184     */
55185     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
55186       Btree *pBt = db->aDb[i].pBt;
55187       if( pBt ){
55188         rc = sqlite3BtreeCommitPhaseTwo(pBt);
55189       }
55190     }
55191     if( rc==SQLITE_OK ){
55192       sqlite3VtabCommit(db);
55193     }
55194   }
55195
55196   /* The complex case - There is a multi-file write-transaction active.
55197   ** This requires a master journal file to ensure the transaction is
55198   ** committed atomicly.
55199   */
55200 #ifndef SQLITE_OMIT_DISKIO
55201   else{
55202     sqlite3_vfs *pVfs = db->pVfs;
55203     int needSync = 0;
55204     char *zMaster = 0;   /* File-name for the master journal */
55205     char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
55206     sqlite3_file *pMaster = 0;
55207     i64 offset = 0;
55208     int res;
55209
55210     /* Select a master journal file name */
55211     do {
55212       u32 iRandom;
55213       sqlite3DbFree(db, zMaster);
55214       sqlite3_randomness(sizeof(iRandom), &iRandom);
55215       zMaster = sqlite3MPrintf(db, "%s-mj%08X", zMainFile, iRandom&0x7fffffff);
55216       if( !zMaster ){
55217         return SQLITE_NOMEM;
55218       }
55219       rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
55220     }while( rc==SQLITE_OK && res );
55221     if( rc==SQLITE_OK ){
55222       /* Open the master journal. */
55223       rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster, 
55224           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
55225           SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
55226       );
55227     }
55228     if( rc!=SQLITE_OK ){
55229       sqlite3DbFree(db, zMaster);
55230       return rc;
55231     }
55232  
55233     /* Write the name of each database file in the transaction into the new
55234     ** master journal file. If an error occurs at this point close
55235     ** and delete the master journal file. All the individual journal files
55236     ** still have 'null' as the master journal pointer, so they will roll
55237     ** back independently if a failure occurs.
55238     */
55239     for(i=0; i<db->nDb; i++){
55240       Btree *pBt = db->aDb[i].pBt;
55241       if( sqlite3BtreeIsInTrans(pBt) ){
55242         char const *zFile = sqlite3BtreeGetJournalname(pBt);
55243         if( zFile==0 || zFile[0]==0 ){
55244           continue;  /* Ignore TEMP and :memory: databases */
55245         }
55246         if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
55247           needSync = 1;
55248         }
55249         rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
55250         offset += sqlite3Strlen30(zFile)+1;
55251         if( rc!=SQLITE_OK ){
55252           sqlite3OsCloseFree(pMaster);
55253           sqlite3OsDelete(pVfs, zMaster, 0);
55254           sqlite3DbFree(db, zMaster);
55255           return rc;
55256         }
55257       }
55258     }
55259
55260     /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
55261     ** flag is set this is not required.
55262     */
55263     if( needSync 
55264      && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
55265      && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
55266     ){
55267       sqlite3OsCloseFree(pMaster);
55268       sqlite3OsDelete(pVfs, zMaster, 0);
55269       sqlite3DbFree(db, zMaster);
55270       return rc;
55271     }
55272
55273     /* Sync all the db files involved in the transaction. The same call
55274     ** sets the master journal pointer in each individual journal. If
55275     ** an error occurs here, do not delete the master journal file.
55276     **
55277     ** If the error occurs during the first call to
55278     ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
55279     ** master journal file will be orphaned. But we cannot delete it,
55280     ** in case the master journal file name was written into the journal
55281     ** file before the failure occurred.
55282     */
55283     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
55284       Btree *pBt = db->aDb[i].pBt;
55285       if( pBt ){
55286         rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
55287       }
55288     }
55289     sqlite3OsCloseFree(pMaster);
55290     if( rc!=SQLITE_OK ){
55291       sqlite3DbFree(db, zMaster);
55292       return rc;
55293     }
55294
55295     /* Delete the master journal file. This commits the transaction. After
55296     ** doing this the directory is synced again before any individual
55297     ** transaction files are deleted.
55298     */
55299     rc = sqlite3OsDelete(pVfs, zMaster, 1);
55300     sqlite3DbFree(db, zMaster);
55301     zMaster = 0;
55302     if( rc ){
55303       return rc;
55304     }
55305
55306     /* All files and directories have already been synced, so the following
55307     ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
55308     ** deleting or truncating journals. If something goes wrong while
55309     ** this is happening we don't really care. The integrity of the
55310     ** transaction is already guaranteed, but some stray 'cold' journals
55311     ** may be lying around. Returning an error code won't help matters.
55312     */
55313     disable_simulated_io_errors();
55314     sqlite3BeginBenignMalloc();
55315     for(i=0; i<db->nDb; i++){ 
55316       Btree *pBt = db->aDb[i].pBt;
55317       if( pBt ){
55318         sqlite3BtreeCommitPhaseTwo(pBt);
55319       }
55320     }
55321     sqlite3EndBenignMalloc();
55322     enable_simulated_io_errors();
55323
55324     sqlite3VtabCommit(db);
55325   }
55326 #endif
55327
55328   return rc;
55329 }
55330
55331 /* 
55332 ** This routine checks that the sqlite3.activeVdbeCnt count variable
55333 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
55334 ** currently active. An assertion fails if the two counts do not match.
55335 ** This is an internal self-check only - it is not an essential processing
55336 ** step.
55337 **
55338 ** This is a no-op if NDEBUG is defined.
55339 */
55340 #ifndef NDEBUG
55341 static void checkActiveVdbeCnt(sqlite3 *db){
55342   Vdbe *p;
55343   int cnt = 0;
55344   int nWrite = 0;
55345   p = db->pVdbe;
55346   while( p ){
55347     if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
55348       cnt++;
55349       if( p->readOnly==0 ) nWrite++;
55350     }
55351     p = p->pNext;
55352   }
55353   assert( cnt==db->activeVdbeCnt );
55354   assert( nWrite==db->writeVdbeCnt );
55355 }
55356 #else
55357 #define checkActiveVdbeCnt(x)
55358 #endif
55359
55360 /*
55361 ** For every Btree that in database connection db which 
55362 ** has been modified, "trip" or invalidate each cursor in
55363 ** that Btree might have been modified so that the cursor
55364 ** can never be used again.  This happens when a rollback
55365 *** occurs.  We have to trip all the other cursors, even
55366 ** cursor from other VMs in different database connections,
55367 ** so that none of them try to use the data at which they
55368 ** were pointing and which now may have been changed due
55369 ** to the rollback.
55370 **
55371 ** Remember that a rollback can delete tables complete and
55372 ** reorder rootpages.  So it is not sufficient just to save
55373 ** the state of the cursor.  We have to invalidate the cursor
55374 ** so that it is never used again.
55375 */
55376 static void invalidateCursorsOnModifiedBtrees(sqlite3 *db){
55377   int i;
55378   for(i=0; i<db->nDb; i++){
55379     Btree *p = db->aDb[i].pBt;
55380     if( p && sqlite3BtreeIsInTrans(p) ){
55381       sqlite3BtreeTripAllCursors(p, SQLITE_ABORT);
55382     }
55383   }
55384 }
55385
55386 /*
55387 ** If the Vdbe passed as the first argument opened a statement-transaction,
55388 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
55389 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
55390 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the 
55391 ** statement transaction is commtted.
55392 **
55393 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned. 
55394 ** Otherwise SQLITE_OK.
55395 */
55396 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
55397   sqlite3 *const db = p->db;
55398   int rc = SQLITE_OK;
55399
55400   /* If p->iStatement is greater than zero, then this Vdbe opened a 
55401   ** statement transaction that should be closed here. The only exception
55402   ** is that an IO error may have occured, causing an emergency rollback.
55403   ** In this case (db->nStatement==0), and there is nothing to do.
55404   */
55405   if( db->nStatement && p->iStatement ){
55406     int i;
55407     const int iSavepoint = p->iStatement-1;
55408
55409     assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
55410     assert( db->nStatement>0 );
55411     assert( p->iStatement==(db->nStatement+db->nSavepoint) );
55412
55413     for(i=0; i<db->nDb; i++){ 
55414       int rc2 = SQLITE_OK;
55415       Btree *pBt = db->aDb[i].pBt;
55416       if( pBt ){
55417         if( eOp==SAVEPOINT_ROLLBACK ){
55418           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
55419         }
55420         if( rc2==SQLITE_OK ){
55421           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
55422         }
55423         if( rc==SQLITE_OK ){
55424           rc = rc2;
55425         }
55426       }
55427     }
55428     db->nStatement--;
55429     p->iStatement = 0;
55430
55431     /* If the statement transaction is being rolled back, also restore the 
55432     ** database handles deferred constraint counter to the value it had when 
55433     ** the statement transaction was opened.  */
55434     if( eOp==SAVEPOINT_ROLLBACK ){
55435       db->nDeferredCons = p->nStmtDefCons;
55436     }
55437   }
55438   return rc;
55439 }
55440
55441 /*
55442 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
55443 ** this routine obtains the mutex associated with each BtShared structure
55444 ** that may be accessed by the VM passed as an argument. In doing so it
55445 ** sets the BtShared.db member of each of the BtShared structures, ensuring
55446 ** that the correct busy-handler callback is invoked if required.
55447 **
55448 ** If SQLite is not threadsafe but does support shared-cache mode, then
55449 ** sqlite3BtreeEnterAll() is invoked to set the BtShared.db variables
55450 ** of all of BtShared structures accessible via the database handle 
55451 ** associated with the VM. Of course only a subset of these structures
55452 ** will be accessed by the VM, and we could use Vdbe.btreeMask to figure
55453 ** that subset out, but there is no advantage to doing so.
55454 **
55455 ** If SQLite is not threadsafe and does not support shared-cache mode, this
55456 ** function is a no-op.
55457 */
55458 #ifndef SQLITE_OMIT_SHARED_CACHE
55459 SQLITE_PRIVATE void sqlite3VdbeMutexArrayEnter(Vdbe *p){
55460 #if SQLITE_THREADSAFE
55461   sqlite3BtreeMutexArrayEnter(&p->aMutex);
55462 #else
55463   sqlite3BtreeEnterAll(p->db);
55464 #endif
55465 }
55466 #endif
55467
55468 /*
55469 ** This function is called when a transaction opened by the database 
55470 ** handle associated with the VM passed as an argument is about to be 
55471 ** committed. If there are outstanding deferred foreign key constraint
55472 ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
55473 **
55474 ** If there are outstanding FK violations and this function returns 
55475 ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT and write
55476 ** an error message to it. Then return SQLITE_ERROR.
55477 */
55478 #ifndef SQLITE_OMIT_FOREIGN_KEY
55479 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
55480   sqlite3 *db = p->db;
55481   if( (deferred && db->nDeferredCons>0) || (!deferred && p->nFkConstraint>0) ){
55482     p->rc = SQLITE_CONSTRAINT;
55483     p->errorAction = OE_Abort;
55484     sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed");
55485     return SQLITE_ERROR;
55486   }
55487   return SQLITE_OK;
55488 }
55489 #endif
55490
55491 /*
55492 ** This routine is called the when a VDBE tries to halt.  If the VDBE
55493 ** has made changes and is in autocommit mode, then commit those
55494 ** changes.  If a rollback is needed, then do the rollback.
55495 **
55496 ** This routine is the only way to move the state of a VM from
55497 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
55498 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
55499 **
55500 ** Return an error code.  If the commit could not complete because of
55501 ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
55502 ** means the close did not happen and needs to be repeated.
55503 */
55504 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
55505   int rc;                         /* Used to store transient return codes */
55506   sqlite3 *db = p->db;
55507
55508   /* This function contains the logic that determines if a statement or
55509   ** transaction will be committed or rolled back as a result of the
55510   ** execution of this virtual machine. 
55511   **
55512   ** If any of the following errors occur:
55513   **
55514   **     SQLITE_NOMEM
55515   **     SQLITE_IOERR
55516   **     SQLITE_FULL
55517   **     SQLITE_INTERRUPT
55518   **
55519   ** Then the internal cache might have been left in an inconsistent
55520   ** state.  We need to rollback the statement transaction, if there is
55521   ** one, or the complete transaction if there is no statement transaction.
55522   */
55523
55524   if( p->db->mallocFailed ){
55525     p->rc = SQLITE_NOMEM;
55526   }
55527   closeAllCursors(p);
55528   if( p->magic!=VDBE_MAGIC_RUN ){
55529     return SQLITE_OK;
55530   }
55531   checkActiveVdbeCnt(db);
55532
55533   /* No commit or rollback needed if the program never started */
55534   if( p->pc>=0 ){
55535     int mrc;   /* Primary error code from p->rc */
55536     int eStatementOp = 0;
55537     int isSpecialError;            /* Set to true if a 'special' error */
55538
55539     /* Lock all btrees used by the statement */
55540     sqlite3VdbeMutexArrayEnter(p);
55541
55542     /* Check for one of the special errors */
55543     mrc = p->rc & 0xff;
55544     assert( p->rc!=SQLITE_IOERR_BLOCKED );  /* This error no longer exists */
55545     isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
55546                      || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
55547     if( isSpecialError ){
55548       /* If the query was read-only, we need do no rollback at all. Otherwise,
55549       ** proceed with the special handling.
55550       */
55551       if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
55552         if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
55553           eStatementOp = SAVEPOINT_ROLLBACK;
55554         }else{
55555           /* We are forced to roll back the active transaction. Before doing
55556           ** so, abort any other statements this handle currently has active.
55557           */
55558           invalidateCursorsOnModifiedBtrees(db);
55559           sqlite3RollbackAll(db);
55560           sqlite3CloseSavepoints(db);
55561           db->autoCommit = 1;
55562         }
55563       }
55564     }
55565
55566     /* Check for immediate foreign key violations. */
55567     if( p->rc==SQLITE_OK ){
55568       sqlite3VdbeCheckFk(p, 0);
55569     }
55570   
55571     /* If the auto-commit flag is set and this is the only active writer 
55572     ** VM, then we do either a commit or rollback of the current transaction. 
55573     **
55574     ** Note: This block also runs if one of the special errors handled 
55575     ** above has occurred. 
55576     */
55577     if( !sqlite3VtabInSync(db) 
55578      && db->autoCommit 
55579      && db->writeVdbeCnt==(p->readOnly==0) 
55580     ){
55581       if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
55582         if( sqlite3VdbeCheckFk(p, 1) ){
55583           sqlite3BtreeMutexArrayLeave(&p->aMutex);
55584           return SQLITE_ERROR;
55585         }
55586         /* The auto-commit flag is true, the vdbe program was successful 
55587         ** or hit an 'OR FAIL' constraint and there are no deferred foreign
55588         ** key constraints to hold up the transaction. This means a commit 
55589         ** is required.  */
55590         rc = vdbeCommit(db, p);
55591         if( rc==SQLITE_BUSY ){
55592           sqlite3BtreeMutexArrayLeave(&p->aMutex);
55593           return SQLITE_BUSY;
55594         }else if( rc!=SQLITE_OK ){
55595           p->rc = rc;
55596           sqlite3RollbackAll(db);
55597         }else{
55598           db->nDeferredCons = 0;
55599           sqlite3CommitInternalChanges(db);
55600         }
55601       }else{
55602         sqlite3RollbackAll(db);
55603       }
55604       db->nStatement = 0;
55605     }else if( eStatementOp==0 ){
55606       if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
55607         eStatementOp = SAVEPOINT_RELEASE;
55608       }else if( p->errorAction==OE_Abort ){
55609         eStatementOp = SAVEPOINT_ROLLBACK;
55610       }else{
55611         invalidateCursorsOnModifiedBtrees(db);
55612         sqlite3RollbackAll(db);
55613         sqlite3CloseSavepoints(db);
55614         db->autoCommit = 1;
55615       }
55616     }
55617   
55618     /* If eStatementOp is non-zero, then a statement transaction needs to
55619     ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
55620     ** do so. If this operation returns an error, and the current statement
55621     ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
55622     ** current statement error code.
55623     **
55624     ** Note that sqlite3VdbeCloseStatement() can only fail if eStatementOp
55625     ** is SAVEPOINT_ROLLBACK.  But if p->rc==SQLITE_OK then eStatementOp
55626     ** must be SAVEPOINT_RELEASE.  Hence the NEVER(p->rc==SQLITE_OK) in 
55627     ** the following code.
55628     */
55629     if( eStatementOp ){
55630       rc = sqlite3VdbeCloseStatement(p, eStatementOp);
55631       if( rc ){
55632         assert( eStatementOp==SAVEPOINT_ROLLBACK );
55633         if( NEVER(p->rc==SQLITE_OK) || p->rc==SQLITE_CONSTRAINT ){
55634           p->rc = rc;
55635           sqlite3DbFree(db, p->zErrMsg);
55636           p->zErrMsg = 0;
55637         }
55638         invalidateCursorsOnModifiedBtrees(db);
55639         sqlite3RollbackAll(db);
55640         sqlite3CloseSavepoints(db);
55641         db->autoCommit = 1;
55642       }
55643     }
55644   
55645     /* If this was an INSERT, UPDATE or DELETE and no statement transaction
55646     ** has been rolled back, update the database connection change-counter. 
55647     */
55648     if( p->changeCntOn ){
55649       if( eStatementOp!=SAVEPOINT_ROLLBACK ){
55650         sqlite3VdbeSetChanges(db, p->nChange);
55651       }else{
55652         sqlite3VdbeSetChanges(db, 0);
55653       }
55654       p->nChange = 0;
55655     }
55656   
55657     /* Rollback or commit any schema changes that occurred. */
55658     if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
55659       sqlite3ResetInternalSchema(db, 0);
55660       db->flags = (db->flags | SQLITE_InternChanges);
55661     }
55662
55663     /* Release the locks */
55664     sqlite3BtreeMutexArrayLeave(&p->aMutex);
55665   }
55666
55667   /* We have successfully halted and closed the VM.  Record this fact. */
55668   if( p->pc>=0 ){
55669     db->activeVdbeCnt--;
55670     if( !p->readOnly ){
55671       db->writeVdbeCnt--;
55672     }
55673     assert( db->activeVdbeCnt>=db->writeVdbeCnt );
55674   }
55675   p->magic = VDBE_MAGIC_HALT;
55676   checkActiveVdbeCnt(db);
55677   if( p->db->mallocFailed ){
55678     p->rc = SQLITE_NOMEM;
55679   }
55680
55681   /* If the auto-commit flag is set to true, then any locks that were held
55682   ** by connection db have now been released. Call sqlite3ConnectionUnlocked() 
55683   ** to invoke any required unlock-notify callbacks.
55684   */
55685   if( db->autoCommit ){
55686     sqlite3ConnectionUnlocked(db);
55687   }
55688
55689   assert( db->activeVdbeCnt>0 || db->autoCommit==0 || db->nStatement==0 );
55690   return SQLITE_OK;
55691 }
55692
55693
55694 /*
55695 ** Each VDBE holds the result of the most recent sqlite3_step() call
55696 ** in p->rc.  This routine sets that result back to SQLITE_OK.
55697 */
55698 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
55699   p->rc = SQLITE_OK;
55700 }
55701
55702 /*
55703 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
55704 ** Write any error messages into *pzErrMsg.  Return the result code.
55705 **
55706 ** After this routine is run, the VDBE should be ready to be executed
55707 ** again.
55708 **
55709 ** To look at it another way, this routine resets the state of the
55710 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
55711 ** VDBE_MAGIC_INIT.
55712 */
55713 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
55714   sqlite3 *db;
55715   db = p->db;
55716
55717   /* If the VM did not run to completion or if it encountered an
55718   ** error, then it might not have been halted properly.  So halt
55719   ** it now.
55720   */
55721   sqlite3VdbeHalt(p);
55722
55723   /* If the VDBE has be run even partially, then transfer the error code
55724   ** and error message from the VDBE into the main database structure.  But
55725   ** if the VDBE has just been set to run but has not actually executed any
55726   ** instructions yet, leave the main database error information unchanged.
55727   */
55728   if( p->pc>=0 ){
55729     if( p->zErrMsg ){
55730       sqlite3BeginBenignMalloc();
55731       sqlite3ValueSetStr(db->pErr,-1,p->zErrMsg,SQLITE_UTF8,SQLITE_TRANSIENT);
55732       sqlite3EndBenignMalloc();
55733       db->errCode = p->rc;
55734       sqlite3DbFree(db, p->zErrMsg);
55735       p->zErrMsg = 0;
55736     }else if( p->rc ){
55737       sqlite3Error(db, p->rc, 0);
55738     }else{
55739       sqlite3Error(db, SQLITE_OK, 0);
55740     }
55741     if( p->runOnlyOnce ) p->expired = 1;
55742   }else if( p->rc && p->expired ){
55743     /* The expired flag was set on the VDBE before the first call
55744     ** to sqlite3_step(). For consistency (since sqlite3_step() was
55745     ** called), set the database error in this case as well.
55746     */
55747     sqlite3Error(db, p->rc, 0);
55748     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
55749     sqlite3DbFree(db, p->zErrMsg);
55750     p->zErrMsg = 0;
55751   }
55752
55753   /* Reclaim all memory used by the VDBE
55754   */
55755   Cleanup(p);
55756
55757   /* Save profiling information from this VDBE run.
55758   */
55759 #ifdef VDBE_PROFILE
55760   {
55761     FILE *out = fopen("vdbe_profile.out", "a");
55762     if( out ){
55763       int i;
55764       fprintf(out, "---- ");
55765       for(i=0; i<p->nOp; i++){
55766         fprintf(out, "%02x", p->aOp[i].opcode);
55767       }
55768       fprintf(out, "\n");
55769       for(i=0; i<p->nOp; i++){
55770         fprintf(out, "%6d %10lld %8lld ",
55771            p->aOp[i].cnt,
55772            p->aOp[i].cycles,
55773            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
55774         );
55775         sqlite3VdbePrintOp(out, i, &p->aOp[i]);
55776       }
55777       fclose(out);
55778     }
55779   }
55780 #endif
55781   p->magic = VDBE_MAGIC_INIT;
55782   return p->rc & db->errMask;
55783 }
55784  
55785 /*
55786 ** Clean up and delete a VDBE after execution.  Return an integer which is
55787 ** the result code.  Write any error message text into *pzErrMsg.
55788 */
55789 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
55790   int rc = SQLITE_OK;
55791   if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
55792     rc = sqlite3VdbeReset(p);
55793     assert( (rc & p->db->errMask)==rc );
55794   }
55795   sqlite3VdbeDelete(p);
55796   return rc;
55797 }
55798
55799 /*
55800 ** Call the destructor for each auxdata entry in pVdbeFunc for which
55801 ** the corresponding bit in mask is clear.  Auxdata entries beyond 31
55802 ** are always destroyed.  To destroy all auxdata entries, call this
55803 ** routine with mask==0.
55804 */
55805 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
55806   int i;
55807   for(i=0; i<pVdbeFunc->nAux; i++){
55808     struct AuxData *pAux = &pVdbeFunc->apAux[i];
55809     if( (i>31 || !(mask&(((u32)1)<<i))) && pAux->pAux ){
55810       if( pAux->xDelete ){
55811         pAux->xDelete(pAux->pAux);
55812       }
55813       pAux->pAux = 0;
55814     }
55815   }
55816 }
55817
55818 /*
55819 ** Delete an entire VDBE.
55820 */
55821 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
55822   sqlite3 *db;
55823
55824   if( NEVER(p==0) ) return;
55825   db = p->db;
55826   if( p->pPrev ){
55827     p->pPrev->pNext = p->pNext;
55828   }else{
55829     assert( db->pVdbe==p );
55830     db->pVdbe = p->pNext;
55831   }
55832   if( p->pNext ){
55833     p->pNext->pPrev = p->pPrev;
55834   }
55835   releaseMemArray(p->aVar, p->nVar);
55836   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
55837   vdbeFreeOpArray(db, p->aOp, p->nOp);
55838   sqlite3DbFree(db, p->aLabel);
55839   sqlite3DbFree(db, p->aColName);
55840   sqlite3DbFree(db, p->zSql);
55841   p->magic = VDBE_MAGIC_DEAD;
55842   sqlite3DbFree(db, p->pFree);
55843   p->db = 0;
55844   sqlite3DbFree(db, p);
55845 }
55846
55847 /*
55848 ** Make sure the cursor p is ready to read or write the row to which it
55849 ** was last positioned.  Return an error code if an OOM fault or I/O error
55850 ** prevents us from positioning the cursor to its correct position.
55851 **
55852 ** If a MoveTo operation is pending on the given cursor, then do that
55853 ** MoveTo now.  If no move is pending, check to see if the row has been
55854 ** deleted out from under the cursor and if it has, mark the row as
55855 ** a NULL row.
55856 **
55857 ** If the cursor is already pointing to the correct row and that row has
55858 ** not been deleted out from under the cursor, then this routine is a no-op.
55859 */
55860 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
55861   if( p->deferredMoveto ){
55862     int res, rc;
55863 #ifdef SQLITE_TEST
55864     extern int sqlite3_search_count;
55865 #endif
55866     assert( p->isTable );
55867     rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
55868     if( rc ) return rc;
55869     p->lastRowid = p->movetoTarget;
55870     p->rowidIsValid = ALWAYS(res==0) ?1:0;
55871     if( NEVER(res<0) ){
55872       rc = sqlite3BtreeNext(p->pCursor, &res);
55873       if( rc ) return rc;
55874     }
55875 #ifdef SQLITE_TEST
55876     sqlite3_search_count++;
55877 #endif
55878     p->deferredMoveto = 0;
55879     p->cacheStatus = CACHE_STALE;
55880   }else if( ALWAYS(p->pCursor) ){
55881     int hasMoved;
55882     int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
55883     if( rc ) return rc;
55884     if( hasMoved ){
55885       p->cacheStatus = CACHE_STALE;
55886       p->nullRow = 1;
55887     }
55888   }
55889   return SQLITE_OK;
55890 }
55891
55892 /*
55893 ** The following functions:
55894 **
55895 ** sqlite3VdbeSerialType()
55896 ** sqlite3VdbeSerialTypeLen()
55897 ** sqlite3VdbeSerialLen()
55898 ** sqlite3VdbeSerialPut()
55899 ** sqlite3VdbeSerialGet()
55900 **
55901 ** encapsulate the code that serializes values for storage in SQLite
55902 ** data and index records. Each serialized value consists of a
55903 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
55904 ** integer, stored as a varint.
55905 **
55906 ** In an SQLite index record, the serial type is stored directly before
55907 ** the blob of data that it corresponds to. In a table record, all serial
55908 ** types are stored at the start of the record, and the blobs of data at
55909 ** the end. Hence these functions allow the caller to handle the
55910 ** serial-type and data blob seperately.
55911 **
55912 ** The following table describes the various storage classes for data:
55913 **
55914 **   serial type        bytes of data      type
55915 **   --------------     ---------------    ---------------
55916 **      0                     0            NULL
55917 **      1                     1            signed integer
55918 **      2                     2            signed integer
55919 **      3                     3            signed integer
55920 **      4                     4            signed integer
55921 **      5                     6            signed integer
55922 **      6                     8            signed integer
55923 **      7                     8            IEEE float
55924 **      8                     0            Integer constant 0
55925 **      9                     0            Integer constant 1
55926 **     10,11                               reserved for expansion
55927 **    N>=12 and even       (N-12)/2        BLOB
55928 **    N>=13 and odd        (N-13)/2        text
55929 **
55930 ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
55931 ** of SQLite will not understand those serial types.
55932 */
55933
55934 /*
55935 ** Return the serial-type for the value stored in pMem.
55936 */
55937 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
55938   int flags = pMem->flags;
55939   int n;
55940
55941   if( flags&MEM_Null ){
55942     return 0;
55943   }
55944   if( flags&MEM_Int ){
55945     /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
55946 #   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
55947     i64 i = pMem->u.i;
55948     u64 u;
55949     if( file_format>=4 && (i&1)==i ){
55950       return 8+(u32)i;
55951     }
55952     u = i<0 ? -i : i;
55953     if( u<=127 ) return 1;
55954     if( u<=32767 ) return 2;
55955     if( u<=8388607 ) return 3;
55956     if( u<=2147483647 ) return 4;
55957     if( u<=MAX_6BYTE ) return 5;
55958     return 6;
55959   }
55960   if( flags&MEM_Real ){
55961     return 7;
55962   }
55963   assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
55964   n = pMem->n;
55965   if( flags & MEM_Zero ){
55966     n += pMem->u.nZero;
55967   }
55968   assert( n>=0 );
55969   return ((n*2) + 12 + ((flags&MEM_Str)!=0));
55970 }
55971
55972 /*
55973 ** Return the length of the data corresponding to the supplied serial-type.
55974 */
55975 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
55976   if( serial_type>=12 ){
55977     return (serial_type-12)/2;
55978   }else{
55979     static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
55980     return aSize[serial_type];
55981   }
55982 }
55983
55984 /*
55985 ** If we are on an architecture with mixed-endian floating 
55986 ** points (ex: ARM7) then swap the lower 4 bytes with the 
55987 ** upper 4 bytes.  Return the result.
55988 **
55989 ** For most architectures, this is a no-op.
55990 **
55991 ** (later):  It is reported to me that the mixed-endian problem
55992 ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
55993 ** that early versions of GCC stored the two words of a 64-bit
55994 ** float in the wrong order.  And that error has been propagated
55995 ** ever since.  The blame is not necessarily with GCC, though.
55996 ** GCC might have just copying the problem from a prior compiler.
55997 ** I am also told that newer versions of GCC that follow a different
55998 ** ABI get the byte order right.
55999 **
56000 ** Developers using SQLite on an ARM7 should compile and run their
56001 ** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
56002 ** enabled, some asserts below will ensure that the byte order of
56003 ** floating point values is correct.
56004 **
56005 ** (2007-08-30)  Frank van Vugt has studied this problem closely
56006 ** and has send his findings to the SQLite developers.  Frank
56007 ** writes that some Linux kernels offer floating point hardware
56008 ** emulation that uses only 32-bit mantissas instead of a full 
56009 ** 48-bits as required by the IEEE standard.  (This is the
56010 ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
56011 ** byte swapping becomes very complicated.  To avoid problems,
56012 ** the necessary byte swapping is carried out using a 64-bit integer
56013 ** rather than a 64-bit float.  Frank assures us that the code here
56014 ** works for him.  We, the developers, have no way to independently
56015 ** verify this, but Frank seems to know what he is talking about
56016 ** so we trust him.
56017 */
56018 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
56019 static u64 floatSwap(u64 in){
56020   union {
56021     u64 r;
56022     u32 i[2];
56023   } u;
56024   u32 t;
56025
56026   u.r = in;
56027   t = u.i[0];
56028   u.i[0] = u.i[1];
56029   u.i[1] = t;
56030   return u.r;
56031 }
56032 # define swapMixedEndianFloat(X)  X = floatSwap(X)
56033 #else
56034 # define swapMixedEndianFloat(X)
56035 #endif
56036
56037 /*
56038 ** Write the serialized data blob for the value stored in pMem into 
56039 ** buf. It is assumed that the caller has allocated sufficient space.
56040 ** Return the number of bytes written.
56041 **
56042 ** nBuf is the amount of space left in buf[].  nBuf must always be
56043 ** large enough to hold the entire field.  Except, if the field is
56044 ** a blob with a zero-filled tail, then buf[] might be just the right
56045 ** size to hold everything except for the zero-filled tail.  If buf[]
56046 ** is only big enough to hold the non-zero prefix, then only write that
56047 ** prefix into buf[].  But if buf[] is large enough to hold both the
56048 ** prefix and the tail then write the prefix and set the tail to all
56049 ** zeros.
56050 **
56051 ** Return the number of bytes actually written into buf[].  The number
56052 ** of bytes in the zero-filled tail is included in the return value only
56053 ** if those bytes were zeroed in buf[].
56054 */ 
56055 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
56056   u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
56057   u32 len;
56058
56059   /* Integer and Real */
56060   if( serial_type<=7 && serial_type>0 ){
56061     u64 v;
56062     u32 i;
56063     if( serial_type==7 ){
56064       assert( sizeof(v)==sizeof(pMem->r) );
56065       memcpy(&v, &pMem->r, sizeof(v));
56066       swapMixedEndianFloat(v);
56067     }else{
56068       v = pMem->u.i;
56069     }
56070     len = i = sqlite3VdbeSerialTypeLen(serial_type);
56071     assert( len<=(u32)nBuf );
56072     while( i-- ){
56073       buf[i] = (u8)(v&0xFF);
56074       v >>= 8;
56075     }
56076     return len;
56077   }
56078
56079   /* String or blob */
56080   if( serial_type>=12 ){
56081     assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
56082              == (int)sqlite3VdbeSerialTypeLen(serial_type) );
56083     assert( pMem->n<=nBuf );
56084     len = pMem->n;
56085     memcpy(buf, pMem->z, len);
56086     if( pMem->flags & MEM_Zero ){
56087       len += pMem->u.nZero;
56088       assert( nBuf>=0 );
56089       if( len > (u32)nBuf ){
56090         len = (u32)nBuf;
56091       }
56092       memset(&buf[pMem->n], 0, len-pMem->n);
56093     }
56094     return len;
56095   }
56096
56097   /* NULL or constants 0 or 1 */
56098   return 0;
56099 }
56100
56101 /*
56102 ** Deserialize the data blob pointed to by buf as serial type serial_type
56103 ** and store the result in pMem.  Return the number of bytes read.
56104 */ 
56105 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
56106   const unsigned char *buf,     /* Buffer to deserialize from */
56107   u32 serial_type,              /* Serial type to deserialize */
56108   Mem *pMem                     /* Memory cell to write value into */
56109 ){
56110   switch( serial_type ){
56111     case 10:   /* Reserved for future use */
56112     case 11:   /* Reserved for future use */
56113     case 0: {  /* NULL */
56114       pMem->flags = MEM_Null;
56115       break;
56116     }
56117     case 1: { /* 1-byte signed integer */
56118       pMem->u.i = (signed char)buf[0];
56119       pMem->flags = MEM_Int;
56120       return 1;
56121     }
56122     case 2: { /* 2-byte signed integer */
56123       pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
56124       pMem->flags = MEM_Int;
56125       return 2;
56126     }
56127     case 3: { /* 3-byte signed integer */
56128       pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
56129       pMem->flags = MEM_Int;
56130       return 3;
56131     }
56132     case 4: { /* 4-byte signed integer */
56133       pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
56134       pMem->flags = MEM_Int;
56135       return 4;
56136     }
56137     case 5: { /* 6-byte signed integer */
56138       u64 x = (((signed char)buf[0])<<8) | buf[1];
56139       u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
56140       x = (x<<32) | y;
56141       pMem->u.i = *(i64*)&x;
56142       pMem->flags = MEM_Int;
56143       return 6;
56144     }
56145     case 6:   /* 8-byte signed integer */
56146     case 7: { /* IEEE floating point */
56147       u64 x;
56148       u32 y;
56149 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
56150       /* Verify that integers and floating point values use the same
56151       ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
56152       ** defined that 64-bit floating point values really are mixed
56153       ** endian.
56154       */
56155       static const u64 t1 = ((u64)0x3ff00000)<<32;
56156       static const double r1 = 1.0;
56157       u64 t2 = t1;
56158       swapMixedEndianFloat(t2);
56159       assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
56160 #endif
56161
56162       x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
56163       y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
56164       x = (x<<32) | y;
56165       if( serial_type==6 ){
56166         pMem->u.i = *(i64*)&x;
56167         pMem->flags = MEM_Int;
56168       }else{
56169         assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
56170         swapMixedEndianFloat(x);
56171         memcpy(&pMem->r, &x, sizeof(x));
56172         pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
56173       }
56174       return 8;
56175     }
56176     case 8:    /* Integer 0 */
56177     case 9: {  /* Integer 1 */
56178       pMem->u.i = serial_type-8;
56179       pMem->flags = MEM_Int;
56180       return 0;
56181     }
56182     default: {
56183       u32 len = (serial_type-12)/2;
56184       pMem->z = (char *)buf;
56185       pMem->n = len;
56186       pMem->xDel = 0;
56187       if( serial_type&0x01 ){
56188         pMem->flags = MEM_Str | MEM_Ephem;
56189       }else{
56190         pMem->flags = MEM_Blob | MEM_Ephem;
56191       }
56192       return len;
56193     }
56194   }
56195   return 0;
56196 }
56197
56198
56199 /*
56200 ** Given the nKey-byte encoding of a record in pKey[], parse the
56201 ** record into a UnpackedRecord structure.  Return a pointer to
56202 ** that structure.
56203 **
56204 ** The calling function might provide szSpace bytes of memory
56205 ** space at pSpace.  This space can be used to hold the returned
56206 ** VDbeParsedRecord structure if it is large enough.  If it is
56207 ** not big enough, space is obtained from sqlite3_malloc().
56208 **
56209 ** The returned structure should be closed by a call to
56210 ** sqlite3VdbeDeleteUnpackedRecord().
56211 */ 
56212 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(
56213   KeyInfo *pKeyInfo,     /* Information about the record format */
56214   int nKey,              /* Size of the binary record */
56215   const void *pKey,      /* The binary record */
56216   char *pSpace,          /* Unaligned space available to hold the object */
56217   int szSpace            /* Size of pSpace[] in bytes */
56218 ){
56219   const unsigned char *aKey = (const unsigned char *)pKey;
56220   UnpackedRecord *p;  /* The unpacked record that we will return */
56221   int nByte;          /* Memory space needed to hold p, in bytes */
56222   int d;
56223   u32 idx;
56224   u16 u;              /* Unsigned loop counter */
56225   u32 szHdr;
56226   Mem *pMem;
56227   int nOff;           /* Increase pSpace by this much to 8-byte align it */
56228   
56229   /*
56230   ** We want to shift the pointer pSpace up such that it is 8-byte aligned.
56231   ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift 
56232   ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
56233   */
56234   nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
56235   pSpace += nOff;
56236   szSpace -= nOff;
56237   nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
56238   if( nByte>szSpace ){
56239     p = sqlite3DbMallocRaw(pKeyInfo->db, nByte);
56240     if( p==0 ) return 0;
56241     p->flags = UNPACKED_NEED_FREE | UNPACKED_NEED_DESTROY;
56242   }else{
56243     p = (UnpackedRecord*)pSpace;
56244     p->flags = UNPACKED_NEED_DESTROY;
56245   }
56246   p->pKeyInfo = pKeyInfo;
56247   p->nField = pKeyInfo->nField + 1;
56248   p->aMem = pMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
56249   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
56250   idx = getVarint32(aKey, szHdr);
56251   d = szHdr;
56252   u = 0;
56253   while( idx<szHdr && u<p->nField && d<=nKey ){
56254     u32 serial_type;
56255
56256     idx += getVarint32(&aKey[idx], serial_type);
56257     pMem->enc = pKeyInfo->enc;
56258     pMem->db = pKeyInfo->db;
56259     pMem->flags = 0;
56260     pMem->zMalloc = 0;
56261     d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
56262     pMem++;
56263     u++;
56264   }
56265   assert( u<=pKeyInfo->nField + 1 );
56266   p->nField = u;
56267   return (void*)p;
56268 }
56269
56270 /*
56271 ** This routine destroys a UnpackedRecord object.
56272 */
56273 SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord *p){
56274   int i;
56275   Mem *pMem;
56276
56277   assert( p!=0 );
56278   assert( p->flags & UNPACKED_NEED_DESTROY );
56279   for(i=0, pMem=p->aMem; i<p->nField; i++, pMem++){
56280     /* The unpacked record is always constructed by the
56281     ** sqlite3VdbeUnpackRecord() function above, which makes all
56282     ** strings and blobs static.  And none of the elements are
56283     ** ever transformed, so there is never anything to delete.
56284     */
56285     if( NEVER(pMem->zMalloc) ) sqlite3VdbeMemRelease(pMem);
56286   }
56287   if( p->flags & UNPACKED_NEED_FREE ){
56288     sqlite3DbFree(p->pKeyInfo->db, p);
56289   }
56290 }
56291
56292 /*
56293 ** This function compares the two table rows or index records
56294 ** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
56295 ** or positive integer if key1 is less than, equal to or 
56296 ** greater than key2.  The {nKey1, pKey1} key must be a blob
56297 ** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
56298 ** key must be a parsed key such as obtained from
56299 ** sqlite3VdbeParseRecord.
56300 **
56301 ** Key1 and Key2 do not have to contain the same number of fields.
56302 ** The key with fewer fields is usually compares less than the 
56303 ** longer key.  However if the UNPACKED_INCRKEY flags in pPKey2 is set
56304 ** and the common prefixes are equal, then key1 is less than key2.
56305 ** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
56306 ** equal, then the keys are considered to be equal and
56307 ** the parts beyond the common prefix are ignored.
56308 **
56309 ** If the UNPACKED_IGNORE_ROWID flag is set, then the last byte of
56310 ** the header of pKey1 is ignored.  It is assumed that pKey1 is
56311 ** an index key, and thus ends with a rowid value.  The last byte
56312 ** of the header will therefore be the serial type of the rowid:
56313 ** one of 1, 2, 3, 4, 5, 6, 8, or 9 - the integer serial types.
56314 ** The serial type of the final rowid will always be a single byte.
56315 ** By ignoring this last byte of the header, we force the comparison
56316 ** to ignore the rowid at the end of key1.
56317 */
56318 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
56319   int nKey1, const void *pKey1, /* Left key */
56320   UnpackedRecord *pPKey2        /* Right key */
56321 ){
56322   int d1;            /* Offset into aKey[] of next data element */
56323   u32 idx1;          /* Offset into aKey[] of next header element */
56324   u32 szHdr1;        /* Number of bytes in header */
56325   int i = 0;
56326   int nField;
56327   int rc = 0;
56328   const unsigned char *aKey1 = (const unsigned char *)pKey1;
56329   KeyInfo *pKeyInfo;
56330   Mem mem1;
56331
56332   pKeyInfo = pPKey2->pKeyInfo;
56333   mem1.enc = pKeyInfo->enc;
56334   mem1.db = pKeyInfo->db;
56335   /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
56336   VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
56337
56338   /* Compilers may complain that mem1.u.i is potentially uninitialized.
56339   ** We could initialize it, as shown here, to silence those complaints.
56340   ** But in fact, mem1.u.i will never actually be used initialized, and doing 
56341   ** the unnecessary initialization has a measurable negative performance
56342   ** impact, since this routine is a very high runner.  And so, we choose
56343   ** to ignore the compiler warnings and leave this variable uninitialized.
56344   */
56345   /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
56346   
56347   idx1 = getVarint32(aKey1, szHdr1);
56348   d1 = szHdr1;
56349   if( pPKey2->flags & UNPACKED_IGNORE_ROWID ){
56350     szHdr1--;
56351   }
56352   nField = pKeyInfo->nField;
56353   while( idx1<szHdr1 && i<pPKey2->nField ){
56354     u32 serial_type1;
56355
56356     /* Read the serial types for the next element in each key. */
56357     idx1 += getVarint32( aKey1+idx1, serial_type1 );
56358     if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
56359
56360     /* Extract the values to be compared.
56361     */
56362     d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
56363
56364     /* Do the comparison
56365     */
56366     rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
56367                            i<nField ? pKeyInfo->aColl[i] : 0);
56368     if( rc!=0 ){
56369       assert( mem1.zMalloc==0 );  /* See comment below */
56370
56371       /* Invert the result if we are using DESC sort order. */
56372       if( pKeyInfo->aSortOrder && i<nField && pKeyInfo->aSortOrder[i] ){
56373         rc = -rc;
56374       }
56375     
56376       /* If the PREFIX_SEARCH flag is set and all fields except the final
56377       ** rowid field were equal, then clear the PREFIX_SEARCH flag and set 
56378       ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
56379       ** This is used by the OP_IsUnique opcode.
56380       */
56381       if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
56382         assert( idx1==szHdr1 && rc );
56383         assert( mem1.flags & MEM_Int );
56384         pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
56385         pPKey2->rowid = mem1.u.i;
56386       }
56387     
56388       return rc;
56389     }
56390     i++;
56391   }
56392
56393   /* No memory allocation is ever used on mem1.  Prove this using
56394   ** the following assert().  If the assert() fails, it indicates a
56395   ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
56396   */
56397   assert( mem1.zMalloc==0 );
56398
56399   /* rc==0 here means that one of the keys ran out of fields and
56400   ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
56401   ** flag is set, then break the tie by treating key2 as larger.
56402   ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
56403   ** are considered to be equal.  Otherwise, the longer key is the 
56404   ** larger.  As it happens, the pPKey2 will always be the longer
56405   ** if there is a difference.
56406   */
56407   assert( rc==0 );
56408   if( pPKey2->flags & UNPACKED_INCRKEY ){
56409     rc = -1;
56410   }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
56411     /* Leave rc==0 */
56412   }else if( idx1<szHdr1 ){
56413     rc = 1;
56414   }
56415   return rc;
56416 }
56417  
56418
56419 /*
56420 ** pCur points at an index entry created using the OP_MakeRecord opcode.
56421 ** Read the rowid (the last field in the record) and store it in *rowid.
56422 ** Return SQLITE_OK if everything works, or an error code otherwise.
56423 **
56424 ** pCur might be pointing to text obtained from a corrupt database file.
56425 ** So the content cannot be trusted.  Do appropriate checks on the content.
56426 */
56427 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
56428   i64 nCellKey = 0;
56429   int rc;
56430   u32 szHdr;        /* Size of the header */
56431   u32 typeRowid;    /* Serial type of the rowid */
56432   u32 lenRowid;     /* Size of the rowid */
56433   Mem m, v;
56434
56435   UNUSED_PARAMETER(db);
56436
56437   /* Get the size of the index entry.  Only indices entries of less
56438   ** than 2GiB are support - anything large must be database corruption.
56439   ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
56440   ** this code can safely assume that nCellKey is 32-bits  
56441   */
56442   assert( sqlite3BtreeCursorIsValid(pCur) );
56443   rc = sqlite3BtreeKeySize(pCur, &nCellKey);
56444   assert( rc==SQLITE_OK );     /* pCur is always valid so KeySize cannot fail */
56445   assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
56446
56447   /* Read in the complete content of the index entry */
56448   memset(&m, 0, sizeof(m));
56449   rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
56450   if( rc ){
56451     return rc;
56452   }
56453
56454   /* The index entry must begin with a header size */
56455   (void)getVarint32((u8*)m.z, szHdr);
56456   testcase( szHdr==3 );
56457   testcase( szHdr==m.n );
56458   if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
56459     goto idx_rowid_corruption;
56460   }
56461
56462   /* The last field of the index should be an integer - the ROWID.
56463   ** Verify that the last entry really is an integer. */
56464   (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
56465   testcase( typeRowid==1 );
56466   testcase( typeRowid==2 );
56467   testcase( typeRowid==3 );
56468   testcase( typeRowid==4 );
56469   testcase( typeRowid==5 );
56470   testcase( typeRowid==6 );
56471   testcase( typeRowid==8 );
56472   testcase( typeRowid==9 );
56473   if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
56474     goto idx_rowid_corruption;
56475   }
56476   lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
56477   testcase( (u32)m.n==szHdr+lenRowid );
56478   if( unlikely((u32)m.n<szHdr+lenRowid) ){
56479     goto idx_rowid_corruption;
56480   }
56481
56482   /* Fetch the integer off the end of the index record */
56483   sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
56484   *rowid = v.u.i;
56485   sqlite3VdbeMemRelease(&m);
56486   return SQLITE_OK;
56487
56488   /* Jump here if database corruption is detected after m has been
56489   ** allocated.  Free the m object and return SQLITE_CORRUPT. */
56490 idx_rowid_corruption:
56491   testcase( m.zMalloc!=0 );
56492   sqlite3VdbeMemRelease(&m);
56493   return SQLITE_CORRUPT_BKPT;
56494 }
56495
56496 /*
56497 ** Compare the key of the index entry that cursor pC is pointing to against
56498 ** the key string in pUnpacked.  Write into *pRes a number
56499 ** that is negative, zero, or positive if pC is less than, equal to,
56500 ** or greater than pUnpacked.  Return SQLITE_OK on success.
56501 **
56502 ** pUnpacked is either created without a rowid or is truncated so that it
56503 ** omits the rowid at the end.  The rowid at the end of the index entry
56504 ** is ignored as well.  Hence, this routine only compares the prefixes 
56505 ** of the keys prior to the final rowid, not the entire key.
56506 */
56507 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
56508   VdbeCursor *pC,             /* The cursor to compare against */
56509   UnpackedRecord *pUnpacked,  /* Unpacked version of key to compare against */
56510   int *res                    /* Write the comparison result here */
56511 ){
56512   i64 nCellKey = 0;
56513   int rc;
56514   BtCursor *pCur = pC->pCursor;
56515   Mem m;
56516
56517   assert( sqlite3BtreeCursorIsValid(pCur) );
56518   rc = sqlite3BtreeKeySize(pCur, &nCellKey);
56519   assert( rc==SQLITE_OK );    /* pCur is always valid so KeySize cannot fail */
56520   /* nCellKey will always be between 0 and 0xffffffff because of the say
56521   ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
56522   if( nCellKey<=0 || nCellKey>0x7fffffff ){
56523     *res = 0;
56524     return SQLITE_CORRUPT_BKPT;
56525   }
56526   memset(&m, 0, sizeof(m));
56527   rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
56528   if( rc ){
56529     return rc;
56530   }
56531   assert( pUnpacked->flags & UNPACKED_IGNORE_ROWID );
56532   *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
56533   sqlite3VdbeMemRelease(&m);
56534   return SQLITE_OK;
56535 }
56536
56537 /*
56538 ** This routine sets the value to be returned by subsequent calls to
56539 ** sqlite3_changes() on the database handle 'db'. 
56540 */
56541 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
56542   assert( sqlite3_mutex_held(db->mutex) );
56543   db->nChange = nChange;
56544   db->nTotalChange += nChange;
56545 }
56546
56547 /*
56548 ** Set a flag in the vdbe to update the change counter when it is finalised
56549 ** or reset.
56550 */
56551 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
56552   v->changeCntOn = 1;
56553 }
56554
56555 /*
56556 ** Mark every prepared statement associated with a database connection
56557 ** as expired.
56558 **
56559 ** An expired statement means that recompilation of the statement is
56560 ** recommend.  Statements expire when things happen that make their
56561 ** programs obsolete.  Removing user-defined functions or collating
56562 ** sequences, or changing an authorization function are the types of
56563 ** things that make prepared statements obsolete.
56564 */
56565 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
56566   Vdbe *p;
56567   for(p = db->pVdbe; p; p=p->pNext){
56568     p->expired = 1;
56569   }
56570 }
56571
56572 /*
56573 ** Return the database associated with the Vdbe.
56574 */
56575 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
56576   return v->db;
56577 }
56578
56579 /*
56580 ** Return a pointer to an sqlite3_value structure containing the value bound
56581 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return 
56582 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
56583 ** constants) to the value before returning it.
56584 **
56585 ** The returned value must be freed by the caller using sqlite3ValueFree().
56586 */
56587 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe *v, int iVar, u8 aff){
56588   assert( iVar>0 );
56589   if( v ){
56590     Mem *pMem = &v->aVar[iVar-1];
56591     if( 0==(pMem->flags & MEM_Null) ){
56592       sqlite3_value *pRet = sqlite3ValueNew(v->db);
56593       if( pRet ){
56594         sqlite3VdbeMemCopy((Mem *)pRet, pMem);
56595         sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
56596         sqlite3VdbeMemStoreType((Mem *)pRet);
56597       }
56598       return pRet;
56599     }
56600   }
56601   return 0;
56602 }
56603
56604 /*
56605 ** Configure SQL variable iVar so that binding a new value to it signals
56606 ** to sqlite3_reoptimize() that re-preparing the statement may result
56607 ** in a better query plan.
56608 */
56609 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
56610   assert( iVar>0 );
56611   if( iVar>32 ){
56612     v->expmask = 0xffffffff;
56613   }else{
56614     v->expmask |= ((u32)1 << (iVar-1));
56615   }
56616 }
56617
56618 /************** End of vdbeaux.c *********************************************/
56619 /************** Begin file vdbeapi.c *****************************************/
56620 /*
56621 ** 2004 May 26
56622 **
56623 ** The author disclaims copyright to this source code.  In place of
56624 ** a legal notice, here is a blessing:
56625 **
56626 **    May you do good and not evil.
56627 **    May you find forgiveness for yourself and forgive others.
56628 **    May you share freely, never taking more than you give.
56629 **
56630 *************************************************************************
56631 **
56632 ** This file contains code use to implement APIs that are part of the
56633 ** VDBE.
56634 */
56635
56636 #ifndef SQLITE_OMIT_DEPRECATED
56637 /*
56638 ** Return TRUE (non-zero) of the statement supplied as an argument needs
56639 ** to be recompiled.  A statement needs to be recompiled whenever the
56640 ** execution environment changes in a way that would alter the program
56641 ** that sqlite3_prepare() generates.  For example, if new functions or
56642 ** collating sequences are registered or if an authorizer function is
56643 ** added or changed.
56644 */
56645 SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
56646   Vdbe *p = (Vdbe*)pStmt;
56647   return p==0 || p->expired;
56648 }
56649 #endif
56650
56651 /*
56652 ** Check on a Vdbe to make sure it has not been finalized.  Log
56653 ** an error and return true if it has been finalized (or is otherwise
56654 ** invalid).  Return false if it is ok.
56655 */
56656 static int vdbeSafety(Vdbe *p){
56657   if( p->db==0 ){
56658     sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
56659     return 1;
56660   }else{
56661     return 0;
56662   }
56663 }
56664 static int vdbeSafetyNotNull(Vdbe *p){
56665   if( p==0 ){
56666     sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
56667     return 1;
56668   }else{
56669     return vdbeSafety(p);
56670   }
56671 }
56672
56673 /*
56674 ** The following routine destroys a virtual machine that is created by
56675 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
56676 ** success/failure code that describes the result of executing the virtual
56677 ** machine.
56678 **
56679 ** This routine sets the error code and string returned by
56680 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
56681 */
56682 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
56683   int rc;
56684   if( pStmt==0 ){
56685     rc = SQLITE_OK;
56686   }else{
56687     Vdbe *v = (Vdbe*)pStmt;
56688     sqlite3 *db = v->db;
56689 #if SQLITE_THREADSAFE
56690     sqlite3_mutex *mutex;
56691 #endif
56692     if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
56693 #if SQLITE_THREADSAFE
56694     mutex = v->db->mutex;
56695 #endif
56696     sqlite3_mutex_enter(mutex);
56697     rc = sqlite3VdbeFinalize(v);
56698     rc = sqlite3ApiExit(db, rc);
56699     sqlite3_mutex_leave(mutex);
56700   }
56701   return rc;
56702 }
56703
56704 /*
56705 ** Terminate the current execution of an SQL statement and reset it
56706 ** back to its starting state so that it can be reused. A success code from
56707 ** the prior execution is returned.
56708 **
56709 ** This routine sets the error code and string returned by
56710 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
56711 */
56712 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
56713   int rc;
56714   if( pStmt==0 ){
56715     rc = SQLITE_OK;
56716   }else{
56717     Vdbe *v = (Vdbe*)pStmt;
56718     sqlite3_mutex_enter(v->db->mutex);
56719     rc = sqlite3VdbeReset(v);
56720     sqlite3VdbeMakeReady(v, -1, 0, 0, 0, 0, 0);
56721     assert( (rc & (v->db->errMask))==rc );
56722     rc = sqlite3ApiExit(v->db, rc);
56723     sqlite3_mutex_leave(v->db->mutex);
56724   }
56725   return rc;
56726 }
56727
56728 /*
56729 ** Set all the parameters in the compiled SQL statement to NULL.
56730 */
56731 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
56732   int i;
56733   int rc = SQLITE_OK;
56734   Vdbe *p = (Vdbe*)pStmt;
56735 #if SQLITE_THREADSAFE
56736   sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
56737 #endif
56738   sqlite3_mutex_enter(mutex);
56739   for(i=0; i<p->nVar; i++){
56740     sqlite3VdbeMemRelease(&p->aVar[i]);
56741     p->aVar[i].flags = MEM_Null;
56742   }
56743   if( p->isPrepareV2 && p->expmask ){
56744     p->expired = 1;
56745   }
56746   sqlite3_mutex_leave(mutex);
56747   return rc;
56748 }
56749
56750
56751 /**************************** sqlite3_value_  *******************************
56752 ** The following routines extract information from a Mem or sqlite3_value
56753 ** structure.
56754 */
56755 SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
56756   Mem *p = (Mem*)pVal;
56757   if( p->flags & (MEM_Blob|MEM_Str) ){
56758     sqlite3VdbeMemExpandBlob(p);
56759     p->flags &= ~MEM_Str;
56760     p->flags |= MEM_Blob;
56761     return p->z;
56762   }else{
56763     return sqlite3_value_text(pVal);
56764   }
56765 }
56766 SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
56767   return sqlite3ValueBytes(pVal, SQLITE_UTF8);
56768 }
56769 SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
56770   return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
56771 }
56772 SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
56773   return sqlite3VdbeRealValue((Mem*)pVal);
56774 }
56775 SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
56776   return (int)sqlite3VdbeIntValue((Mem*)pVal);
56777 }
56778 SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
56779   return sqlite3VdbeIntValue((Mem*)pVal);
56780 }
56781 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
56782   return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
56783 }
56784 #ifndef SQLITE_OMIT_UTF16
56785 SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
56786   return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
56787 }
56788 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
56789   return sqlite3ValueText(pVal, SQLITE_UTF16BE);
56790 }
56791 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
56792   return sqlite3ValueText(pVal, SQLITE_UTF16LE);
56793 }
56794 #endif /* SQLITE_OMIT_UTF16 */
56795 SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
56796   return pVal->type;
56797 }
56798
56799 /**************************** sqlite3_result_  *******************************
56800 ** The following routines are used by user-defined functions to specify
56801 ** the function result.
56802 **
56803 ** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the
56804 ** result as a string or blob but if the string or blob is too large, it
56805 ** then sets the error code to SQLITE_TOOBIG
56806 */
56807 static void setResultStrOrError(
56808   sqlite3_context *pCtx,  /* Function context */
56809   const char *z,          /* String pointer */
56810   int n,                  /* Bytes in string, or negative */
56811   u8 enc,                 /* Encoding of z.  0 for BLOBs */
56812   void (*xDel)(void*)     /* Destructor function */
56813 ){
56814   if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
56815     sqlite3_result_error_toobig(pCtx);
56816   }
56817 }
56818 SQLITE_API void sqlite3_result_blob(
56819   sqlite3_context *pCtx, 
56820   const void *z, 
56821   int n, 
56822   void (*xDel)(void *)
56823 ){
56824   assert( n>=0 );
56825   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
56826   setResultStrOrError(pCtx, z, n, 0, xDel);
56827 }
56828 SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
56829   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
56830   sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
56831 }
56832 SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
56833   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
56834   pCtx->isError = SQLITE_ERROR;
56835   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
56836 }
56837 #ifndef SQLITE_OMIT_UTF16
56838 SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
56839   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
56840   pCtx->isError = SQLITE_ERROR;
56841   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
56842 }
56843 #endif
56844 SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
56845   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
56846   sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
56847 }
56848 SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
56849   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
56850   sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
56851 }
56852 SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
56853   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
56854   sqlite3VdbeMemSetNull(&pCtx->s);
56855 }
56856 SQLITE_API void sqlite3_result_text(
56857   sqlite3_context *pCtx, 
56858   const char *z, 
56859   int n,
56860   void (*xDel)(void *)
56861 ){
56862   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
56863   setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
56864 }
56865 #ifndef SQLITE_OMIT_UTF16
56866 SQLITE_API void sqlite3_result_text16(
56867   sqlite3_context *pCtx, 
56868   const void *z, 
56869   int n, 
56870   void (*xDel)(void *)
56871 ){
56872   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
56873   setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
56874 }
56875 SQLITE_API void sqlite3_result_text16be(
56876   sqlite3_context *pCtx, 
56877   const void *z, 
56878   int n, 
56879   void (*xDel)(void *)
56880 ){
56881   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
56882   setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
56883 }
56884 SQLITE_API void sqlite3_result_text16le(
56885   sqlite3_context *pCtx, 
56886   const void *z, 
56887   int n, 
56888   void (*xDel)(void *)
56889 ){
56890   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
56891   setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
56892 }
56893 #endif /* SQLITE_OMIT_UTF16 */
56894 SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
56895   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
56896   sqlite3VdbeMemCopy(&pCtx->s, pValue);
56897 }
56898 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
56899   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
56900   sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
56901 }
56902 SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
56903   pCtx->isError = errCode;
56904   if( pCtx->s.flags & MEM_Null ){
56905     sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1, 
56906                          SQLITE_UTF8, SQLITE_STATIC);
56907   }
56908 }
56909
56910 /* Force an SQLITE_TOOBIG error. */
56911 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
56912   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
56913   pCtx->isError = SQLITE_TOOBIG;
56914   sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1, 
56915                        SQLITE_UTF8, SQLITE_STATIC);
56916 }
56917
56918 /* An SQLITE_NOMEM error. */
56919 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
56920   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
56921   sqlite3VdbeMemSetNull(&pCtx->s);
56922   pCtx->isError = SQLITE_NOMEM;
56923   pCtx->s.db->mallocFailed = 1;
56924 }
56925
56926 /*
56927 ** This function is called after a transaction has been committed. It 
56928 ** invokes callbacks registered with sqlite3_wal_hook() as required.
56929 */
56930 static int doWalCallbacks(sqlite3 *db){
56931   int rc = SQLITE_OK;
56932 #ifndef SQLITE_OMIT_WAL
56933   int i;
56934   for(i=0; i<db->nDb; i++){
56935     Btree *pBt = db->aDb[i].pBt;
56936     if( pBt ){
56937       int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
56938       if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
56939         rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
56940       }
56941     }
56942   }
56943 #endif
56944   return rc;
56945 }
56946
56947 /*
56948 ** Execute the statement pStmt, either until a row of data is ready, the
56949 ** statement is completely executed or an error occurs.
56950 **
56951 ** This routine implements the bulk of the logic behind the sqlite_step()
56952 ** API.  The only thing omitted is the automatic recompile if a 
56953 ** schema change has occurred.  That detail is handled by the
56954 ** outer sqlite3_step() wrapper procedure.
56955 */
56956 static int sqlite3Step(Vdbe *p){
56957   sqlite3 *db;
56958   int rc;
56959
56960   assert(p);
56961   if( p->magic!=VDBE_MAGIC_RUN ){
56962     /* We used to require that sqlite3_reset() be called before retrying
56963     ** sqlite3_step() after any error.  But after 3.6.23, we changed this
56964     ** so that sqlite3_reset() would be called automatically instead of
56965     ** throwing the error.
56966     */
56967     sqlite3_reset((sqlite3_stmt*)p);
56968   }
56969
56970   /* Check that malloc() has not failed. If it has, return early. */
56971   db = p->db;
56972   if( db->mallocFailed ){
56973     p->rc = SQLITE_NOMEM;
56974     return SQLITE_NOMEM;
56975   }
56976
56977   if( p->pc<=0 && p->expired ){
56978     p->rc = SQLITE_SCHEMA;
56979     rc = SQLITE_ERROR;
56980     goto end_of_step;
56981   }
56982   if( p->pc<0 ){
56983     /* If there are no other statements currently running, then
56984     ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
56985     ** from interrupting a statement that has not yet started.
56986     */
56987     if( db->activeVdbeCnt==0 ){
56988       db->u1.isInterrupted = 0;
56989     }
56990
56991     assert( db->writeVdbeCnt>0 || db->autoCommit==0 || db->nDeferredCons==0 );
56992
56993 #ifndef SQLITE_OMIT_TRACE
56994     if( db->xProfile && !db->init.busy ){
56995       sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
56996     }
56997 #endif
56998
56999     db->activeVdbeCnt++;
57000     if( p->readOnly==0 ) db->writeVdbeCnt++;
57001     p->pc = 0;
57002   }
57003 #ifndef SQLITE_OMIT_EXPLAIN
57004   if( p->explain ){
57005     rc = sqlite3VdbeList(p);
57006   }else
57007 #endif /* SQLITE_OMIT_EXPLAIN */
57008   {
57009     rc = sqlite3VdbeExec(p);
57010   }
57011
57012 #ifndef SQLITE_OMIT_TRACE
57013   /* Invoke the profile callback if there is one
57014   */
57015   if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
57016     sqlite3_int64 iNow;
57017     sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
57018     db->xProfile(db->pProfileArg, p->zSql, iNow - p->startTime);
57019   }
57020 #endif
57021
57022   if( rc==SQLITE_DONE ){
57023     assert( p->rc==SQLITE_OK );
57024     p->rc = doWalCallbacks(db);
57025     if( p->rc!=SQLITE_OK ){
57026       rc = SQLITE_ERROR;
57027     }
57028   }
57029
57030   db->errCode = rc;
57031   if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
57032     p->rc = SQLITE_NOMEM;
57033   }
57034 end_of_step:
57035   /* At this point local variable rc holds the value that should be 
57036   ** returned if this statement was compiled using the legacy 
57037   ** sqlite3_prepare() interface. According to the docs, this can only
57038   ** be one of the values in the first assert() below. Variable p->rc 
57039   ** contains the value that would be returned if sqlite3_finalize() 
57040   ** were called on statement p.
57041   */
57042   assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR 
57043        || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
57044   );
57045   assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
57046   if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
57047     /* If this statement was prepared using sqlite3_prepare_v2(), and an
57048     ** error has occured, then return the error code in p->rc to the
57049     ** caller. Set the error code in the database handle to the same value.
57050     */ 
57051     rc = db->errCode = p->rc;
57052   }
57053   return (rc&db->errMask);
57054 }
57055
57056 /*
57057 ** This is the top-level implementation of sqlite3_step().  Call
57058 ** sqlite3Step() to do most of the work.  If a schema error occurs,
57059 ** call sqlite3Reprepare() and try again.
57060 */
57061 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
57062   int rc = SQLITE_OK;      /* Result from sqlite3Step() */
57063   int rc2 = SQLITE_OK;     /* Result from sqlite3Reprepare() */
57064   Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
57065   int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
57066   sqlite3 *db;             /* The database connection */
57067
57068   if( vdbeSafetyNotNull(v) ){
57069     return SQLITE_MISUSE_BKPT;
57070   }
57071   db = v->db;
57072   sqlite3_mutex_enter(db->mutex);
57073   while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
57074          && cnt++ < 5
57075          && (rc2 = rc = sqlite3Reprepare(v))==SQLITE_OK ){
57076     sqlite3_reset(pStmt);
57077     v->expired = 0;
57078   }
57079   if( rc2!=SQLITE_OK && ALWAYS(v->isPrepareV2) && ALWAYS(db->pErr) ){
57080     /* This case occurs after failing to recompile an sql statement. 
57081     ** The error message from the SQL compiler has already been loaded 
57082     ** into the database handle. This block copies the error message 
57083     ** from the database handle into the statement and sets the statement
57084     ** program counter to 0 to ensure that when the statement is 
57085     ** finalized or reset the parser error message is available via
57086     ** sqlite3_errmsg() and sqlite3_errcode().
57087     */
57088     const char *zErr = (const char *)sqlite3_value_text(db->pErr); 
57089     sqlite3DbFree(db, v->zErrMsg);
57090     if( !db->mallocFailed ){
57091       v->zErrMsg = sqlite3DbStrDup(db, zErr);
57092       v->rc = rc2;
57093     } else {
57094       v->zErrMsg = 0;
57095       v->rc = rc = SQLITE_NOMEM;
57096     }
57097   }
57098   rc = sqlite3ApiExit(db, rc);
57099   sqlite3_mutex_leave(db->mutex);
57100   return rc;
57101 }
57102
57103 /*
57104 ** Extract the user data from a sqlite3_context structure and return a
57105 ** pointer to it.
57106 */
57107 SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
57108   assert( p && p->pFunc );
57109   return p->pFunc->pUserData;
57110 }
57111
57112 /*
57113 ** Extract the user data from a sqlite3_context structure and return a
57114 ** pointer to it.
57115 */
57116 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
57117   assert( p && p->pFunc );
57118   return p->s.db;
57119 }
57120
57121 /*
57122 ** The following is the implementation of an SQL function that always
57123 ** fails with an error message stating that the function is used in the
57124 ** wrong context.  The sqlite3_overload_function() API might construct
57125 ** SQL function that use this routine so that the functions will exist
57126 ** for name resolution but are actually overloaded by the xFindFunction
57127 ** method of virtual tables.
57128 */
57129 SQLITE_PRIVATE void sqlite3InvalidFunction(
57130   sqlite3_context *context,  /* The function calling context */
57131   int NotUsed,               /* Number of arguments to the function */
57132   sqlite3_value **NotUsed2   /* Value of each argument */
57133 ){
57134   const char *zName = context->pFunc->zName;
57135   char *zErr;
57136   UNUSED_PARAMETER2(NotUsed, NotUsed2);
57137   zErr = sqlite3_mprintf(
57138       "unable to use function %s in the requested context", zName);
57139   sqlite3_result_error(context, zErr, -1);
57140   sqlite3_free(zErr);
57141 }
57142
57143 /*
57144 ** Allocate or return the aggregate context for a user function.  A new
57145 ** context is allocated on the first call.  Subsequent calls return the
57146 ** same context that was returned on prior calls.
57147 */
57148 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
57149   Mem *pMem;
57150   assert( p && p->pFunc && p->pFunc->xStep );
57151   assert( sqlite3_mutex_held(p->s.db->mutex) );
57152   pMem = p->pMem;
57153   testcase( nByte<0 );
57154   if( (pMem->flags & MEM_Agg)==0 ){
57155     if( nByte<=0 ){
57156       sqlite3VdbeMemReleaseExternal(pMem);
57157       pMem->flags = MEM_Null;
57158       pMem->z = 0;
57159     }else{
57160       sqlite3VdbeMemGrow(pMem, nByte, 0);
57161       pMem->flags = MEM_Agg;
57162       pMem->u.pDef = p->pFunc;
57163       if( pMem->z ){
57164         memset(pMem->z, 0, nByte);
57165       }
57166     }
57167   }
57168   return (void*)pMem->z;
57169 }
57170
57171 /*
57172 ** Return the auxilary data pointer, if any, for the iArg'th argument to
57173 ** the user-function defined by pCtx.
57174 */
57175 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
57176   VdbeFunc *pVdbeFunc;
57177
57178   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
57179   pVdbeFunc = pCtx->pVdbeFunc;
57180   if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
57181     return 0;
57182   }
57183   return pVdbeFunc->apAux[iArg].pAux;
57184 }
57185
57186 /*
57187 ** Set the auxilary data pointer and delete function, for the iArg'th
57188 ** argument to the user-function defined by pCtx. Any previous value is
57189 ** deleted by calling the delete function specified when it was set.
57190 */
57191 SQLITE_API void sqlite3_set_auxdata(
57192   sqlite3_context *pCtx, 
57193   int iArg, 
57194   void *pAux, 
57195   void (*xDelete)(void*)
57196 ){
57197   struct AuxData *pAuxData;
57198   VdbeFunc *pVdbeFunc;
57199   if( iArg<0 ) goto failed;
57200
57201   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
57202   pVdbeFunc = pCtx->pVdbeFunc;
57203   if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
57204     int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
57205     int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
57206     pVdbeFunc = sqlite3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
57207     if( !pVdbeFunc ){
57208       goto failed;
57209     }
57210     pCtx->pVdbeFunc = pVdbeFunc;
57211     memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
57212     pVdbeFunc->nAux = iArg+1;
57213     pVdbeFunc->pFunc = pCtx->pFunc;
57214   }
57215
57216   pAuxData = &pVdbeFunc->apAux[iArg];
57217   if( pAuxData->pAux && pAuxData->xDelete ){
57218     pAuxData->xDelete(pAuxData->pAux);
57219   }
57220   pAuxData->pAux = pAux;
57221   pAuxData->xDelete = xDelete;
57222   return;
57223
57224 failed:
57225   if( xDelete ){
57226     xDelete(pAux);
57227   }
57228 }
57229
57230 #ifndef SQLITE_OMIT_DEPRECATED
57231 /*
57232 ** Return the number of times the Step function of a aggregate has been 
57233 ** called.
57234 **
57235 ** This function is deprecated.  Do not use it for new code.  It is
57236 ** provide only to avoid breaking legacy code.  New aggregate function
57237 ** implementations should keep their own counts within their aggregate
57238 ** context.
57239 */
57240 SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
57241   assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
57242   return p->pMem->n;
57243 }
57244 #endif
57245
57246 /*
57247 ** Return the number of columns in the result set for the statement pStmt.
57248 */
57249 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
57250   Vdbe *pVm = (Vdbe *)pStmt;
57251   return pVm ? pVm->nResColumn : 0;
57252 }
57253
57254 /*
57255 ** Return the number of values available from the current row of the
57256 ** currently executing statement pStmt.
57257 */
57258 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
57259   Vdbe *pVm = (Vdbe *)pStmt;
57260   if( pVm==0 || pVm->pResultSet==0 ) return 0;
57261   return pVm->nResColumn;
57262 }
57263
57264
57265 /*
57266 ** Check to see if column iCol of the given statement is valid.  If
57267 ** it is, return a pointer to the Mem for the value of that column.
57268 ** If iCol is not valid, return a pointer to a Mem which has a value
57269 ** of NULL.
57270 */
57271 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
57272   Vdbe *pVm;
57273   int vals;
57274   Mem *pOut;
57275
57276   pVm = (Vdbe *)pStmt;
57277   if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
57278     sqlite3_mutex_enter(pVm->db->mutex);
57279     vals = sqlite3_data_count(pStmt);
57280     pOut = &pVm->pResultSet[i];
57281   }else{
57282     /* If the value passed as the second argument is out of range, return
57283     ** a pointer to the following static Mem object which contains the
57284     ** value SQL NULL. Even though the Mem structure contains an element
57285     ** of type i64, on certain architecture (x86) with certain compiler
57286     ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
57287     ** instead of an 8-byte one. This all works fine, except that when
57288     ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
57289     ** that a Mem structure is located on an 8-byte boundary. To prevent
57290     ** this assert() from failing, when building with SQLITE_DEBUG defined
57291     ** using gcc, force nullMem to be 8-byte aligned using the magical
57292     ** __attribute__((aligned(8))) macro.  */
57293     static const Mem nullMem 
57294 #if defined(SQLITE_DEBUG) && defined(__GNUC__)
57295       __attribute__((aligned(8))) 
57296 #endif
57297       = {{0}, (double)0, 0, "", 0, MEM_Null, SQLITE_NULL, 0, 0, 0 };
57298
57299     if( pVm && ALWAYS(pVm->db) ){
57300       sqlite3_mutex_enter(pVm->db->mutex);
57301       sqlite3Error(pVm->db, SQLITE_RANGE, 0);
57302     }
57303     pOut = (Mem*)&nullMem;
57304   }
57305   return pOut;
57306 }
57307
57308 /*
57309 ** This function is called after invoking an sqlite3_value_XXX function on a 
57310 ** column value (i.e. a value returned by evaluating an SQL expression in the
57311 ** select list of a SELECT statement) that may cause a malloc() failure. If 
57312 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
57313 ** code of statement pStmt set to SQLITE_NOMEM.
57314 **
57315 ** Specifically, this is called from within:
57316 **
57317 **     sqlite3_column_int()
57318 **     sqlite3_column_int64()
57319 **     sqlite3_column_text()
57320 **     sqlite3_column_text16()
57321 **     sqlite3_column_real()
57322 **     sqlite3_column_bytes()
57323 **     sqlite3_column_bytes16()
57324 **
57325 ** But not for sqlite3_column_blob(), which never calls malloc().
57326 */
57327 static void columnMallocFailure(sqlite3_stmt *pStmt)
57328 {
57329   /* If malloc() failed during an encoding conversion within an
57330   ** sqlite3_column_XXX API, then set the return code of the statement to
57331   ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
57332   ** and _finalize() will return NOMEM.
57333   */
57334   Vdbe *p = (Vdbe *)pStmt;
57335   if( p ){
57336     p->rc = sqlite3ApiExit(p->db, p->rc);
57337     sqlite3_mutex_leave(p->db->mutex);
57338   }
57339 }
57340
57341 /**************************** sqlite3_column_  *******************************
57342 ** The following routines are used to access elements of the current row
57343 ** in the result set.
57344 */
57345 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
57346   const void *val;
57347   val = sqlite3_value_blob( columnMem(pStmt,i) );
57348   /* Even though there is no encoding conversion, value_blob() might
57349   ** need to call malloc() to expand the result of a zeroblob() 
57350   ** expression. 
57351   */
57352   columnMallocFailure(pStmt);
57353   return val;
57354 }
57355 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
57356   int val = sqlite3_value_bytes( columnMem(pStmt,i) );
57357   columnMallocFailure(pStmt);
57358   return val;
57359 }
57360 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
57361   int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
57362   columnMallocFailure(pStmt);
57363   return val;
57364 }
57365 SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
57366   double val = sqlite3_value_double( columnMem(pStmt,i) );
57367   columnMallocFailure(pStmt);
57368   return val;
57369 }
57370 SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
57371   int val = sqlite3_value_int( columnMem(pStmt,i) );
57372   columnMallocFailure(pStmt);
57373   return val;
57374 }
57375 SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
57376   sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
57377   columnMallocFailure(pStmt);
57378   return val;
57379 }
57380 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
57381   const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
57382   columnMallocFailure(pStmt);
57383   return val;
57384 }
57385 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
57386   Mem *pOut = columnMem(pStmt, i);
57387   if( pOut->flags&MEM_Static ){
57388     pOut->flags &= ~MEM_Static;
57389     pOut->flags |= MEM_Ephem;
57390   }
57391   columnMallocFailure(pStmt);
57392   return (sqlite3_value *)pOut;
57393 }
57394 #ifndef SQLITE_OMIT_UTF16
57395 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
57396   const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
57397   columnMallocFailure(pStmt);
57398   return val;
57399 }
57400 #endif /* SQLITE_OMIT_UTF16 */
57401 SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
57402   int iType = sqlite3_value_type( columnMem(pStmt,i) );
57403   columnMallocFailure(pStmt);
57404   return iType;
57405 }
57406
57407 /* The following function is experimental and subject to change or
57408 ** removal */
57409 /*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
57410 **  return sqlite3_value_numeric_type( columnMem(pStmt,i) );
57411 **}
57412 */
57413
57414 /*
57415 ** Convert the N-th element of pStmt->pColName[] into a string using
57416 ** xFunc() then return that string.  If N is out of range, return 0.
57417 **
57418 ** There are up to 5 names for each column.  useType determines which
57419 ** name is returned.  Here are the names:
57420 **
57421 **    0      The column name as it should be displayed for output
57422 **    1      The datatype name for the column
57423 **    2      The name of the database that the column derives from
57424 **    3      The name of the table that the column derives from
57425 **    4      The name of the table column that the result column derives from
57426 **
57427 ** If the result is not a simple column reference (if it is an expression
57428 ** or a constant) then useTypes 2, 3, and 4 return NULL.
57429 */
57430 static const void *columnName(
57431   sqlite3_stmt *pStmt,
57432   int N,
57433   const void *(*xFunc)(Mem*),
57434   int useType
57435 ){
57436   const void *ret = 0;
57437   Vdbe *p = (Vdbe *)pStmt;
57438   int n;
57439   sqlite3 *db = p->db;
57440   
57441   assert( db!=0 );
57442   n = sqlite3_column_count(pStmt);
57443   if( N<n && N>=0 ){
57444     N += useType*n;
57445     sqlite3_mutex_enter(db->mutex);
57446     assert( db->mallocFailed==0 );
57447     ret = xFunc(&p->aColName[N]);
57448      /* A malloc may have failed inside of the xFunc() call. If this
57449     ** is the case, clear the mallocFailed flag and return NULL.
57450     */
57451     if( db->mallocFailed ){
57452       db->mallocFailed = 0;
57453       ret = 0;
57454     }
57455     sqlite3_mutex_leave(db->mutex);
57456   }
57457   return ret;
57458 }
57459
57460 /*
57461 ** Return the name of the Nth column of the result set returned by SQL
57462 ** statement pStmt.
57463 */
57464 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
57465   return columnName(
57466       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
57467 }
57468 #ifndef SQLITE_OMIT_UTF16
57469 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
57470   return columnName(
57471       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
57472 }
57473 #endif
57474
57475 /*
57476 ** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
57477 ** not define OMIT_DECLTYPE.
57478 */
57479 #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
57480 # error "Must not define both SQLITE_OMIT_DECLTYPE \
57481          and SQLITE_ENABLE_COLUMN_METADATA"
57482 #endif
57483
57484 #ifndef SQLITE_OMIT_DECLTYPE
57485 /*
57486 ** Return the column declaration type (if applicable) of the 'i'th column
57487 ** of the result set of SQL statement pStmt.
57488 */
57489 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
57490   return columnName(
57491       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
57492 }
57493 #ifndef SQLITE_OMIT_UTF16
57494 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
57495   return columnName(
57496       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
57497 }
57498 #endif /* SQLITE_OMIT_UTF16 */
57499 #endif /* SQLITE_OMIT_DECLTYPE */
57500
57501 #ifdef SQLITE_ENABLE_COLUMN_METADATA
57502 /*
57503 ** Return the name of the database from which a result column derives.
57504 ** NULL is returned if the result column is an expression or constant or
57505 ** anything else which is not an unabiguous reference to a database column.
57506 */
57507 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
57508   return columnName(
57509       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
57510 }
57511 #ifndef SQLITE_OMIT_UTF16
57512 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
57513   return columnName(
57514       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
57515 }
57516 #endif /* SQLITE_OMIT_UTF16 */
57517
57518 /*
57519 ** Return the name of the table from which a result column derives.
57520 ** NULL is returned if the result column is an expression or constant or
57521 ** anything else which is not an unabiguous reference to a database column.
57522 */
57523 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
57524   return columnName(
57525       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
57526 }
57527 #ifndef SQLITE_OMIT_UTF16
57528 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
57529   return columnName(
57530       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
57531 }
57532 #endif /* SQLITE_OMIT_UTF16 */
57533
57534 /*
57535 ** Return the name of the table column from which a result column derives.
57536 ** NULL is returned if the result column is an expression or constant or
57537 ** anything else which is not an unabiguous reference to a database column.
57538 */
57539 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
57540   return columnName(
57541       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
57542 }
57543 #ifndef SQLITE_OMIT_UTF16
57544 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
57545   return columnName(
57546       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
57547 }
57548 #endif /* SQLITE_OMIT_UTF16 */
57549 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
57550
57551
57552 /******************************* sqlite3_bind_  ***************************
57553 ** 
57554 ** Routines used to attach values to wildcards in a compiled SQL statement.
57555 */
57556 /*
57557 ** Unbind the value bound to variable i in virtual machine p. This is the 
57558 ** the same as binding a NULL value to the column. If the "i" parameter is
57559 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
57560 **
57561 ** A successful evaluation of this routine acquires the mutex on p.
57562 ** the mutex is released if any kind of error occurs.
57563 **
57564 ** The error code stored in database p->db is overwritten with the return
57565 ** value in any case.
57566 */
57567 static int vdbeUnbind(Vdbe *p, int i){
57568   Mem *pVar;
57569   if( vdbeSafetyNotNull(p) ){
57570     return SQLITE_MISUSE_BKPT;
57571   }
57572   sqlite3_mutex_enter(p->db->mutex);
57573   if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
57574     sqlite3Error(p->db, SQLITE_MISUSE, 0);
57575     sqlite3_mutex_leave(p->db->mutex);
57576     sqlite3_log(SQLITE_MISUSE, 
57577         "bind on a busy prepared statement: [%s]", p->zSql);
57578     return SQLITE_MISUSE_BKPT;
57579   }
57580   if( i<1 || i>p->nVar ){
57581     sqlite3Error(p->db, SQLITE_RANGE, 0);
57582     sqlite3_mutex_leave(p->db->mutex);
57583     return SQLITE_RANGE;
57584   }
57585   i--;
57586   pVar = &p->aVar[i];
57587   sqlite3VdbeMemRelease(pVar);
57588   pVar->flags = MEM_Null;
57589   sqlite3Error(p->db, SQLITE_OK, 0);
57590
57591   /* If the bit corresponding to this variable in Vdbe.expmask is set, then 
57592   ** binding a new value to this variable invalidates the current query plan.
57593   */
57594   if( p->isPrepareV2 &&
57595      ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
57596   ){
57597     p->expired = 1;
57598   }
57599   return SQLITE_OK;
57600 }
57601
57602 /*
57603 ** Bind a text or BLOB value.
57604 */
57605 static int bindText(
57606   sqlite3_stmt *pStmt,   /* The statement to bind against */
57607   int i,                 /* Index of the parameter to bind */
57608   const void *zData,     /* Pointer to the data to be bound */
57609   int nData,             /* Number of bytes of data to be bound */
57610   void (*xDel)(void*),   /* Destructor for the data */
57611   u8 encoding            /* Encoding for the data */
57612 ){
57613   Vdbe *p = (Vdbe *)pStmt;
57614   Mem *pVar;
57615   int rc;
57616
57617   rc = vdbeUnbind(p, i);
57618   if( rc==SQLITE_OK ){
57619     if( zData!=0 ){
57620       pVar = &p->aVar[i-1];
57621       rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
57622       if( rc==SQLITE_OK && encoding!=0 ){
57623         rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
57624       }
57625       sqlite3Error(p->db, rc, 0);
57626       rc = sqlite3ApiExit(p->db, rc);
57627     }
57628     sqlite3_mutex_leave(p->db->mutex);
57629   }
57630   return rc;
57631 }
57632
57633
57634 /*
57635 ** Bind a blob value to an SQL statement variable.
57636 */
57637 SQLITE_API int sqlite3_bind_blob(
57638   sqlite3_stmt *pStmt, 
57639   int i, 
57640   const void *zData, 
57641   int nData, 
57642   void (*xDel)(void*)
57643 ){
57644   return bindText(pStmt, i, zData, nData, xDel, 0);
57645 }
57646 SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
57647   int rc;
57648   Vdbe *p = (Vdbe *)pStmt;
57649   rc = vdbeUnbind(p, i);
57650   if( rc==SQLITE_OK ){
57651     sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
57652     sqlite3_mutex_leave(p->db->mutex);
57653   }
57654   return rc;
57655 }
57656 SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
57657   return sqlite3_bind_int64(p, i, (i64)iValue);
57658 }
57659 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
57660   int rc;
57661   Vdbe *p = (Vdbe *)pStmt;
57662   rc = vdbeUnbind(p, i);
57663   if( rc==SQLITE_OK ){
57664     sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
57665     sqlite3_mutex_leave(p->db->mutex);
57666   }
57667   return rc;
57668 }
57669 SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
57670   int rc;
57671   Vdbe *p = (Vdbe*)pStmt;
57672   rc = vdbeUnbind(p, i);
57673   if( rc==SQLITE_OK ){
57674     sqlite3_mutex_leave(p->db->mutex);
57675   }
57676   return rc;
57677 }
57678 SQLITE_API int sqlite3_bind_text( 
57679   sqlite3_stmt *pStmt, 
57680   int i, 
57681   const char *zData, 
57682   int nData, 
57683   void (*xDel)(void*)
57684 ){
57685   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
57686 }
57687 #ifndef SQLITE_OMIT_UTF16
57688 SQLITE_API int sqlite3_bind_text16(
57689   sqlite3_stmt *pStmt, 
57690   int i, 
57691   const void *zData, 
57692   int nData, 
57693   void (*xDel)(void*)
57694 ){
57695   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
57696 }
57697 #endif /* SQLITE_OMIT_UTF16 */
57698 SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
57699   int rc;
57700   switch( pValue->type ){
57701     case SQLITE_INTEGER: {
57702       rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
57703       break;
57704     }
57705     case SQLITE_FLOAT: {
57706       rc = sqlite3_bind_double(pStmt, i, pValue->r);
57707       break;
57708     }
57709     case SQLITE_BLOB: {
57710       if( pValue->flags & MEM_Zero ){
57711         rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
57712       }else{
57713         rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
57714       }
57715       break;
57716     }
57717     case SQLITE_TEXT: {
57718       rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
57719                               pValue->enc);
57720       break;
57721     }
57722     default: {
57723       rc = sqlite3_bind_null(pStmt, i);
57724       break;
57725     }
57726   }
57727   return rc;
57728 }
57729 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
57730   int rc;
57731   Vdbe *p = (Vdbe *)pStmt;
57732   rc = vdbeUnbind(p, i);
57733   if( rc==SQLITE_OK ){
57734     sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
57735     sqlite3_mutex_leave(p->db->mutex);
57736   }
57737   return rc;
57738 }
57739
57740 /*
57741 ** Return the number of wildcards that can be potentially bound to.
57742 ** This routine is added to support DBD::SQLite.  
57743 */
57744 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
57745   Vdbe *p = (Vdbe*)pStmt;
57746   return p ? p->nVar : 0;
57747 }
57748
57749 /*
57750 ** Create a mapping from variable numbers to variable names
57751 ** in the Vdbe.azVar[] array, if such a mapping does not already
57752 ** exist.
57753 */
57754 static void createVarMap(Vdbe *p){
57755   if( !p->okVar ){
57756     int j;
57757     Op *pOp;
57758     sqlite3_mutex_enter(p->db->mutex);
57759     /* The race condition here is harmless.  If two threads call this
57760     ** routine on the same Vdbe at the same time, they both might end
57761     ** up initializing the Vdbe.azVar[] array.  That is a little extra
57762     ** work but it results in the same answer.
57763     */
57764     for(j=0, pOp=p->aOp; j<p->nOp; j++, pOp++){
57765       if( pOp->opcode==OP_Variable ){
57766         assert( pOp->p1>0 && pOp->p1<=p->nVar );
57767         p->azVar[pOp->p1-1] = pOp->p4.z;
57768       }
57769     }
57770     p->okVar = 1;
57771     sqlite3_mutex_leave(p->db->mutex);
57772   }
57773 }
57774
57775 /*
57776 ** Return the name of a wildcard parameter.  Return NULL if the index
57777 ** is out of range or if the wildcard is unnamed.
57778 **
57779 ** The result is always UTF-8.
57780 */
57781 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
57782   Vdbe *p = (Vdbe*)pStmt;
57783   if( p==0 || i<1 || i>p->nVar ){
57784     return 0;
57785   }
57786   createVarMap(p);
57787   return p->azVar[i-1];
57788 }
57789
57790 /*
57791 ** Given a wildcard parameter name, return the index of the variable
57792 ** with that name.  If there is no variable with the given name,
57793 ** return 0.
57794 */
57795 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
57796   int i;
57797   if( p==0 ){
57798     return 0;
57799   }
57800   createVarMap(p); 
57801   if( zName ){
57802     for(i=0; i<p->nVar; i++){
57803       const char *z = p->azVar[i];
57804       if( z && memcmp(z,zName,nName)==0 && z[nName]==0 ){
57805         return i+1;
57806       }
57807     }
57808   }
57809   return 0;
57810 }
57811 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
57812   return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
57813 }
57814
57815 /*
57816 ** Transfer all bindings from the first statement over to the second.
57817 */
57818 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
57819   Vdbe *pFrom = (Vdbe*)pFromStmt;
57820   Vdbe *pTo = (Vdbe*)pToStmt;
57821   int i;
57822   assert( pTo->db==pFrom->db );
57823   assert( pTo->nVar==pFrom->nVar );
57824   sqlite3_mutex_enter(pTo->db->mutex);
57825   for(i=0; i<pFrom->nVar; i++){
57826     sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
57827   }
57828   sqlite3_mutex_leave(pTo->db->mutex);
57829   return SQLITE_OK;
57830 }
57831
57832 #ifndef SQLITE_OMIT_DEPRECATED
57833 /*
57834 ** Deprecated external interface.  Internal/core SQLite code
57835 ** should call sqlite3TransferBindings.
57836 **
57837 ** Is is misuse to call this routine with statements from different
57838 ** database connections.  But as this is a deprecated interface, we
57839 ** will not bother to check for that condition.
57840 **
57841 ** If the two statements contain a different number of bindings, then
57842 ** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
57843 ** SQLITE_OK is returned.
57844 */
57845 SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
57846   Vdbe *pFrom = (Vdbe*)pFromStmt;
57847   Vdbe *pTo = (Vdbe*)pToStmt;
57848   if( pFrom->nVar!=pTo->nVar ){
57849     return SQLITE_ERROR;
57850   }
57851   if( pTo->isPrepareV2 && pTo->expmask ){
57852     pTo->expired = 1;
57853   }
57854   if( pFrom->isPrepareV2 && pFrom->expmask ){
57855     pFrom->expired = 1;
57856   }
57857   return sqlite3TransferBindings(pFromStmt, pToStmt);
57858 }
57859 #endif
57860
57861 /*
57862 ** Return the sqlite3* database handle to which the prepared statement given
57863 ** in the argument belongs.  This is the same database handle that was
57864 ** the first argument to the sqlite3_prepare() that was used to create
57865 ** the statement in the first place.
57866 */
57867 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
57868   return pStmt ? ((Vdbe*)pStmt)->db : 0;
57869 }
57870
57871 /*
57872 ** Return a pointer to the next prepared statement after pStmt associated
57873 ** with database connection pDb.  If pStmt is NULL, return the first
57874 ** prepared statement for the database connection.  Return NULL if there
57875 ** are no more.
57876 */
57877 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
57878   sqlite3_stmt *pNext;
57879   sqlite3_mutex_enter(pDb->mutex);
57880   if( pStmt==0 ){
57881     pNext = (sqlite3_stmt*)pDb->pVdbe;
57882   }else{
57883     pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
57884   }
57885   sqlite3_mutex_leave(pDb->mutex);
57886   return pNext;
57887 }
57888
57889 /*
57890 ** Return the value of a status counter for a prepared statement
57891 */
57892 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
57893   Vdbe *pVdbe = (Vdbe*)pStmt;
57894   int v = pVdbe->aCounter[op-1];
57895   if( resetFlag ) pVdbe->aCounter[op-1] = 0;
57896   return v;
57897 }
57898
57899 /************** End of vdbeapi.c *********************************************/
57900 /************** Begin file vdbetrace.c ***************************************/
57901 /*
57902 ** 2009 November 25
57903 **
57904 ** The author disclaims copyright to this source code.  In place of
57905 ** a legal notice, here is a blessing:
57906 **
57907 **    May you do good and not evil.
57908 **    May you find forgiveness for yourself and forgive others.
57909 **    May you share freely, never taking more than you give.
57910 **
57911 *************************************************************************
57912 **
57913 ** This file contains code used to insert the values of host parameters
57914 ** (aka "wildcards") into the SQL text output by sqlite3_trace().
57915 */
57916
57917 #ifndef SQLITE_OMIT_TRACE
57918
57919 /*
57920 ** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
57921 ** bytes in this text up to but excluding the first character in
57922 ** a host parameter.  If the text contains no host parameters, return
57923 ** the total number of bytes in the text.
57924 */
57925 static int findNextHostParameter(const char *zSql, int *pnToken){
57926   int tokenType;
57927   int nTotal = 0;
57928   int n;
57929
57930   *pnToken = 0;
57931   while( zSql[0] ){
57932     n = sqlite3GetToken((u8*)zSql, &tokenType);
57933     assert( n>0 && tokenType!=TK_ILLEGAL );
57934     if( tokenType==TK_VARIABLE ){
57935       *pnToken = n;
57936       break;
57937     }
57938     nTotal += n;
57939     zSql += n;
57940   }
57941   return nTotal;
57942 }
57943
57944 /*
57945 ** Return a pointer to a string in memory obtained form sqlite3DbMalloc() which
57946 ** holds a copy of zRawSql but with host parameters expanded to their
57947 ** current bindings.
57948 **
57949 ** The calling function is responsible for making sure the memory returned
57950 ** is eventually freed.
57951 **
57952 ** ALGORITHM:  Scan the input string looking for host parameters in any of
57953 ** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
57954 ** string literals, quoted identifier names, and comments.  For text forms,
57955 ** the host parameter index is found by scanning the perpared
57956 ** statement for the corresponding OP_Variable opcode.  Once the host
57957 ** parameter index is known, locate the value in p->aVar[].  Then render
57958 ** the value as a literal in place of the host parameter name.
57959 */
57960 SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
57961   Vdbe *p,                 /* The prepared statement being evaluated */
57962   const char *zRawSql      /* Raw text of the SQL statement */
57963 ){
57964   sqlite3 *db;             /* The database connection */
57965   int idx = 0;             /* Index of a host parameter */
57966   int nextIndex = 1;       /* Index of next ? host parameter */
57967   int n;                   /* Length of a token prefix */
57968   int nToken;              /* Length of the parameter token */
57969   int i;                   /* Loop counter */
57970   Mem *pVar;               /* Value of a host parameter */
57971   StrAccum out;            /* Accumulate the output here */
57972   char zBase[100];         /* Initial working space */
57973
57974   db = p->db;
57975   sqlite3StrAccumInit(&out, zBase, sizeof(zBase), 
57976                       db->aLimit[SQLITE_LIMIT_LENGTH]);
57977   out.db = db;
57978   while( zRawSql[0] ){
57979     n = findNextHostParameter(zRawSql, &nToken);
57980     assert( n>0 );
57981     sqlite3StrAccumAppend(&out, zRawSql, n);
57982     zRawSql += n;
57983     assert( zRawSql[0] || nToken==0 );
57984     if( nToken==0 ) break;
57985     if( zRawSql[0]=='?' ){
57986       if( nToken>1 ){
57987         assert( sqlite3Isdigit(zRawSql[1]) );
57988         sqlite3GetInt32(&zRawSql[1], &idx);
57989       }else{
57990         idx = nextIndex;
57991       }
57992     }else{
57993       assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
57994       testcase( zRawSql[0]==':' );
57995       testcase( zRawSql[0]=='$' );
57996       testcase( zRawSql[0]=='@' );
57997       idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
57998       assert( idx>0 );
57999     }
58000     zRawSql += nToken;
58001     nextIndex = idx + 1;
58002     assert( idx>0 && idx<=p->nVar );
58003     pVar = &p->aVar[idx-1];
58004     if( pVar->flags & MEM_Null ){
58005       sqlite3StrAccumAppend(&out, "NULL", 4);
58006     }else if( pVar->flags & MEM_Int ){
58007       sqlite3XPrintf(&out, "%lld", pVar->u.i);
58008     }else if( pVar->flags & MEM_Real ){
58009       sqlite3XPrintf(&out, "%!.15g", pVar->r);
58010     }else if( pVar->flags & MEM_Str ){
58011 #ifndef SQLITE_OMIT_UTF16
58012       u8 enc = ENC(db);
58013       if( enc!=SQLITE_UTF8 ){
58014         Mem utf8;
58015         memset(&utf8, 0, sizeof(utf8));
58016         utf8.db = db;
58017         sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
58018         sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
58019         sqlite3XPrintf(&out, "'%.*q'", utf8.n, utf8.z);
58020         sqlite3VdbeMemRelease(&utf8);
58021       }else
58022 #endif
58023       {
58024         sqlite3XPrintf(&out, "'%.*q'", pVar->n, pVar->z);
58025       }
58026     }else if( pVar->flags & MEM_Zero ){
58027       sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
58028     }else{
58029       assert( pVar->flags & MEM_Blob );
58030       sqlite3StrAccumAppend(&out, "x'", 2);
58031       for(i=0; i<pVar->n; i++){
58032         sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
58033       }
58034       sqlite3StrAccumAppend(&out, "'", 1);
58035     }
58036   }
58037   return sqlite3StrAccumFinish(&out);
58038 }
58039
58040 #endif /* #ifndef SQLITE_OMIT_TRACE */
58041
58042 /************** End of vdbetrace.c *******************************************/
58043 /************** Begin file vdbe.c ********************************************/
58044 /*
58045 ** 2001 September 15
58046 **
58047 ** The author disclaims copyright to this source code.  In place of
58048 ** a legal notice, here is a blessing:
58049 **
58050 **    May you do good and not evil.
58051 **    May you find forgiveness for yourself and forgive others.
58052 **    May you share freely, never taking more than you give.
58053 **
58054 *************************************************************************
58055 ** The code in this file implements execution method of the 
58056 ** Virtual Database Engine (VDBE).  A separate file ("vdbeaux.c")
58057 ** handles housekeeping details such as creating and deleting
58058 ** VDBE instances.  This file is solely interested in executing
58059 ** the VDBE program.
58060 **
58061 ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
58062 ** to a VDBE.
58063 **
58064 ** The SQL parser generates a program which is then executed by
58065 ** the VDBE to do the work of the SQL statement.  VDBE programs are 
58066 ** similar in form to assembly language.  The program consists of
58067 ** a linear sequence of operations.  Each operation has an opcode 
58068 ** and 5 operands.  Operands P1, P2, and P3 are integers.  Operand P4 
58069 ** is a null-terminated string.  Operand P5 is an unsigned character.
58070 ** Few opcodes use all 5 operands.
58071 **
58072 ** Computation results are stored on a set of registers numbered beginning
58073 ** with 1 and going up to Vdbe.nMem.  Each register can store
58074 ** either an integer, a null-terminated string, a floating point
58075 ** number, or the SQL "NULL" value.  An implicit conversion from one
58076 ** type to the other occurs as necessary.
58077 ** 
58078 ** Most of the code in this file is taken up by the sqlite3VdbeExec()
58079 ** function which does the work of interpreting a VDBE program.
58080 ** But other routines are also provided to help in building up
58081 ** a program instruction by instruction.
58082 **
58083 ** Various scripts scan this source file in order to generate HTML
58084 ** documentation, headers files, or other derived files.  The formatting
58085 ** of the code in this file is, therefore, important.  See other comments
58086 ** in this file for details.  If in doubt, do not deviate from existing
58087 ** commenting and indentation practices when changing or adding code.
58088 */
58089
58090 /*
58091 ** The following global variable is incremented every time a cursor
58092 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
58093 ** procedures use this information to make sure that indices are
58094 ** working correctly.  This variable has no function other than to
58095 ** help verify the correct operation of the library.
58096 */
58097 #ifdef SQLITE_TEST
58098 SQLITE_API int sqlite3_search_count = 0;
58099 #endif
58100
58101 /*
58102 ** When this global variable is positive, it gets decremented once before
58103 ** each instruction in the VDBE.  When reaches zero, the u1.isInterrupted
58104 ** field of the sqlite3 structure is set in order to simulate and interrupt.
58105 **
58106 ** This facility is used for testing purposes only.  It does not function
58107 ** in an ordinary build.
58108 */
58109 #ifdef SQLITE_TEST
58110 SQLITE_API int sqlite3_interrupt_count = 0;
58111 #endif
58112
58113 /*
58114 ** The next global variable is incremented each type the OP_Sort opcode
58115 ** is executed.  The test procedures use this information to make sure that
58116 ** sorting is occurring or not occurring at appropriate times.   This variable
58117 ** has no function other than to help verify the correct operation of the
58118 ** library.
58119 */
58120 #ifdef SQLITE_TEST
58121 SQLITE_API int sqlite3_sort_count = 0;
58122 #endif
58123
58124 /*
58125 ** The next global variable records the size of the largest MEM_Blob
58126 ** or MEM_Str that has been used by a VDBE opcode.  The test procedures
58127 ** use this information to make sure that the zero-blob functionality
58128 ** is working correctly.   This variable has no function other than to
58129 ** help verify the correct operation of the library.
58130 */
58131 #ifdef SQLITE_TEST
58132 SQLITE_API int sqlite3_max_blobsize = 0;
58133 static void updateMaxBlobsize(Mem *p){
58134   if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
58135     sqlite3_max_blobsize = p->n;
58136   }
58137 }
58138 #endif
58139
58140 /*
58141 ** The next global variable is incremented each type the OP_Found opcode
58142 ** is executed. This is used to test whether or not the foreign key
58143 ** operation implemented using OP_FkIsZero is working. This variable
58144 ** has no function other than to help verify the correct operation of the
58145 ** library.
58146 */
58147 #ifdef SQLITE_TEST
58148 SQLITE_API int sqlite3_found_count = 0;
58149 #endif
58150
58151 /*
58152 ** Test a register to see if it exceeds the current maximum blob size.
58153 ** If it does, record the new maximum blob size.
58154 */
58155 #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
58156 # define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
58157 #else
58158 # define UPDATE_MAX_BLOBSIZE(P)
58159 #endif
58160
58161 /*
58162 ** Convert the given register into a string if it isn't one
58163 ** already. Return non-zero if a malloc() fails.
58164 */
58165 #define Stringify(P, enc) \
58166    if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
58167      { goto no_mem; }
58168
58169 /*
58170 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
58171 ** a pointer to a dynamically allocated string where some other entity
58172 ** is responsible for deallocating that string.  Because the register
58173 ** does not control the string, it might be deleted without the register
58174 ** knowing it.
58175 **
58176 ** This routine converts an ephemeral string into a dynamically allocated
58177 ** string that the register itself controls.  In other words, it
58178 ** converts an MEM_Ephem string into an MEM_Dyn string.
58179 */
58180 #define Deephemeralize(P) \
58181    if( ((P)->flags&MEM_Ephem)!=0 \
58182        && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
58183
58184 /*
58185 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
58186 ** P if required.
58187 */
58188 #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
58189
58190 /*
58191 ** Argument pMem points at a register that will be passed to a
58192 ** user-defined function or returned to the user as the result of a query.
58193 ** This routine sets the pMem->type variable used by the sqlite3_value_*() 
58194 ** routines.
58195 */
58196 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem){
58197   int flags = pMem->flags;
58198   if( flags & MEM_Null ){
58199     pMem->type = SQLITE_NULL;
58200   }
58201   else if( flags & MEM_Int ){
58202     pMem->type = SQLITE_INTEGER;
58203   }
58204   else if( flags & MEM_Real ){
58205     pMem->type = SQLITE_FLOAT;
58206   }
58207   else if( flags & MEM_Str ){
58208     pMem->type = SQLITE_TEXT;
58209   }else{
58210     pMem->type = SQLITE_BLOB;
58211   }
58212 }
58213
58214 /*
58215 ** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
58216 ** if we run out of memory.
58217 */
58218 static VdbeCursor *allocateCursor(
58219   Vdbe *p,              /* The virtual machine */
58220   int iCur,             /* Index of the new VdbeCursor */
58221   int nField,           /* Number of fields in the table or index */
58222   int iDb,              /* When database the cursor belongs to, or -1 */
58223   int isBtreeCursor     /* True for B-Tree.  False for pseudo-table or vtab */
58224 ){
58225   /* Find the memory cell that will be used to store the blob of memory
58226   ** required for this VdbeCursor structure. It is convenient to use a 
58227   ** vdbe memory cell to manage the memory allocation required for a
58228   ** VdbeCursor structure for the following reasons:
58229   **
58230   **   * Sometimes cursor numbers are used for a couple of different
58231   **     purposes in a vdbe program. The different uses might require
58232   **     different sized allocations. Memory cells provide growable
58233   **     allocations.
58234   **
58235   **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
58236   **     be freed lazily via the sqlite3_release_memory() API. This
58237   **     minimizes the number of malloc calls made by the system.
58238   **
58239   ** Memory cells for cursors are allocated at the top of the address
58240   ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
58241   ** cursor 1 is managed by memory cell (p->nMem-1), etc.
58242   */
58243   Mem *pMem = &p->aMem[p->nMem-iCur];
58244
58245   int nByte;
58246   VdbeCursor *pCx = 0;
58247   nByte = 
58248       ROUND8(sizeof(VdbeCursor)) + 
58249       (isBtreeCursor?sqlite3BtreeCursorSize():0) + 
58250       2*nField*sizeof(u32);
58251
58252   assert( iCur<p->nCursor );
58253   if( p->apCsr[iCur] ){
58254     sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
58255     p->apCsr[iCur] = 0;
58256   }
58257   if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
58258     p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
58259     memset(pCx, 0, sizeof(VdbeCursor));
58260     pCx->iDb = iDb;
58261     pCx->nField = nField;
58262     if( nField ){
58263       pCx->aType = (u32 *)&pMem->z[ROUND8(sizeof(VdbeCursor))];
58264     }
58265     if( isBtreeCursor ){
58266       pCx->pCursor = (BtCursor*)
58267           &pMem->z[ROUND8(sizeof(VdbeCursor))+2*nField*sizeof(u32)];
58268       sqlite3BtreeCursorZero(pCx->pCursor);
58269     }
58270   }
58271   return pCx;
58272 }
58273
58274 /*
58275 ** Try to convert a value into a numeric representation if we can
58276 ** do so without loss of information.  In other words, if the string
58277 ** looks like a number, convert it into a number.  If it does not
58278 ** look like a number, leave it alone.
58279 */
58280 static void applyNumericAffinity(Mem *pRec){
58281   if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
58282     int realnum;
58283     u8 enc = pRec->enc;
58284     sqlite3VdbeMemNulTerminate(pRec);
58285     if( (pRec->flags&MEM_Str) && sqlite3IsNumber(pRec->z, &realnum, enc) ){
58286       i64 value;
58287       char *zUtf8 = pRec->z;
58288 #ifndef SQLITE_OMIT_UTF16
58289       if( enc!=SQLITE_UTF8 ){
58290         assert( pRec->db );
58291         zUtf8 = sqlite3Utf16to8(pRec->db, pRec->z, pRec->n, enc);
58292         if( !zUtf8 ) return;
58293       }
58294 #endif
58295       if( !realnum && sqlite3Atoi64(zUtf8, &value) ){
58296         pRec->u.i = value;
58297         MemSetTypeFlag(pRec, MEM_Int);
58298       }else{
58299         sqlite3AtoF(zUtf8, &pRec->r);
58300         MemSetTypeFlag(pRec, MEM_Real);
58301       }
58302 #ifndef SQLITE_OMIT_UTF16
58303       if( enc!=SQLITE_UTF8 ){
58304         sqlite3DbFree(pRec->db, zUtf8);
58305       }
58306 #endif
58307     }
58308   }
58309 }
58310
58311 /*
58312 ** Processing is determine by the affinity parameter:
58313 **
58314 ** SQLITE_AFF_INTEGER:
58315 ** SQLITE_AFF_REAL:
58316 ** SQLITE_AFF_NUMERIC:
58317 **    Try to convert pRec to an integer representation or a 
58318 **    floating-point representation if an integer representation
58319 **    is not possible.  Note that the integer representation is
58320 **    always preferred, even if the affinity is REAL, because
58321 **    an integer representation is more space efficient on disk.
58322 **
58323 ** SQLITE_AFF_TEXT:
58324 **    Convert pRec to a text representation.
58325 **
58326 ** SQLITE_AFF_NONE:
58327 **    No-op.  pRec is unchanged.
58328 */
58329 static void applyAffinity(
58330   Mem *pRec,          /* The value to apply affinity to */
58331   char affinity,      /* The affinity to be applied */
58332   u8 enc              /* Use this text encoding */
58333 ){
58334   if( affinity==SQLITE_AFF_TEXT ){
58335     /* Only attempt the conversion to TEXT if there is an integer or real
58336     ** representation (blob and NULL do not get converted) but no string
58337     ** representation.
58338     */
58339     if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
58340       sqlite3VdbeMemStringify(pRec, enc);
58341     }
58342     pRec->flags &= ~(MEM_Real|MEM_Int);
58343   }else if( affinity!=SQLITE_AFF_NONE ){
58344     assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
58345              || affinity==SQLITE_AFF_NUMERIC );
58346     applyNumericAffinity(pRec);
58347     if( pRec->flags & MEM_Real ){
58348       sqlite3VdbeIntegerAffinity(pRec);
58349     }
58350   }
58351 }
58352
58353 /*
58354 ** Try to convert the type of a function argument or a result column
58355 ** into a numeric representation.  Use either INTEGER or REAL whichever
58356 ** is appropriate.  But only do the conversion if it is possible without
58357 ** loss of information and return the revised type of the argument.
58358 **
58359 ** This is an EXPERIMENTAL api and is subject to change or removal.
58360 */
58361 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
58362   Mem *pMem = (Mem*)pVal;
58363   applyNumericAffinity(pMem);
58364   sqlite3VdbeMemStoreType(pMem);
58365   return pMem->type;
58366 }
58367
58368 /*
58369 ** Exported version of applyAffinity(). This one works on sqlite3_value*, 
58370 ** not the internal Mem* type.
58371 */
58372 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
58373   sqlite3_value *pVal, 
58374   u8 affinity, 
58375   u8 enc
58376 ){
58377   applyAffinity((Mem *)pVal, affinity, enc);
58378 }
58379
58380 #ifdef SQLITE_DEBUG
58381 /*
58382 ** Write a nice string representation of the contents of cell pMem
58383 ** into buffer zBuf, length nBuf.
58384 */
58385 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
58386   char *zCsr = zBuf;
58387   int f = pMem->flags;
58388
58389   static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
58390
58391   if( f&MEM_Blob ){
58392     int i;
58393     char c;
58394     if( f & MEM_Dyn ){
58395       c = 'z';
58396       assert( (f & (MEM_Static|MEM_Ephem))==0 );
58397     }else if( f & MEM_Static ){
58398       c = 't';
58399       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
58400     }else if( f & MEM_Ephem ){
58401       c = 'e';
58402       assert( (f & (MEM_Static|MEM_Dyn))==0 );
58403     }else{
58404       c = 's';
58405     }
58406
58407     sqlite3_snprintf(100, zCsr, "%c", c);
58408     zCsr += sqlite3Strlen30(zCsr);
58409     sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
58410     zCsr += sqlite3Strlen30(zCsr);
58411     for(i=0; i<16 && i<pMem->n; i++){
58412       sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
58413       zCsr += sqlite3Strlen30(zCsr);
58414     }
58415     for(i=0; i<16 && i<pMem->n; i++){
58416       char z = pMem->z[i];
58417       if( z<32 || z>126 ) *zCsr++ = '.';
58418       else *zCsr++ = z;
58419     }
58420
58421     sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
58422     zCsr += sqlite3Strlen30(zCsr);
58423     if( f & MEM_Zero ){
58424       sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
58425       zCsr += sqlite3Strlen30(zCsr);
58426     }
58427     *zCsr = '\0';
58428   }else if( f & MEM_Str ){
58429     int j, k;
58430     zBuf[0] = ' ';
58431     if( f & MEM_Dyn ){
58432       zBuf[1] = 'z';
58433       assert( (f & (MEM_Static|MEM_Ephem))==0 );
58434     }else if( f & MEM_Static ){
58435       zBuf[1] = 't';
58436       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
58437     }else if( f & MEM_Ephem ){
58438       zBuf[1] = 'e';
58439       assert( (f & (MEM_Static|MEM_Dyn))==0 );
58440     }else{
58441       zBuf[1] = 's';
58442     }
58443     k = 2;
58444     sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
58445     k += sqlite3Strlen30(&zBuf[k]);
58446     zBuf[k++] = '[';
58447     for(j=0; j<15 && j<pMem->n; j++){
58448       u8 c = pMem->z[j];
58449       if( c>=0x20 && c<0x7f ){
58450         zBuf[k++] = c;
58451       }else{
58452         zBuf[k++] = '.';
58453       }
58454     }
58455     zBuf[k++] = ']';
58456     sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
58457     k += sqlite3Strlen30(&zBuf[k]);
58458     zBuf[k++] = 0;
58459   }
58460 }
58461 #endif
58462
58463 #ifdef SQLITE_DEBUG
58464 /*
58465 ** Print the value of a register for tracing purposes:
58466 */
58467 static void memTracePrint(FILE *out, Mem *p){
58468   if( p->flags & MEM_Null ){
58469     fprintf(out, " NULL");
58470   }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
58471     fprintf(out, " si:%lld", p->u.i);
58472   }else if( p->flags & MEM_Int ){
58473     fprintf(out, " i:%lld", p->u.i);
58474 #ifndef SQLITE_OMIT_FLOATING_POINT
58475   }else if( p->flags & MEM_Real ){
58476     fprintf(out, " r:%g", p->r);
58477 #endif
58478   }else if( p->flags & MEM_RowSet ){
58479     fprintf(out, " (rowset)");
58480   }else{
58481     char zBuf[200];
58482     sqlite3VdbeMemPrettyPrint(p, zBuf);
58483     fprintf(out, " ");
58484     fprintf(out, "%s", zBuf);
58485   }
58486 }
58487 static void registerTrace(FILE *out, int iReg, Mem *p){
58488   fprintf(out, "REG[%d] = ", iReg);
58489   memTracePrint(out, p);
58490   fprintf(out, "\n");
58491 }
58492 #endif
58493
58494 #ifdef SQLITE_DEBUG
58495 #  define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
58496 #else
58497 #  define REGISTER_TRACE(R,M)
58498 #endif
58499
58500
58501 #ifdef VDBE_PROFILE
58502
58503 /* 
58504 ** hwtime.h contains inline assembler code for implementing 
58505 ** high-performance timing routines.
58506 */
58507 /************** Include hwtime.h in the middle of vdbe.c *********************/
58508 /************** Begin file hwtime.h ******************************************/
58509 /*
58510 ** 2008 May 27
58511 **
58512 ** The author disclaims copyright to this source code.  In place of
58513 ** a legal notice, here is a blessing:
58514 **
58515 **    May you do good and not evil.
58516 **    May you find forgiveness for yourself and forgive others.
58517 **    May you share freely, never taking more than you give.
58518 **
58519 ******************************************************************************
58520 **
58521 ** This file contains inline asm code for retrieving "high-performance"
58522 ** counters for x86 class CPUs.
58523 */
58524 #ifndef _HWTIME_H_
58525 #define _HWTIME_H_
58526
58527 /*
58528 ** The following routine only works on pentium-class (or newer) processors.
58529 ** It uses the RDTSC opcode to read the cycle count value out of the
58530 ** processor and returns that value.  This can be used for high-res
58531 ** profiling.
58532 */
58533 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
58534       (defined(i386) || defined(__i386__) || defined(_M_IX86))
58535
58536   #if defined(__GNUC__)
58537
58538   __inline__ sqlite_uint64 sqlite3Hwtime(void){
58539      unsigned int lo, hi;
58540      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
58541      return (sqlite_uint64)hi << 32 | lo;
58542   }
58543
58544   #elif defined(_MSC_VER)
58545
58546   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
58547      __asm {
58548         rdtsc
58549         ret       ; return value at EDX:EAX
58550      }
58551   }
58552
58553   #endif
58554
58555 #elif (defined(__GNUC__) && defined(__x86_64__))
58556
58557   __inline__ sqlite_uint64 sqlite3Hwtime(void){
58558       unsigned long val;
58559       __asm__ __volatile__ ("rdtsc" : "=A" (val));
58560       return val;
58561   }
58562  
58563 #elif (defined(__GNUC__) && defined(__ppc__))
58564
58565   __inline__ sqlite_uint64 sqlite3Hwtime(void){
58566       unsigned long long retval;
58567       unsigned long junk;
58568       __asm__ __volatile__ ("\n\
58569           1:      mftbu   %1\n\
58570                   mftb    %L0\n\
58571                   mftbu   %0\n\
58572                   cmpw    %0,%1\n\
58573                   bne     1b"
58574                   : "=r" (retval), "=r" (junk));
58575       return retval;
58576   }
58577
58578 #else
58579
58580   #error Need implementation of sqlite3Hwtime() for your platform.
58581
58582   /*
58583   ** To compile without implementing sqlite3Hwtime() for your platform,
58584   ** you can remove the above #error and use the following
58585   ** stub function.  You will lose timing support for many
58586   ** of the debugging and testing utilities, but it should at
58587   ** least compile and run.
58588   */
58589 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
58590
58591 #endif
58592
58593 #endif /* !defined(_HWTIME_H_) */
58594
58595 /************** End of hwtime.h **********************************************/
58596 /************** Continuing where we left off in vdbe.c ***********************/
58597
58598 #endif
58599
58600 /*
58601 ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
58602 ** sqlite3_interrupt() routine has been called.  If it has been, then
58603 ** processing of the VDBE program is interrupted.
58604 **
58605 ** This macro added to every instruction that does a jump in order to
58606 ** implement a loop.  This test used to be on every single instruction,
58607 ** but that meant we more testing that we needed.  By only testing the
58608 ** flag on jump instructions, we get a (small) speed improvement.
58609 */
58610 #define CHECK_FOR_INTERRUPT \
58611    if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
58612
58613
58614 #ifndef NDEBUG
58615 /*
58616 ** This function is only called from within an assert() expression. It
58617 ** checks that the sqlite3.nTransaction variable is correctly set to
58618 ** the number of non-transaction savepoints currently in the 
58619 ** linked list starting at sqlite3.pSavepoint.
58620 ** 
58621 ** Usage:
58622 **
58623 **     assert( checkSavepointCount(db) );
58624 */
58625 static int checkSavepointCount(sqlite3 *db){
58626   int n = 0;
58627   Savepoint *p;
58628   for(p=db->pSavepoint; p; p=p->pNext) n++;
58629   assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
58630   return 1;
58631 }
58632 #endif
58633
58634 /*
58635 ** Execute as much of a VDBE program as we can then return.
58636 **
58637 ** sqlite3VdbeMakeReady() must be called before this routine in order to
58638 ** close the program with a final OP_Halt and to set up the callbacks
58639 ** and the error message pointer.
58640 **
58641 ** Whenever a row or result data is available, this routine will either
58642 ** invoke the result callback (if there is one) or return with
58643 ** SQLITE_ROW.
58644 **
58645 ** If an attempt is made to open a locked database, then this routine
58646 ** will either invoke the busy callback (if there is one) or it will
58647 ** return SQLITE_BUSY.
58648 **
58649 ** If an error occurs, an error message is written to memory obtained
58650 ** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
58651 ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
58652 **
58653 ** If the callback ever returns non-zero, then the program exits
58654 ** immediately.  There will be no error message but the p->rc field is
58655 ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
58656 **
58657 ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
58658 ** routine to return SQLITE_ERROR.
58659 **
58660 ** Other fatal errors return SQLITE_ERROR.
58661 **
58662 ** After this routine has finished, sqlite3VdbeFinalize() should be
58663 ** used to clean up the mess that was left behind.
58664 */
58665 SQLITE_PRIVATE int sqlite3VdbeExec(
58666   Vdbe *p                    /* The VDBE */
58667 ){
58668   int pc=0;                  /* The program counter */
58669   Op *aOp = p->aOp;          /* Copy of p->aOp */
58670   Op *pOp;                   /* Current operation */
58671   int rc = SQLITE_OK;        /* Value to return */
58672   sqlite3 *db = p->db;       /* The database */
58673   u8 resetSchemaOnFault = 0; /* Reset schema after an error if true */
58674   u8 encoding = ENC(db);     /* The database encoding */
58675 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
58676   int checkProgress;         /* True if progress callbacks are enabled */
58677   int nProgressOps = 0;      /* Opcodes executed since progress callback. */
58678 #endif
58679   Mem *aMem = p->aMem;       /* Copy of p->aMem */
58680   Mem *pIn1 = 0;             /* 1st input operand */
58681   Mem *pIn2 = 0;             /* 2nd input operand */
58682   Mem *pIn3 = 0;             /* 3rd input operand */
58683   Mem *pOut = 0;             /* Output operand */
58684   int iCompare = 0;          /* Result of last OP_Compare operation */
58685   int *aPermute = 0;         /* Permutation of columns for OP_Compare */
58686 #ifdef VDBE_PROFILE
58687   u64 start;                 /* CPU clock count at start of opcode */
58688   int origPc;                /* Program counter at start of opcode */
58689 #endif
58690   /********************************************************************
58691   ** Automatically generated code
58692   **
58693   ** The following union is automatically generated by the
58694   ** vdbe-compress.tcl script.  The purpose of this union is to
58695   ** reduce the amount of stack space required by this function.
58696   ** See comments in the vdbe-compress.tcl script for details.
58697   */
58698   union vdbeExecUnion {
58699     struct OP_Yield_stack_vars {
58700       int pcDest;
58701     } aa;
58702     struct OP_Variable_stack_vars {
58703       Mem *pVar;       /* Value being transferred */
58704     } ab;
58705     struct OP_Move_stack_vars {
58706       char *zMalloc;   /* Holding variable for allocated memory */
58707       int n;           /* Number of registers left to copy */
58708       int p1;          /* Register to copy from */
58709       int p2;          /* Register to copy to */
58710     } ac;
58711     struct OP_ResultRow_stack_vars {
58712       Mem *pMem;
58713       int i;
58714     } ad;
58715     struct OP_Concat_stack_vars {
58716       i64 nByte;
58717     } ae;
58718     struct OP_Remainder_stack_vars {
58719       int flags;      /* Combined MEM_* flags from both inputs */
58720       i64 iA;         /* Integer value of left operand */
58721       i64 iB;         /* Integer value of right operand */
58722       double rA;      /* Real value of left operand */
58723       double rB;      /* Real value of right operand */
58724     } af;
58725     struct OP_Function_stack_vars {
58726       int i;
58727       Mem *pArg;
58728       sqlite3_context ctx;
58729       sqlite3_value **apVal;
58730       int n;
58731     } ag;
58732     struct OP_ShiftRight_stack_vars {
58733       i64 a;
58734       i64 b;
58735     } ah;
58736     struct OP_Ge_stack_vars {
58737       int res;            /* Result of the comparison of pIn1 against pIn3 */
58738       char affinity;      /* Affinity to use for comparison */
58739       u16 flags1;         /* Copy of initial value of pIn1->flags */
58740       u16 flags3;         /* Copy of initial value of pIn3->flags */
58741     } ai;
58742     struct OP_Compare_stack_vars {
58743       int n;
58744       int i;
58745       int p1;
58746       int p2;
58747       const KeyInfo *pKeyInfo;
58748       int idx;
58749       CollSeq *pColl;    /* Collating sequence to use on this term */
58750       int bRev;          /* True for DESCENDING sort order */
58751     } aj;
58752     struct OP_Or_stack_vars {
58753       int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
58754       int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
58755     } ak;
58756     struct OP_IfNot_stack_vars {
58757       int c;
58758     } al;
58759     struct OP_Column_stack_vars {
58760       u32 payloadSize;   /* Number of bytes in the record */
58761       i64 payloadSize64; /* Number of bytes in the record */
58762       int p1;            /* P1 value of the opcode */
58763       int p2;            /* column number to retrieve */
58764       VdbeCursor *pC;    /* The VDBE cursor */
58765       char *zRec;        /* Pointer to complete record-data */
58766       BtCursor *pCrsr;   /* The BTree cursor */
58767       u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
58768       u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
58769       int nField;        /* number of fields in the record */
58770       int len;           /* The length of the serialized data for the column */
58771       int i;             /* Loop counter */
58772       char *zData;       /* Part of the record being decoded */
58773       Mem *pDest;        /* Where to write the extracted value */
58774       Mem sMem;          /* For storing the record being decoded */
58775       u8 *zIdx;          /* Index into header */
58776       u8 *zEndHdr;       /* Pointer to first byte after the header */
58777       u32 offset;        /* Offset into the data */
58778       u32 szField;       /* Number of bytes in the content of a field */
58779       int szHdr;         /* Size of the header size field at start of record */
58780       int avail;         /* Number of bytes of available data */
58781       Mem *pReg;         /* PseudoTable input register */
58782     } am;
58783     struct OP_Affinity_stack_vars {
58784       const char *zAffinity;   /* The affinity to be applied */
58785       char cAff;               /* A single character of affinity */
58786     } an;
58787     struct OP_MakeRecord_stack_vars {
58788       u8 *zNewRecord;        /* A buffer to hold the data for the new record */
58789       Mem *pRec;             /* The new record */
58790       u64 nData;             /* Number of bytes of data space */
58791       int nHdr;              /* Number of bytes of header space */
58792       i64 nByte;             /* Data space required for this record */
58793       int nZero;             /* Number of zero bytes at the end of the record */
58794       int nVarint;           /* Number of bytes in a varint */
58795       u32 serial_type;       /* Type field */
58796       Mem *pData0;           /* First field to be combined into the record */
58797       Mem *pLast;            /* Last field of the record */
58798       int nField;            /* Number of fields in the record */
58799       char *zAffinity;       /* The affinity string for the record */
58800       int file_format;       /* File format to use for encoding */
58801       int i;                 /* Space used in zNewRecord[] */
58802       int len;               /* Length of a field */
58803     } ao;
58804     struct OP_Count_stack_vars {
58805       i64 nEntry;
58806       BtCursor *pCrsr;
58807     } ap;
58808     struct OP_Savepoint_stack_vars {
58809       int p1;                         /* Value of P1 operand */
58810       char *zName;                    /* Name of savepoint */
58811       int nName;
58812       Savepoint *pNew;
58813       Savepoint *pSavepoint;
58814       Savepoint *pTmp;
58815       int iSavepoint;
58816       int ii;
58817     } aq;
58818     struct OP_AutoCommit_stack_vars {
58819       int desiredAutoCommit;
58820       int iRollback;
58821       int turnOnAC;
58822     } ar;
58823     struct OP_Transaction_stack_vars {
58824       Btree *pBt;
58825     } as;
58826     struct OP_ReadCookie_stack_vars {
58827       int iMeta;
58828       int iDb;
58829       int iCookie;
58830     } at;
58831     struct OP_SetCookie_stack_vars {
58832       Db *pDb;
58833     } au;
58834     struct OP_VerifyCookie_stack_vars {
58835       int iMeta;
58836       Btree *pBt;
58837     } av;
58838     struct OP_OpenWrite_stack_vars {
58839       int nField;
58840       KeyInfo *pKeyInfo;
58841       int p2;
58842       int iDb;
58843       int wrFlag;
58844       Btree *pX;
58845       VdbeCursor *pCur;
58846       Db *pDb;
58847     } aw;
58848     struct OP_OpenEphemeral_stack_vars {
58849       VdbeCursor *pCx;
58850     } ax;
58851     struct OP_OpenPseudo_stack_vars {
58852       VdbeCursor *pCx;
58853     } ay;
58854     struct OP_SeekGt_stack_vars {
58855       int res;
58856       int oc;
58857       VdbeCursor *pC;
58858       UnpackedRecord r;
58859       int nField;
58860       i64 iKey;      /* The rowid we are to seek to */
58861     } az;
58862     struct OP_Seek_stack_vars {
58863       VdbeCursor *pC;
58864     } ba;
58865     struct OP_Found_stack_vars {
58866       int alreadyExists;
58867       VdbeCursor *pC;
58868       int res;
58869       UnpackedRecord *pIdxKey;
58870       UnpackedRecord r;
58871       char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
58872     } bb;
58873     struct OP_IsUnique_stack_vars {
58874       u16 ii;
58875       VdbeCursor *pCx;
58876       BtCursor *pCrsr;
58877       u16 nField;
58878       Mem *aMx;
58879       UnpackedRecord r;                  /* B-Tree index search key */
58880       i64 R;                             /* Rowid stored in register P3 */
58881     } bc;
58882     struct OP_NotExists_stack_vars {
58883       VdbeCursor *pC;
58884       BtCursor *pCrsr;
58885       int res;
58886       u64 iKey;
58887     } bd;
58888     struct OP_NewRowid_stack_vars {
58889       i64 v;                 /* The new rowid */
58890       VdbeCursor *pC;        /* Cursor of table to get the new rowid */
58891       int res;               /* Result of an sqlite3BtreeLast() */
58892       int cnt;               /* Counter to limit the number of searches */
58893       Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
58894       VdbeFrame *pFrame;     /* Root frame of VDBE */
58895     } be;
58896     struct OP_InsertInt_stack_vars {
58897       Mem *pData;       /* MEM cell holding data for the record to be inserted */
58898       Mem *pKey;        /* MEM cell holding key  for the record */
58899       i64 iKey;         /* The integer ROWID or key for the record to be inserted */
58900       VdbeCursor *pC;   /* Cursor to table into which insert is written */
58901       int nZero;        /* Number of zero-bytes to append */
58902       int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
58903       const char *zDb;  /* database name - used by the update hook */
58904       const char *zTbl; /* Table name - used by the opdate hook */
58905       int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
58906     } bf;
58907     struct OP_Delete_stack_vars {
58908       i64 iKey;
58909       VdbeCursor *pC;
58910     } bg;
58911     struct OP_RowData_stack_vars {
58912       VdbeCursor *pC;
58913       BtCursor *pCrsr;
58914       u32 n;
58915       i64 n64;
58916     } bh;
58917     struct OP_Rowid_stack_vars {
58918       VdbeCursor *pC;
58919       i64 v;
58920       sqlite3_vtab *pVtab;
58921       const sqlite3_module *pModule;
58922     } bi;
58923     struct OP_NullRow_stack_vars {
58924       VdbeCursor *pC;
58925     } bj;
58926     struct OP_Last_stack_vars {
58927       VdbeCursor *pC;
58928       BtCursor *pCrsr;
58929       int res;
58930     } bk;
58931     struct OP_Rewind_stack_vars {
58932       VdbeCursor *pC;
58933       BtCursor *pCrsr;
58934       int res;
58935     } bl;
58936     struct OP_Next_stack_vars {
58937       VdbeCursor *pC;
58938       BtCursor *pCrsr;
58939       int res;
58940     } bm;
58941     struct OP_IdxInsert_stack_vars {
58942       VdbeCursor *pC;
58943       BtCursor *pCrsr;
58944       int nKey;
58945       const char *zKey;
58946     } bn;
58947     struct OP_IdxDelete_stack_vars {
58948       VdbeCursor *pC;
58949       BtCursor *pCrsr;
58950       int res;
58951       UnpackedRecord r;
58952     } bo;
58953     struct OP_IdxRowid_stack_vars {
58954       BtCursor *pCrsr;
58955       VdbeCursor *pC;
58956       i64 rowid;
58957     } bp;
58958     struct OP_IdxGE_stack_vars {
58959       VdbeCursor *pC;
58960       int res;
58961       UnpackedRecord r;
58962     } bq;
58963     struct OP_Destroy_stack_vars {
58964       int iMoved;
58965       int iCnt;
58966       Vdbe *pVdbe;
58967       int iDb;
58968     } br;
58969     struct OP_Clear_stack_vars {
58970       int nChange;
58971     } bs;
58972     struct OP_CreateTable_stack_vars {
58973       int pgno;
58974       int flags;
58975       Db *pDb;
58976     } bt;
58977     struct OP_ParseSchema_stack_vars {
58978       int iDb;
58979       const char *zMaster;
58980       char *zSql;
58981       InitData initData;
58982     } bu;
58983     struct OP_IntegrityCk_stack_vars {
58984       int nRoot;      /* Number of tables to check.  (Number of root pages.) */
58985       int *aRoot;     /* Array of rootpage numbers for tables to be checked */
58986       int j;          /* Loop counter */
58987       int nErr;       /* Number of errors reported */
58988       char *z;        /* Text of the error report */
58989       Mem *pnErr;     /* Register keeping track of errors remaining */
58990     } bv;
58991     struct OP_RowSetRead_stack_vars {
58992       i64 val;
58993     } bw;
58994     struct OP_RowSetTest_stack_vars {
58995       int iSet;
58996       int exists;
58997     } bx;
58998     struct OP_Program_stack_vars {
58999       int nMem;               /* Number of memory registers for sub-program */
59000       int nByte;              /* Bytes of runtime space required for sub-program */
59001       Mem *pRt;               /* Register to allocate runtime space */
59002       Mem *pMem;              /* Used to iterate through memory cells */
59003       Mem *pEnd;              /* Last memory cell in new array */
59004       VdbeFrame *pFrame;      /* New vdbe frame to execute in */
59005       SubProgram *pProgram;   /* Sub-program to execute */
59006       void *t;                /* Token identifying trigger */
59007     } by;
59008     struct OP_Param_stack_vars {
59009       VdbeFrame *pFrame;
59010       Mem *pIn;
59011     } bz;
59012     struct OP_MemMax_stack_vars {
59013       Mem *pIn1;
59014       VdbeFrame *pFrame;
59015     } ca;
59016     struct OP_AggStep_stack_vars {
59017       int n;
59018       int i;
59019       Mem *pMem;
59020       Mem *pRec;
59021       sqlite3_context ctx;
59022       sqlite3_value **apVal;
59023     } cb;
59024     struct OP_AggFinal_stack_vars {
59025       Mem *pMem;
59026     } cc;
59027     struct OP_JournalMode_stack_vars {
59028       Btree *pBt;                     /* Btree to change journal mode of */
59029       Pager *pPager;                  /* Pager associated with pBt */
59030       int eNew;                       /* New journal mode */
59031       int eOld;                       /* The old journal mode */
59032       const char *zFilename;          /* Name of database file for pPager */
59033     } cd;
59034     struct OP_IncrVacuum_stack_vars {
59035       Btree *pBt;
59036     } ce;
59037     struct OP_VBegin_stack_vars {
59038       VTable *pVTab;
59039     } cf;
59040     struct OP_VOpen_stack_vars {
59041       VdbeCursor *pCur;
59042       sqlite3_vtab_cursor *pVtabCursor;
59043       sqlite3_vtab *pVtab;
59044       sqlite3_module *pModule;
59045     } cg;
59046     struct OP_VFilter_stack_vars {
59047       int nArg;
59048       int iQuery;
59049       const sqlite3_module *pModule;
59050       Mem *pQuery;
59051       Mem *pArgc;
59052       sqlite3_vtab_cursor *pVtabCursor;
59053       sqlite3_vtab *pVtab;
59054       VdbeCursor *pCur;
59055       int res;
59056       int i;
59057       Mem **apArg;
59058     } ch;
59059     struct OP_VColumn_stack_vars {
59060       sqlite3_vtab *pVtab;
59061       const sqlite3_module *pModule;
59062       Mem *pDest;
59063       sqlite3_context sContext;
59064     } ci;
59065     struct OP_VNext_stack_vars {
59066       sqlite3_vtab *pVtab;
59067       const sqlite3_module *pModule;
59068       int res;
59069       VdbeCursor *pCur;
59070     } cj;
59071     struct OP_VRename_stack_vars {
59072       sqlite3_vtab *pVtab;
59073       Mem *pName;
59074     } ck;
59075     struct OP_VUpdate_stack_vars {
59076       sqlite3_vtab *pVtab;
59077       sqlite3_module *pModule;
59078       int nArg;
59079       int i;
59080       sqlite_int64 rowid;
59081       Mem **apArg;
59082       Mem *pX;
59083     } cl;
59084     struct OP_Trace_stack_vars {
59085       char *zTrace;
59086     } cm;
59087   } u;
59088   /* End automatically generated code
59089   ********************************************************************/
59090
59091   assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
59092   sqlite3VdbeMutexArrayEnter(p);
59093   if( p->rc==SQLITE_NOMEM ){
59094     /* This happens if a malloc() inside a call to sqlite3_column_text() or
59095     ** sqlite3_column_text16() failed.  */
59096     goto no_mem;
59097   }
59098   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
59099   p->rc = SQLITE_OK;
59100   assert( p->explain==0 );
59101   p->pResultSet = 0;
59102   db->busyHandler.nBusy = 0;
59103   CHECK_FOR_INTERRUPT;
59104   sqlite3VdbeIOTraceSql(p);
59105 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
59106   checkProgress = db->xProgress!=0;
59107 #endif
59108 #ifdef SQLITE_DEBUG
59109   sqlite3BeginBenignMalloc();
59110   if( p->pc==0  && (p->db->flags & SQLITE_VdbeListing)!=0 ){
59111     int i;
59112     printf("VDBE Program Listing:\n");
59113     sqlite3VdbePrintSql(p);
59114     for(i=0; i<p->nOp; i++){
59115       sqlite3VdbePrintOp(stdout, i, &aOp[i]);
59116     }
59117   }
59118   sqlite3EndBenignMalloc();
59119 #endif
59120   for(pc=p->pc; rc==SQLITE_OK; pc++){
59121     assert( pc>=0 && pc<p->nOp );
59122     if( db->mallocFailed ) goto no_mem;
59123 #ifdef VDBE_PROFILE
59124     origPc = pc;
59125     start = sqlite3Hwtime();
59126 #endif
59127     pOp = &aOp[pc];
59128
59129     /* Only allow tracing if SQLITE_DEBUG is defined.
59130     */
59131 #ifdef SQLITE_DEBUG
59132     if( p->trace ){
59133       if( pc==0 ){
59134         printf("VDBE Execution Trace:\n");
59135         sqlite3VdbePrintSql(p);
59136       }
59137       sqlite3VdbePrintOp(p->trace, pc, pOp);
59138     }
59139 #endif
59140       
59141
59142     /* Check to see if we need to simulate an interrupt.  This only happens
59143     ** if we have a special test build.
59144     */
59145 #ifdef SQLITE_TEST
59146     if( sqlite3_interrupt_count>0 ){
59147       sqlite3_interrupt_count--;
59148       if( sqlite3_interrupt_count==0 ){
59149         sqlite3_interrupt(db);
59150       }
59151     }
59152 #endif
59153
59154 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
59155     /* Call the progress callback if it is configured and the required number
59156     ** of VDBE ops have been executed (either since this invocation of
59157     ** sqlite3VdbeExec() or since last time the progress callback was called).
59158     ** If the progress callback returns non-zero, exit the virtual machine with
59159     ** a return code SQLITE_ABORT.
59160     */
59161     if( checkProgress ){
59162       if( db->nProgressOps==nProgressOps ){
59163         int prc;
59164         prc = db->xProgress(db->pProgressArg);
59165         if( prc!=0 ){
59166           rc = SQLITE_INTERRUPT;
59167           goto vdbe_error_halt;
59168         }
59169         nProgressOps = 0;
59170       }
59171       nProgressOps++;
59172     }
59173 #endif
59174
59175     /* On any opcode with the "out2-prerelase" tag, free any
59176     ** external allocations out of mem[p2] and set mem[p2] to be
59177     ** an undefined integer.  Opcodes will either fill in the integer
59178     ** value or convert mem[p2] to a different type.
59179     */
59180     assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
59181     if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
59182       assert( pOp->p2>0 );
59183       assert( pOp->p2<=p->nMem );
59184       pOut = &aMem[pOp->p2];
59185       sqlite3VdbeMemReleaseExternal(pOut);
59186       pOut->flags = MEM_Int;
59187     }
59188
59189     /* Sanity checking on other operands */
59190 #ifdef SQLITE_DEBUG
59191     if( (pOp->opflags & OPFLG_IN1)!=0 ){
59192       assert( pOp->p1>0 );
59193       assert( pOp->p1<=p->nMem );
59194       REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
59195     }
59196     if( (pOp->opflags & OPFLG_IN2)!=0 ){
59197       assert( pOp->p2>0 );
59198       assert( pOp->p2<=p->nMem );
59199       REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
59200     }
59201     if( (pOp->opflags & OPFLG_IN3)!=0 ){
59202       assert( pOp->p3>0 );
59203       assert( pOp->p3<=p->nMem );
59204       REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
59205     }
59206     if( (pOp->opflags & OPFLG_OUT2)!=0 ){
59207       assert( pOp->p2>0 );
59208       assert( pOp->p2<=p->nMem );
59209     }
59210     if( (pOp->opflags & OPFLG_OUT3)!=0 ){
59211       assert( pOp->p3>0 );
59212       assert( pOp->p3<=p->nMem );
59213     }
59214 #endif
59215   
59216     switch( pOp->opcode ){
59217
59218 /*****************************************************************************
59219 ** What follows is a massive switch statement where each case implements a
59220 ** separate instruction in the virtual machine.  If we follow the usual
59221 ** indentation conventions, each case should be indented by 6 spaces.  But
59222 ** that is a lot of wasted space on the left margin.  So the code within
59223 ** the switch statement will break with convention and be flush-left. Another
59224 ** big comment (similar to this one) will mark the point in the code where
59225 ** we transition back to normal indentation.
59226 **
59227 ** The formatting of each case is important.  The makefile for SQLite
59228 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
59229 ** file looking for lines that begin with "case OP_".  The opcodes.h files
59230 ** will be filled with #defines that give unique integer values to each
59231 ** opcode and the opcodes.c file is filled with an array of strings where
59232 ** each string is the symbolic name for the corresponding opcode.  If the
59233 ** case statement is followed by a comment of the form "/# same as ... #/"
59234 ** that comment is used to determine the particular value of the opcode.
59235 **
59236 ** Other keywords in the comment that follows each case are used to
59237 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
59238 ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3.  See
59239 ** the mkopcodeh.awk script for additional information.
59240 **
59241 ** Documentation about VDBE opcodes is generated by scanning this file
59242 ** for lines of that contain "Opcode:".  That line and all subsequent
59243 ** comment lines are used in the generation of the opcode.html documentation
59244 ** file.
59245 **
59246 ** SUMMARY:
59247 **
59248 **     Formatting is important to scripts that scan this file.
59249 **     Do not deviate from the formatting style currently in use.
59250 **
59251 *****************************************************************************/
59252
59253 /* Opcode:  Goto * P2 * * *
59254 **
59255 ** An unconditional jump to address P2.
59256 ** The next instruction executed will be 
59257 ** the one at index P2 from the beginning of
59258 ** the program.
59259 */
59260 case OP_Goto: {             /* jump */
59261   CHECK_FOR_INTERRUPT;
59262   pc = pOp->p2 - 1;
59263   break;
59264 }
59265
59266 /* Opcode:  Gosub P1 P2 * * *
59267 **
59268 ** Write the current address onto register P1
59269 ** and then jump to address P2.
59270 */
59271 case OP_Gosub: {            /* jump, in1 */
59272   pIn1 = &aMem[pOp->p1];
59273   assert( (pIn1->flags & MEM_Dyn)==0 );
59274   pIn1->flags = MEM_Int;
59275   pIn1->u.i = pc;
59276   REGISTER_TRACE(pOp->p1, pIn1);
59277   pc = pOp->p2 - 1;
59278   break;
59279 }
59280
59281 /* Opcode:  Return P1 * * * *
59282 **
59283 ** Jump to the next instruction after the address in register P1.
59284 */
59285 case OP_Return: {           /* in1 */
59286   pIn1 = &aMem[pOp->p1];
59287   assert( pIn1->flags & MEM_Int );
59288   pc = (int)pIn1->u.i;
59289   break;
59290 }
59291
59292 /* Opcode:  Yield P1 * * * *
59293 **
59294 ** Swap the program counter with the value in register P1.
59295 */
59296 case OP_Yield: {            /* in1 */
59297 #if 0  /* local variables moved into u.aa */
59298   int pcDest;
59299 #endif /* local variables moved into u.aa */
59300   pIn1 = &aMem[pOp->p1];
59301   assert( (pIn1->flags & MEM_Dyn)==0 );
59302   pIn1->flags = MEM_Int;
59303   u.aa.pcDest = (int)pIn1->u.i;
59304   pIn1->u.i = pc;
59305   REGISTER_TRACE(pOp->p1, pIn1);
59306   pc = u.aa.pcDest;
59307   break;
59308 }
59309
59310 /* Opcode:  HaltIfNull  P1 P2 P3 P4 *
59311 **
59312 ** Check the value in register P3.  If is is NULL then Halt using
59313 ** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
59314 ** value in register P3 is not NULL, then this routine is a no-op.
59315 */
59316 case OP_HaltIfNull: {      /* in3 */
59317   pIn3 = &aMem[pOp->p3];
59318   if( (pIn3->flags & MEM_Null)==0 ) break;
59319   /* Fall through into OP_Halt */
59320 }
59321
59322 /* Opcode:  Halt P1 P2 * P4 *
59323 **
59324 ** Exit immediately.  All open cursors, etc are closed
59325 ** automatically.
59326 **
59327 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
59328 ** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
59329 ** For errors, it can be some other value.  If P1!=0 then P2 will determine
59330 ** whether or not to rollback the current transaction.  Do not rollback
59331 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
59332 ** then back out all changes that have occurred during this execution of the
59333 ** VDBE, but do not rollback the transaction. 
59334 **
59335 ** If P4 is not null then it is an error message string.
59336 **
59337 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
59338 ** every program.  So a jump past the last instruction of the program
59339 ** is the same as executing Halt.
59340 */
59341 case OP_Halt: {
59342   if( pOp->p1==SQLITE_OK && p->pFrame ){
59343     /* Halt the sub-program. Return control to the parent frame. */
59344     VdbeFrame *pFrame = p->pFrame;
59345     p->pFrame = pFrame->pParent;
59346     p->nFrame--;
59347     sqlite3VdbeSetChanges(db, p->nChange);
59348     pc = sqlite3VdbeFrameRestore(pFrame);
59349     if( pOp->p2==OE_Ignore ){
59350       /* Instruction pc is the OP_Program that invoked the sub-program 
59351       ** currently being halted. If the p2 instruction of this OP_Halt
59352       ** instruction is set to OE_Ignore, then the sub-program is throwing
59353       ** an IGNORE exception. In this case jump to the address specified
59354       ** as the p2 of the calling OP_Program.  */
59355       pc = p->aOp[pc].p2-1;
59356     }
59357     aOp = p->aOp;
59358     aMem = p->aMem;
59359     break;
59360   }
59361
59362   p->rc = pOp->p1;
59363   p->errorAction = (u8)pOp->p2;
59364   p->pc = pc;
59365   if( pOp->p4.z ){
59366     assert( p->rc!=SQLITE_OK );
59367     sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
59368     testcase( sqlite3GlobalConfig.xLog!=0 );
59369     sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pc, p->zSql, pOp->p4.z);
59370   }else if( p->rc ){
59371     testcase( sqlite3GlobalConfig.xLog!=0 );
59372     sqlite3_log(pOp->p1, "constraint failed at %d in [%s]", pc, p->zSql);
59373   }
59374   rc = sqlite3VdbeHalt(p);
59375   assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
59376   if( rc==SQLITE_BUSY ){
59377     p->rc = rc = SQLITE_BUSY;
59378   }else{
59379     assert( rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT );
59380     assert( rc==SQLITE_OK || db->nDeferredCons>0 );
59381     rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
59382   }
59383   goto vdbe_return;
59384 }
59385
59386 /* Opcode: Integer P1 P2 * * *
59387 **
59388 ** The 32-bit integer value P1 is written into register P2.
59389 */
59390 case OP_Integer: {         /* out2-prerelease */
59391   pOut->u.i = pOp->p1;
59392   break;
59393 }
59394
59395 /* Opcode: Int64 * P2 * P4 *
59396 **
59397 ** P4 is a pointer to a 64-bit integer value.
59398 ** Write that value into register P2.
59399 */
59400 case OP_Int64: {           /* out2-prerelease */
59401   assert( pOp->p4.pI64!=0 );
59402   pOut->u.i = *pOp->p4.pI64;
59403   break;
59404 }
59405
59406 #ifndef SQLITE_OMIT_FLOATING_POINT
59407 /* Opcode: Real * P2 * P4 *
59408 **
59409 ** P4 is a pointer to a 64-bit floating point value.
59410 ** Write that value into register P2.
59411 */
59412 case OP_Real: {            /* same as TK_FLOAT, out2-prerelease */
59413   pOut->flags = MEM_Real;
59414   assert( !sqlite3IsNaN(*pOp->p4.pReal) );
59415   pOut->r = *pOp->p4.pReal;
59416   break;
59417 }
59418 #endif
59419
59420 /* Opcode: String8 * P2 * P4 *
59421 **
59422 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed 
59423 ** into an OP_String before it is executed for the first time.
59424 */
59425 case OP_String8: {         /* same as TK_STRING, out2-prerelease */
59426   assert( pOp->p4.z!=0 );
59427   pOp->opcode = OP_String;
59428   pOp->p1 = sqlite3Strlen30(pOp->p4.z);
59429
59430 #ifndef SQLITE_OMIT_UTF16
59431   if( encoding!=SQLITE_UTF8 ){
59432     rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
59433     if( rc==SQLITE_TOOBIG ) goto too_big;
59434     if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
59435     assert( pOut->zMalloc==pOut->z );
59436     assert( pOut->flags & MEM_Dyn );
59437     pOut->zMalloc = 0;
59438     pOut->flags |= MEM_Static;
59439     pOut->flags &= ~MEM_Dyn;
59440     if( pOp->p4type==P4_DYNAMIC ){
59441       sqlite3DbFree(db, pOp->p4.z);
59442     }
59443     pOp->p4type = P4_DYNAMIC;
59444     pOp->p4.z = pOut->z;
59445     pOp->p1 = pOut->n;
59446   }
59447 #endif
59448   if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
59449     goto too_big;
59450   }
59451   /* Fall through to the next case, OP_String */
59452 }
59453   
59454 /* Opcode: String P1 P2 * P4 *
59455 **
59456 ** The string value P4 of length P1 (bytes) is stored in register P2.
59457 */
59458 case OP_String: {          /* out2-prerelease */
59459   assert( pOp->p4.z!=0 );
59460   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
59461   pOut->z = pOp->p4.z;
59462   pOut->n = pOp->p1;
59463   pOut->enc = encoding;
59464   UPDATE_MAX_BLOBSIZE(pOut);
59465   break;
59466 }
59467
59468 /* Opcode: Null * P2 * * *
59469 **
59470 ** Write a NULL into register P2.
59471 */
59472 case OP_Null: {           /* out2-prerelease */
59473   pOut->flags = MEM_Null;
59474   break;
59475 }
59476
59477
59478 /* Opcode: Blob P1 P2 * P4
59479 **
59480 ** P4 points to a blob of data P1 bytes long.  Store this
59481 ** blob in register P2. This instruction is not coded directly
59482 ** by the compiler. Instead, the compiler layer specifies
59483 ** an OP_HexBlob opcode, with the hex string representation of
59484 ** the blob as P4. This opcode is transformed to an OP_Blob
59485 ** the first time it is executed.
59486 */
59487 case OP_Blob: {                /* out2-prerelease */
59488   assert( pOp->p1 <= SQLITE_MAX_LENGTH );
59489   sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
59490   pOut->enc = encoding;
59491   UPDATE_MAX_BLOBSIZE(pOut);
59492   break;
59493 }
59494
59495 /* Opcode: Variable P1 P2 * P4 *
59496 **
59497 ** Transfer the values of bound parameter P1 into register P2
59498 **
59499 ** If the parameter is named, then its name appears in P4 and P3==1.
59500 ** The P4 value is used by sqlite3_bind_parameter_name().
59501 */
59502 case OP_Variable: {            /* out2-prerelease */
59503 #if 0  /* local variables moved into u.ab */
59504   Mem *pVar;       /* Value being transferred */
59505 #endif /* local variables moved into u.ab */
59506
59507   assert( pOp->p1>0 && pOp->p1<=p->nVar );
59508   u.ab.pVar = &p->aVar[pOp->p1 - 1];
59509   if( sqlite3VdbeMemTooBig(u.ab.pVar) ){
59510     goto too_big;
59511   }
59512   sqlite3VdbeMemShallowCopy(pOut, u.ab.pVar, MEM_Static);
59513   UPDATE_MAX_BLOBSIZE(pOut);
59514   break;
59515 }
59516
59517 /* Opcode: Move P1 P2 P3 * *
59518 **
59519 ** Move the values in register P1..P1+P3-1 over into
59520 ** registers P2..P2+P3-1.  Registers P1..P1+P1-1 are
59521 ** left holding a NULL.  It is an error for register ranges
59522 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap.
59523 */
59524 case OP_Move: {
59525 #if 0  /* local variables moved into u.ac */
59526   char *zMalloc;   /* Holding variable for allocated memory */
59527   int n;           /* Number of registers left to copy */
59528   int p1;          /* Register to copy from */
59529   int p2;          /* Register to copy to */
59530 #endif /* local variables moved into u.ac */
59531
59532   u.ac.n = pOp->p3;
59533   u.ac.p1 = pOp->p1;
59534   u.ac.p2 = pOp->p2;
59535   assert( u.ac.n>0 && u.ac.p1>0 && u.ac.p2>0 );
59536   assert( u.ac.p1+u.ac.n<=u.ac.p2 || u.ac.p2+u.ac.n<=u.ac.p1 );
59537
59538   pIn1 = &aMem[u.ac.p1];
59539   pOut = &aMem[u.ac.p2];
59540   while( u.ac.n-- ){
59541     assert( pOut<=&aMem[p->nMem] );
59542     assert( pIn1<=&aMem[p->nMem] );
59543     u.ac.zMalloc = pOut->zMalloc;
59544     pOut->zMalloc = 0;
59545     sqlite3VdbeMemMove(pOut, pIn1);
59546     pIn1->zMalloc = u.ac.zMalloc;
59547     REGISTER_TRACE(u.ac.p2++, pOut);
59548     pIn1++;
59549     pOut++;
59550   }
59551   break;
59552 }
59553
59554 /* Opcode: Copy P1 P2 * * *
59555 **
59556 ** Make a copy of register P1 into register P2.
59557 **
59558 ** This instruction makes a deep copy of the value.  A duplicate
59559 ** is made of any string or blob constant.  See also OP_SCopy.
59560 */
59561 case OP_Copy: {             /* in1, out2 */
59562   pIn1 = &aMem[pOp->p1];
59563   pOut = &aMem[pOp->p2];
59564   assert( pOut!=pIn1 );
59565   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
59566   Deephemeralize(pOut);
59567   REGISTER_TRACE(pOp->p2, pOut);
59568   break;
59569 }
59570
59571 /* Opcode: SCopy P1 P2 * * *
59572 **
59573 ** Make a shallow copy of register P1 into register P2.
59574 **
59575 ** This instruction makes a shallow copy of the value.  If the value
59576 ** is a string or blob, then the copy is only a pointer to the
59577 ** original and hence if the original changes so will the copy.
59578 ** Worse, if the original is deallocated, the copy becomes invalid.
59579 ** Thus the program must guarantee that the original will not change
59580 ** during the lifetime of the copy.  Use OP_Copy to make a complete
59581 ** copy.
59582 */
59583 case OP_SCopy: {            /* in1, out2 */
59584   pIn1 = &aMem[pOp->p1];
59585   pOut = &aMem[pOp->p2];
59586   assert( pOut!=pIn1 );
59587   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
59588   REGISTER_TRACE(pOp->p2, pOut);
59589   break;
59590 }
59591
59592 /* Opcode: ResultRow P1 P2 * * *
59593 **
59594 ** The registers P1 through P1+P2-1 contain a single row of
59595 ** results. This opcode causes the sqlite3_step() call to terminate
59596 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
59597 ** structure to provide access to the top P1 values as the result
59598 ** row.
59599 */
59600 case OP_ResultRow: {
59601 #if 0  /* local variables moved into u.ad */
59602   Mem *pMem;
59603   int i;
59604 #endif /* local variables moved into u.ad */
59605   assert( p->nResColumn==pOp->p2 );
59606   assert( pOp->p1>0 );
59607   assert( pOp->p1+pOp->p2<=p->nMem+1 );
59608
59609   /* If this statement has violated immediate foreign key constraints, do
59610   ** not return the number of rows modified. And do not RELEASE the statement
59611   ** transaction. It needs to be rolled back.  */
59612   if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
59613     assert( db->flags&SQLITE_CountRows );
59614     assert( p->usesStmtJournal );
59615     break;
59616   }
59617
59618   /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
59619   ** DML statements invoke this opcode to return the number of rows
59620   ** modified to the user. This is the only way that a VM that
59621   ** opens a statement transaction may invoke this opcode.
59622   **
59623   ** In case this is such a statement, close any statement transaction
59624   ** opened by this VM before returning control to the user. This is to
59625   ** ensure that statement-transactions are always nested, not overlapping.
59626   ** If the open statement-transaction is not closed here, then the user
59627   ** may step another VM that opens its own statement transaction. This
59628   ** may lead to overlapping statement transactions.
59629   **
59630   ** The statement transaction is never a top-level transaction.  Hence
59631   ** the RELEASE call below can never fail.
59632   */
59633   assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
59634   rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
59635   if( NEVER(rc!=SQLITE_OK) ){
59636     break;
59637   }
59638
59639   /* Invalidate all ephemeral cursor row caches */
59640   p->cacheCtr = (p->cacheCtr + 2)|1;
59641
59642   /* Make sure the results of the current row are \000 terminated
59643   ** and have an assigned type.  The results are de-ephemeralized as
59644   ** as side effect.
59645   */
59646   u.ad.pMem = p->pResultSet = &aMem[pOp->p1];
59647   for(u.ad.i=0; u.ad.i<pOp->p2; u.ad.i++){
59648     sqlite3VdbeMemNulTerminate(&u.ad.pMem[u.ad.i]);
59649     sqlite3VdbeMemStoreType(&u.ad.pMem[u.ad.i]);
59650     REGISTER_TRACE(pOp->p1+u.ad.i, &u.ad.pMem[u.ad.i]);
59651   }
59652   if( db->mallocFailed ) goto no_mem;
59653
59654   /* Return SQLITE_ROW
59655   */
59656   p->pc = pc + 1;
59657   rc = SQLITE_ROW;
59658   goto vdbe_return;
59659 }
59660
59661 /* Opcode: Concat P1 P2 P3 * *
59662 **
59663 ** Add the text in register P1 onto the end of the text in
59664 ** register P2 and store the result in register P3.
59665 ** If either the P1 or P2 text are NULL then store NULL in P3.
59666 **
59667 **   P3 = P2 || P1
59668 **
59669 ** It is illegal for P1 and P3 to be the same register. Sometimes,
59670 ** if P3 is the same register as P2, the implementation is able
59671 ** to avoid a memcpy().
59672 */
59673 case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
59674 #if 0  /* local variables moved into u.ae */
59675   i64 nByte;
59676 #endif /* local variables moved into u.ae */
59677
59678   pIn1 = &aMem[pOp->p1];
59679   pIn2 = &aMem[pOp->p2];
59680   pOut = &aMem[pOp->p3];
59681   assert( pIn1!=pOut );
59682   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
59683     sqlite3VdbeMemSetNull(pOut);
59684     break;
59685   }
59686   if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
59687   Stringify(pIn1, encoding);
59688   Stringify(pIn2, encoding);
59689   u.ae.nByte = pIn1->n + pIn2->n;
59690   if( u.ae.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
59691     goto too_big;
59692   }
59693   MemSetTypeFlag(pOut, MEM_Str);
59694   if( sqlite3VdbeMemGrow(pOut, (int)u.ae.nByte+2, pOut==pIn2) ){
59695     goto no_mem;
59696   }
59697   if( pOut!=pIn2 ){
59698     memcpy(pOut->z, pIn2->z, pIn2->n);
59699   }
59700   memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
59701   pOut->z[u.ae.nByte] = 0;
59702   pOut->z[u.ae.nByte+1] = 0;
59703   pOut->flags |= MEM_Term;
59704   pOut->n = (int)u.ae.nByte;
59705   pOut->enc = encoding;
59706   UPDATE_MAX_BLOBSIZE(pOut);
59707   break;
59708 }
59709
59710 /* Opcode: Add P1 P2 P3 * *
59711 **
59712 ** Add the value in register P1 to the value in register P2
59713 ** and store the result in register P3.
59714 ** If either input is NULL, the result is NULL.
59715 */
59716 /* Opcode: Multiply P1 P2 P3 * *
59717 **
59718 **
59719 ** Multiply the value in register P1 by the value in register P2
59720 ** and store the result in register P3.
59721 ** If either input is NULL, the result is NULL.
59722 */
59723 /* Opcode: Subtract P1 P2 P3 * *
59724 **
59725 ** Subtract the value in register P1 from the value in register P2
59726 ** and store the result in register P3.
59727 ** If either input is NULL, the result is NULL.
59728 */
59729 /* Opcode: Divide P1 P2 P3 * *
59730 **
59731 ** Divide the value in register P1 by the value in register P2
59732 ** and store the result in register P3 (P3=P2/P1). If the value in 
59733 ** register P1 is zero, then the result is NULL. If either input is 
59734 ** NULL, the result is NULL.
59735 */
59736 /* Opcode: Remainder P1 P2 P3 * *
59737 **
59738 ** Compute the remainder after integer division of the value in
59739 ** register P1 by the value in register P2 and store the result in P3. 
59740 ** If the value in register P2 is zero the result is NULL.
59741 ** If either operand is NULL, the result is NULL.
59742 */
59743 case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
59744 case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
59745 case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
59746 case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
59747 case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
59748 #if 0  /* local variables moved into u.af */
59749   int flags;      /* Combined MEM_* flags from both inputs */
59750   i64 iA;         /* Integer value of left operand */
59751   i64 iB;         /* Integer value of right operand */
59752   double rA;      /* Real value of left operand */
59753   double rB;      /* Real value of right operand */
59754 #endif /* local variables moved into u.af */
59755
59756   pIn1 = &aMem[pOp->p1];
59757   applyNumericAffinity(pIn1);
59758   pIn2 = &aMem[pOp->p2];
59759   applyNumericAffinity(pIn2);
59760   pOut = &aMem[pOp->p3];
59761   u.af.flags = pIn1->flags | pIn2->flags;
59762   if( (u.af.flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
59763   if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
59764     u.af.iA = pIn1->u.i;
59765     u.af.iB = pIn2->u.i;
59766     switch( pOp->opcode ){
59767       case OP_Add:         u.af.iB += u.af.iA;       break;
59768       case OP_Subtract:    u.af.iB -= u.af.iA;       break;
59769       case OP_Multiply:    u.af.iB *= u.af.iA;       break;
59770       case OP_Divide: {
59771         if( u.af.iA==0 ) goto arithmetic_result_is_null;
59772         /* Dividing the largest possible negative 64-bit integer (1<<63) by
59773         ** -1 returns an integer too large to store in a 64-bit data-type. On
59774         ** some architectures, the value overflows to (1<<63). On others,
59775         ** a SIGFPE is issued. The following statement normalizes this
59776         ** behavior so that all architectures behave as if integer
59777         ** overflow occurred.
59778         */
59779         if( u.af.iA==-1 && u.af.iB==SMALLEST_INT64 ) u.af.iA = 1;
59780         u.af.iB /= u.af.iA;
59781         break;
59782       }
59783       default: {
59784         if( u.af.iA==0 ) goto arithmetic_result_is_null;
59785         if( u.af.iA==-1 ) u.af.iA = 1;
59786         u.af.iB %= u.af.iA;
59787         break;
59788       }
59789     }
59790     pOut->u.i = u.af.iB;
59791     MemSetTypeFlag(pOut, MEM_Int);
59792   }else{
59793     u.af.rA = sqlite3VdbeRealValue(pIn1);
59794     u.af.rB = sqlite3VdbeRealValue(pIn2);
59795     switch( pOp->opcode ){
59796       case OP_Add:         u.af.rB += u.af.rA;       break;
59797       case OP_Subtract:    u.af.rB -= u.af.rA;       break;
59798       case OP_Multiply:    u.af.rB *= u.af.rA;       break;
59799       case OP_Divide: {
59800         /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
59801         if( u.af.rA==(double)0 ) goto arithmetic_result_is_null;
59802         u.af.rB /= u.af.rA;
59803         break;
59804       }
59805       default: {
59806         u.af.iA = (i64)u.af.rA;
59807         u.af.iB = (i64)u.af.rB;
59808         if( u.af.iA==0 ) goto arithmetic_result_is_null;
59809         if( u.af.iA==-1 ) u.af.iA = 1;
59810         u.af.rB = (double)(u.af.iB % u.af.iA);
59811         break;
59812       }
59813     }
59814 #ifdef SQLITE_OMIT_FLOATING_POINT
59815     pOut->u.i = u.af.rB;
59816     MemSetTypeFlag(pOut, MEM_Int);
59817 #else
59818     if( sqlite3IsNaN(u.af.rB) ){
59819       goto arithmetic_result_is_null;
59820     }
59821     pOut->r = u.af.rB;
59822     MemSetTypeFlag(pOut, MEM_Real);
59823     if( (u.af.flags & MEM_Real)==0 ){
59824       sqlite3VdbeIntegerAffinity(pOut);
59825     }
59826 #endif
59827   }
59828   break;
59829
59830 arithmetic_result_is_null:
59831   sqlite3VdbeMemSetNull(pOut);
59832   break;
59833 }
59834
59835 /* Opcode: CollSeq * * P4
59836 **
59837 ** P4 is a pointer to a CollSeq struct. If the next call to a user function
59838 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
59839 ** be returned. This is used by the built-in min(), max() and nullif()
59840 ** functions.
59841 **
59842 ** The interface used by the implementation of the aforementioned functions
59843 ** to retrieve the collation sequence set by this opcode is not available
59844 ** publicly, only to user functions defined in func.c.
59845 */
59846 case OP_CollSeq: {
59847   assert( pOp->p4type==P4_COLLSEQ );
59848   break;
59849 }
59850
59851 /* Opcode: Function P1 P2 P3 P4 P5
59852 **
59853 ** Invoke a user function (P4 is a pointer to a Function structure that
59854 ** defines the function) with P5 arguments taken from register P2 and
59855 ** successors.  The result of the function is stored in register P3.
59856 ** Register P3 must not be one of the function inputs.
59857 **
59858 ** P1 is a 32-bit bitmask indicating whether or not each argument to the 
59859 ** function was determined to be constant at compile time. If the first
59860 ** argument was constant then bit 0 of P1 is set. This is used to determine
59861 ** whether meta data associated with a user function argument using the
59862 ** sqlite3_set_auxdata() API may be safely retained until the next
59863 ** invocation of this opcode.
59864 **
59865 ** See also: AggStep and AggFinal
59866 */
59867 case OP_Function: {
59868 #if 0  /* local variables moved into u.ag */
59869   int i;
59870   Mem *pArg;
59871   sqlite3_context ctx;
59872   sqlite3_value **apVal;
59873   int n;
59874 #endif /* local variables moved into u.ag */
59875
59876   u.ag.n = pOp->p5;
59877   u.ag.apVal = p->apArg;
59878   assert( u.ag.apVal || u.ag.n==0 );
59879
59880   assert( u.ag.n==0 || (pOp->p2>0 && pOp->p2+u.ag.n<=p->nMem+1) );
59881   assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+u.ag.n );
59882   u.ag.pArg = &aMem[pOp->p2];
59883   for(u.ag.i=0; u.ag.i<u.ag.n; u.ag.i++, u.ag.pArg++){
59884     u.ag.apVal[u.ag.i] = u.ag.pArg;
59885     sqlite3VdbeMemStoreType(u.ag.pArg);
59886     REGISTER_TRACE(pOp->p2+u.ag.i, u.ag.pArg);
59887   }
59888
59889   assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
59890   if( pOp->p4type==P4_FUNCDEF ){
59891     u.ag.ctx.pFunc = pOp->p4.pFunc;
59892     u.ag.ctx.pVdbeFunc = 0;
59893   }else{
59894     u.ag.ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
59895     u.ag.ctx.pFunc = u.ag.ctx.pVdbeFunc->pFunc;
59896   }
59897
59898   assert( pOp->p3>0 && pOp->p3<=p->nMem );
59899   pOut = &aMem[pOp->p3];
59900   u.ag.ctx.s.flags = MEM_Null;
59901   u.ag.ctx.s.db = db;
59902   u.ag.ctx.s.xDel = 0;
59903   u.ag.ctx.s.zMalloc = 0;
59904
59905   /* The output cell may already have a buffer allocated. Move
59906   ** the pointer to u.ag.ctx.s so in case the user-function can use
59907   ** the already allocated buffer instead of allocating a new one.
59908   */
59909   sqlite3VdbeMemMove(&u.ag.ctx.s, pOut);
59910   MemSetTypeFlag(&u.ag.ctx.s, MEM_Null);
59911
59912   u.ag.ctx.isError = 0;
59913   if( u.ag.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
59914     assert( pOp>aOp );
59915     assert( pOp[-1].p4type==P4_COLLSEQ );
59916     assert( pOp[-1].opcode==OP_CollSeq );
59917     u.ag.ctx.pColl = pOp[-1].p4.pColl;
59918   }
59919   (*u.ag.ctx.pFunc->xFunc)(&u.ag.ctx, u.ag.n, u.ag.apVal);
59920   if( db->mallocFailed ){
59921     /* Even though a malloc() has failed, the implementation of the
59922     ** user function may have called an sqlite3_result_XXX() function
59923     ** to return a value. The following call releases any resources
59924     ** associated with such a value.
59925     */
59926     sqlite3VdbeMemRelease(&u.ag.ctx.s);
59927     goto no_mem;
59928   }
59929
59930   /* If any auxiliary data functions have been called by this user function,
59931   ** immediately call the destructor for any non-static values.
59932   */
59933   if( u.ag.ctx.pVdbeFunc ){
59934     sqlite3VdbeDeleteAuxData(u.ag.ctx.pVdbeFunc, pOp->p1);
59935     pOp->p4.pVdbeFunc = u.ag.ctx.pVdbeFunc;
59936     pOp->p4type = P4_VDBEFUNC;
59937   }
59938
59939   /* If the function returned an error, throw an exception */
59940   if( u.ag.ctx.isError ){
59941     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.ag.ctx.s));
59942     rc = u.ag.ctx.isError;
59943   }
59944
59945   /* Copy the result of the function into register P3 */
59946   sqlite3VdbeChangeEncoding(&u.ag.ctx.s, encoding);
59947   sqlite3VdbeMemMove(pOut, &u.ag.ctx.s);
59948   if( sqlite3VdbeMemTooBig(pOut) ){
59949     goto too_big;
59950   }
59951   REGISTER_TRACE(pOp->p3, pOut);
59952   UPDATE_MAX_BLOBSIZE(pOut);
59953   break;
59954 }
59955
59956 /* Opcode: BitAnd P1 P2 P3 * *
59957 **
59958 ** Take the bit-wise AND of the values in register P1 and P2 and
59959 ** store the result in register P3.
59960 ** If either input is NULL, the result is NULL.
59961 */
59962 /* Opcode: BitOr P1 P2 P3 * *
59963 **
59964 ** Take the bit-wise OR of the values in register P1 and P2 and
59965 ** store the result in register P3.
59966 ** If either input is NULL, the result is NULL.
59967 */
59968 /* Opcode: ShiftLeft P1 P2 P3 * *
59969 **
59970 ** Shift the integer value in register P2 to the left by the
59971 ** number of bits specified by the integer in regiser P1.
59972 ** Store the result in register P3.
59973 ** If either input is NULL, the result is NULL.
59974 */
59975 /* Opcode: ShiftRight P1 P2 P3 * *
59976 **
59977 ** Shift the integer value in register P2 to the right by the
59978 ** number of bits specified by the integer in register P1.
59979 ** Store the result in register P3.
59980 ** If either input is NULL, the result is NULL.
59981 */
59982 case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
59983 case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
59984 case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
59985 case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
59986 #if 0  /* local variables moved into u.ah */
59987   i64 a;
59988   i64 b;
59989 #endif /* local variables moved into u.ah */
59990
59991   pIn1 = &aMem[pOp->p1];
59992   pIn2 = &aMem[pOp->p2];
59993   pOut = &aMem[pOp->p3];
59994   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
59995     sqlite3VdbeMemSetNull(pOut);
59996     break;
59997   }
59998   u.ah.a = sqlite3VdbeIntValue(pIn2);
59999   u.ah.b = sqlite3VdbeIntValue(pIn1);
60000   switch( pOp->opcode ){
60001     case OP_BitAnd:      u.ah.a &= u.ah.b;     break;
60002     case OP_BitOr:       u.ah.a |= u.ah.b;     break;
60003     case OP_ShiftLeft:   u.ah.a <<= u.ah.b;    break;
60004     default:  assert( pOp->opcode==OP_ShiftRight );
60005                          u.ah.a >>= u.ah.b;    break;
60006   }
60007   pOut->u.i = u.ah.a;
60008   MemSetTypeFlag(pOut, MEM_Int);
60009   break;
60010 }
60011
60012 /* Opcode: AddImm  P1 P2 * * *
60013 ** 
60014 ** Add the constant P2 to the value in register P1.
60015 ** The result is always an integer.
60016 **
60017 ** To force any register to be an integer, just add 0.
60018 */
60019 case OP_AddImm: {            /* in1 */
60020   pIn1 = &aMem[pOp->p1];
60021   sqlite3VdbeMemIntegerify(pIn1);
60022   pIn1->u.i += pOp->p2;
60023   break;
60024 }
60025
60026 /* Opcode: MustBeInt P1 P2 * * *
60027 ** 
60028 ** Force the value in register P1 to be an integer.  If the value
60029 ** in P1 is not an integer and cannot be converted into an integer
60030 ** without data loss, then jump immediately to P2, or if P2==0
60031 ** raise an SQLITE_MISMATCH exception.
60032 */
60033 case OP_MustBeInt: {            /* jump, in1 */
60034   pIn1 = &aMem[pOp->p1];
60035   applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
60036   if( (pIn1->flags & MEM_Int)==0 ){
60037     if( pOp->p2==0 ){
60038       rc = SQLITE_MISMATCH;
60039       goto abort_due_to_error;
60040     }else{
60041       pc = pOp->p2 - 1;
60042     }
60043   }else{
60044     MemSetTypeFlag(pIn1, MEM_Int);
60045   }
60046   break;
60047 }
60048
60049 #ifndef SQLITE_OMIT_FLOATING_POINT
60050 /* Opcode: RealAffinity P1 * * * *
60051 **
60052 ** If register P1 holds an integer convert it to a real value.
60053 **
60054 ** This opcode is used when extracting information from a column that
60055 ** has REAL affinity.  Such column values may still be stored as
60056 ** integers, for space efficiency, but after extraction we want them
60057 ** to have only a real value.
60058 */
60059 case OP_RealAffinity: {                  /* in1 */
60060   pIn1 = &aMem[pOp->p1];
60061   if( pIn1->flags & MEM_Int ){
60062     sqlite3VdbeMemRealify(pIn1);
60063   }
60064   break;
60065 }
60066 #endif
60067
60068 #ifndef SQLITE_OMIT_CAST
60069 /* Opcode: ToText P1 * * * *
60070 **
60071 ** Force the value in register P1 to be text.
60072 ** If the value is numeric, convert it to a string using the
60073 ** equivalent of printf().  Blob values are unchanged and
60074 ** are afterwards simply interpreted as text.
60075 **
60076 ** A NULL value is not changed by this routine.  It remains NULL.
60077 */
60078 case OP_ToText: {                  /* same as TK_TO_TEXT, in1 */
60079   pIn1 = &aMem[pOp->p1];
60080   if( pIn1->flags & MEM_Null ) break;
60081   assert( MEM_Str==(MEM_Blob>>3) );
60082   pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
60083   applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
60084   rc = ExpandBlob(pIn1);
60085   assert( pIn1->flags & MEM_Str || db->mallocFailed );
60086   pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
60087   UPDATE_MAX_BLOBSIZE(pIn1);
60088   break;
60089 }
60090
60091 /* Opcode: ToBlob P1 * * * *
60092 **
60093 ** Force the value in register P1 to be a BLOB.
60094 ** If the value is numeric, convert it to a string first.
60095 ** Strings are simply reinterpreted as blobs with no change
60096 ** to the underlying data.
60097 **
60098 ** A NULL value is not changed by this routine.  It remains NULL.
60099 */
60100 case OP_ToBlob: {                  /* same as TK_TO_BLOB, in1 */
60101   pIn1 = &aMem[pOp->p1];
60102   if( pIn1->flags & MEM_Null ) break;
60103   if( (pIn1->flags & MEM_Blob)==0 ){
60104     applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
60105     assert( pIn1->flags & MEM_Str || db->mallocFailed );
60106     MemSetTypeFlag(pIn1, MEM_Blob);
60107   }else{
60108     pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
60109   }
60110   UPDATE_MAX_BLOBSIZE(pIn1);
60111   break;
60112 }
60113
60114 /* Opcode: ToNumeric P1 * * * *
60115 **
60116 ** Force the value in register P1 to be numeric (either an
60117 ** integer or a floating-point number.)
60118 ** If the value is text or blob, try to convert it to an using the
60119 ** equivalent of atoi() or atof() and store 0 if no such conversion 
60120 ** is possible.
60121 **
60122 ** A NULL value is not changed by this routine.  It remains NULL.
60123 */
60124 case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, in1 */
60125   pIn1 = &aMem[pOp->p1];
60126   if( (pIn1->flags & (MEM_Null|MEM_Int|MEM_Real))==0 ){
60127     sqlite3VdbeMemNumerify(pIn1);
60128   }
60129   break;
60130 }
60131 #endif /* SQLITE_OMIT_CAST */
60132
60133 /* Opcode: ToInt P1 * * * *
60134 **
60135 ** Force the value in register P1 be an integer.  If
60136 ** The value is currently a real number, drop its fractional part.
60137 ** If the value is text or blob, try to convert it to an integer using the
60138 ** equivalent of atoi() and store 0 if no such conversion is possible.
60139 **
60140 ** A NULL value is not changed by this routine.  It remains NULL.
60141 */
60142 case OP_ToInt: {                  /* same as TK_TO_INT, in1 */
60143   pIn1 = &aMem[pOp->p1];
60144   if( (pIn1->flags & MEM_Null)==0 ){
60145     sqlite3VdbeMemIntegerify(pIn1);
60146   }
60147   break;
60148 }
60149
60150 #if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT)
60151 /* Opcode: ToReal P1 * * * *
60152 **
60153 ** Force the value in register P1 to be a floating point number.
60154 ** If The value is currently an integer, convert it.
60155 ** If the value is text or blob, try to convert it to an integer using the
60156 ** equivalent of atoi() and store 0.0 if no such conversion is possible.
60157 **
60158 ** A NULL value is not changed by this routine.  It remains NULL.
60159 */
60160 case OP_ToReal: {                  /* same as TK_TO_REAL, in1 */
60161   pIn1 = &aMem[pOp->p1];
60162   if( (pIn1->flags & MEM_Null)==0 ){
60163     sqlite3VdbeMemRealify(pIn1);
60164   }
60165   break;
60166 }
60167 #endif /* !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) */
60168
60169 /* Opcode: Lt P1 P2 P3 P4 P5
60170 **
60171 ** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
60172 ** jump to address P2.  
60173 **
60174 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
60175 ** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL 
60176 ** bit is clear then fall thru if either operand is NULL.
60177 **
60178 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
60179 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made 
60180 ** to coerce both inputs according to this affinity before the
60181 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
60182 ** affinity is used. Note that the affinity conversions are stored
60183 ** back into the input registers P1 and P3.  So this opcode can cause
60184 ** persistent changes to registers P1 and P3.
60185 **
60186 ** Once any conversions have taken place, and neither value is NULL, 
60187 ** the values are compared. If both values are blobs then memcmp() is
60188 ** used to determine the results of the comparison.  If both values
60189 ** are text, then the appropriate collating function specified in
60190 ** P4 is  used to do the comparison.  If P4 is not specified then
60191 ** memcmp() is used to compare text string.  If both values are
60192 ** numeric, then a numeric comparison is used. If the two values
60193 ** are of different types, then numbers are considered less than
60194 ** strings and strings are considered less than blobs.
60195 **
60196 ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
60197 ** store a boolean result (either 0, or 1, or NULL) in register P2.
60198 */
60199 /* Opcode: Ne P1 P2 P3 P4 P5
60200 **
60201 ** This works just like the Lt opcode except that the jump is taken if
60202 ** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
60203 ** additional information.
60204 **
60205 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
60206 ** true or false and is never NULL.  If both operands are NULL then the result
60207 ** of comparison is false.  If either operand is NULL then the result is true.
60208 ** If neither operand is NULL the the result is the same as it would be if
60209 ** the SQLITE_NULLEQ flag were omitted from P5.
60210 */
60211 /* Opcode: Eq P1 P2 P3 P4 P5
60212 **
60213 ** This works just like the Lt opcode except that the jump is taken if
60214 ** the operands in registers P1 and P3 are equal.
60215 ** See the Lt opcode for additional information.
60216 **
60217 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
60218 ** true or false and is never NULL.  If both operands are NULL then the result
60219 ** of comparison is true.  If either operand is NULL then the result is false.
60220 ** If neither operand is NULL the the result is the same as it would be if
60221 ** the SQLITE_NULLEQ flag were omitted from P5.
60222 */
60223 /* Opcode: Le P1 P2 P3 P4 P5
60224 **
60225 ** This works just like the Lt opcode except that the jump is taken if
60226 ** the content of register P3 is less than or equal to the content of
60227 ** register P1.  See the Lt opcode for additional information.
60228 */
60229 /* Opcode: Gt P1 P2 P3 P4 P5
60230 **
60231 ** This works just like the Lt opcode except that the jump is taken if
60232 ** the content of register P3 is greater than the content of
60233 ** register P1.  See the Lt opcode for additional information.
60234 */
60235 /* Opcode: Ge P1 P2 P3 P4 P5
60236 **
60237 ** This works just like the Lt opcode except that the jump is taken if
60238 ** the content of register P3 is greater than or equal to the content of
60239 ** register P1.  See the Lt opcode for additional information.
60240 */
60241 case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
60242 case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
60243 case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
60244 case OP_Le:               /* same as TK_LE, jump, in1, in3 */
60245 case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
60246 case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
60247 #if 0  /* local variables moved into u.ai */
60248   int res;            /* Result of the comparison of pIn1 against pIn3 */
60249   char affinity;      /* Affinity to use for comparison */
60250   u16 flags1;         /* Copy of initial value of pIn1->flags */
60251   u16 flags3;         /* Copy of initial value of pIn3->flags */
60252 #endif /* local variables moved into u.ai */
60253
60254   pIn1 = &aMem[pOp->p1];
60255   pIn3 = &aMem[pOp->p3];
60256   u.ai.flags1 = pIn1->flags;
60257   u.ai.flags3 = pIn3->flags;
60258   if( (pIn1->flags | pIn3->flags)&MEM_Null ){
60259     /* One or both operands are NULL */
60260     if( pOp->p5 & SQLITE_NULLEQ ){
60261       /* If SQLITE_NULLEQ is set (which will only happen if the operator is
60262       ** OP_Eq or OP_Ne) then take the jump or not depending on whether
60263       ** or not both operands are null.
60264       */
60265       assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
60266       u.ai.res = (pIn1->flags & pIn3->flags & MEM_Null)==0;
60267     }else{
60268       /* SQLITE_NULLEQ is clear and at least one operand is NULL,
60269       ** then the result is always NULL.
60270       ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
60271       */
60272       if( pOp->p5 & SQLITE_STOREP2 ){
60273         pOut = &aMem[pOp->p2];
60274         MemSetTypeFlag(pOut, MEM_Null);
60275         REGISTER_TRACE(pOp->p2, pOut);
60276       }else if( pOp->p5 & SQLITE_JUMPIFNULL ){
60277         pc = pOp->p2-1;
60278       }
60279       break;
60280     }
60281   }else{
60282     /* Neither operand is NULL.  Do a comparison. */
60283     u.ai.affinity = pOp->p5 & SQLITE_AFF_MASK;
60284     if( u.ai.affinity ){
60285       applyAffinity(pIn1, u.ai.affinity, encoding);
60286       applyAffinity(pIn3, u.ai.affinity, encoding);
60287       if( db->mallocFailed ) goto no_mem;
60288     }
60289
60290     assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
60291     ExpandBlob(pIn1);
60292     ExpandBlob(pIn3);
60293     u.ai.res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
60294   }
60295   switch( pOp->opcode ){
60296     case OP_Eq:    u.ai.res = u.ai.res==0;     break;
60297     case OP_Ne:    u.ai.res = u.ai.res!=0;     break;
60298     case OP_Lt:    u.ai.res = u.ai.res<0;      break;
60299     case OP_Le:    u.ai.res = u.ai.res<=0;     break;
60300     case OP_Gt:    u.ai.res = u.ai.res>0;      break;
60301     default:       u.ai.res = u.ai.res>=0;     break;
60302   }
60303
60304   if( pOp->p5 & SQLITE_STOREP2 ){
60305     pOut = &aMem[pOp->p2];
60306     MemSetTypeFlag(pOut, MEM_Int);
60307     pOut->u.i = u.ai.res;
60308     REGISTER_TRACE(pOp->p2, pOut);
60309   }else if( u.ai.res ){
60310     pc = pOp->p2-1;
60311   }
60312
60313   /* Undo any changes made by applyAffinity() to the input registers. */
60314   pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (u.ai.flags1&MEM_TypeMask);
60315   pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (u.ai.flags3&MEM_TypeMask);
60316   break;
60317 }
60318
60319 /* Opcode: Permutation * * * P4 *
60320 **
60321 ** Set the permutation used by the OP_Compare operator to be the array
60322 ** of integers in P4.
60323 **
60324 ** The permutation is only valid until the next OP_Permutation, OP_Compare,
60325 ** OP_Halt, or OP_ResultRow.  Typically the OP_Permutation should occur
60326 ** immediately prior to the OP_Compare.
60327 */
60328 case OP_Permutation: {
60329   assert( pOp->p4type==P4_INTARRAY );
60330   assert( pOp->p4.ai );
60331   aPermute = pOp->p4.ai;
60332   break;
60333 }
60334
60335 /* Opcode: Compare P1 P2 P3 P4 *
60336 **
60337 ** Compare to vectors of registers in reg(P1)..reg(P1+P3-1) (all this
60338 ** one "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
60339 ** the comparison for use by the next OP_Jump instruct.
60340 **
60341 ** P4 is a KeyInfo structure that defines collating sequences and sort
60342 ** orders for the comparison.  The permutation applies to registers
60343 ** only.  The KeyInfo elements are used sequentially.
60344 **
60345 ** The comparison is a sort comparison, so NULLs compare equal,
60346 ** NULLs are less than numbers, numbers are less than strings,
60347 ** and strings are less than blobs.
60348 */
60349 case OP_Compare: {
60350 #if 0  /* local variables moved into u.aj */
60351   int n;
60352   int i;
60353   int p1;
60354   int p2;
60355   const KeyInfo *pKeyInfo;
60356   int idx;
60357   CollSeq *pColl;    /* Collating sequence to use on this term */
60358   int bRev;          /* True for DESCENDING sort order */
60359 #endif /* local variables moved into u.aj */
60360
60361   u.aj.n = pOp->p3;
60362   u.aj.pKeyInfo = pOp->p4.pKeyInfo;
60363   assert( u.aj.n>0 );
60364   assert( u.aj.pKeyInfo!=0 );
60365   u.aj.p1 = pOp->p1;
60366   u.aj.p2 = pOp->p2;
60367 #if SQLITE_DEBUG
60368   if( aPermute ){
60369     int k, mx = 0;
60370     for(k=0; k<u.aj.n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
60371     assert( u.aj.p1>0 && u.aj.p1+mx<=p->nMem+1 );
60372     assert( u.aj.p2>0 && u.aj.p2+mx<=p->nMem+1 );
60373   }else{
60374     assert( u.aj.p1>0 && u.aj.p1+u.aj.n<=p->nMem+1 );
60375     assert( u.aj.p2>0 && u.aj.p2+u.aj.n<=p->nMem+1 );
60376   }
60377 #endif /* SQLITE_DEBUG */
60378   for(u.aj.i=0; u.aj.i<u.aj.n; u.aj.i++){
60379     u.aj.idx = aPermute ? aPermute[u.aj.i] : u.aj.i;
60380     REGISTER_TRACE(u.aj.p1+u.aj.idx, &aMem[u.aj.p1+u.aj.idx]);
60381     REGISTER_TRACE(u.aj.p2+u.aj.idx, &aMem[u.aj.p2+u.aj.idx]);
60382     assert( u.aj.i<u.aj.pKeyInfo->nField );
60383     u.aj.pColl = u.aj.pKeyInfo->aColl[u.aj.i];
60384     u.aj.bRev = u.aj.pKeyInfo->aSortOrder[u.aj.i];
60385     iCompare = sqlite3MemCompare(&aMem[u.aj.p1+u.aj.idx], &aMem[u.aj.p2+u.aj.idx], u.aj.pColl);
60386     if( iCompare ){
60387       if( u.aj.bRev ) iCompare = -iCompare;
60388       break;
60389     }
60390   }
60391   aPermute = 0;
60392   break;
60393 }
60394
60395 /* Opcode: Jump P1 P2 P3 * *
60396 **
60397 ** Jump to the instruction at address P1, P2, or P3 depending on whether
60398 ** in the most recent OP_Compare instruction the P1 vector was less than
60399 ** equal to, or greater than the P2 vector, respectively.
60400 */
60401 case OP_Jump: {             /* jump */
60402   if( iCompare<0 ){
60403     pc = pOp->p1 - 1;
60404   }else if( iCompare==0 ){
60405     pc = pOp->p2 - 1;
60406   }else{
60407     pc = pOp->p3 - 1;
60408   }
60409   break;
60410 }
60411
60412 /* Opcode: And P1 P2 P3 * *
60413 **
60414 ** Take the logical AND of the values in registers P1 and P2 and
60415 ** write the result into register P3.
60416 **
60417 ** If either P1 or P2 is 0 (false) then the result is 0 even if
60418 ** the other input is NULL.  A NULL and true or two NULLs give
60419 ** a NULL output.
60420 */
60421 /* Opcode: Or P1 P2 P3 * *
60422 **
60423 ** Take the logical OR of the values in register P1 and P2 and
60424 ** store the answer in register P3.
60425 **
60426 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
60427 ** even if the other input is NULL.  A NULL and false or two NULLs
60428 ** give a NULL output.
60429 */
60430 case OP_And:              /* same as TK_AND, in1, in2, out3 */
60431 case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
60432 #if 0  /* local variables moved into u.ak */
60433   int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
60434   int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
60435 #endif /* local variables moved into u.ak */
60436
60437   pIn1 = &aMem[pOp->p1];
60438   if( pIn1->flags & MEM_Null ){
60439     u.ak.v1 = 2;
60440   }else{
60441     u.ak.v1 = sqlite3VdbeIntValue(pIn1)!=0;
60442   }
60443   pIn2 = &aMem[pOp->p2];
60444   if( pIn2->flags & MEM_Null ){
60445     u.ak.v2 = 2;
60446   }else{
60447     u.ak.v2 = sqlite3VdbeIntValue(pIn2)!=0;
60448   }
60449   if( pOp->opcode==OP_And ){
60450     static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
60451     u.ak.v1 = and_logic[u.ak.v1*3+u.ak.v2];
60452   }else{
60453     static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
60454     u.ak.v1 = or_logic[u.ak.v1*3+u.ak.v2];
60455   }
60456   pOut = &aMem[pOp->p3];
60457   if( u.ak.v1==2 ){
60458     MemSetTypeFlag(pOut, MEM_Null);
60459   }else{
60460     pOut->u.i = u.ak.v1;
60461     MemSetTypeFlag(pOut, MEM_Int);
60462   }
60463   break;
60464 }
60465
60466 /* Opcode: Not P1 P2 * * *
60467 **
60468 ** Interpret the value in register P1 as a boolean value.  Store the
60469 ** boolean complement in register P2.  If the value in register P1 is 
60470 ** NULL, then a NULL is stored in P2.
60471 */
60472 case OP_Not: {                /* same as TK_NOT, in1, out2 */
60473   pIn1 = &aMem[pOp->p1];
60474   pOut = &aMem[pOp->p2];
60475   if( pIn1->flags & MEM_Null ){
60476     sqlite3VdbeMemSetNull(pOut);
60477   }else{
60478     sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
60479   }
60480   break;
60481 }
60482
60483 /* Opcode: BitNot P1 P2 * * *
60484 **
60485 ** Interpret the content of register P1 as an integer.  Store the
60486 ** ones-complement of the P1 value into register P2.  If P1 holds
60487 ** a NULL then store a NULL in P2.
60488 */
60489 case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
60490   pIn1 = &aMem[pOp->p1];
60491   pOut = &aMem[pOp->p2];
60492   if( pIn1->flags & MEM_Null ){
60493     sqlite3VdbeMemSetNull(pOut);
60494   }else{
60495     sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
60496   }
60497   break;
60498 }
60499
60500 /* Opcode: If P1 P2 P3 * *
60501 **
60502 ** Jump to P2 if the value in register P1 is true.  The value is
60503 ** is considered true if it is numeric and non-zero.  If the value
60504 ** in P1 is NULL then take the jump if P3 is true.
60505 */
60506 /* Opcode: IfNot P1 P2 P3 * *
60507 **
60508 ** Jump to P2 if the value in register P1 is False.  The value is
60509 ** is considered true if it has a numeric value of zero.  If the value
60510 ** in P1 is NULL then take the jump if P3 is true.
60511 */
60512 case OP_If:                 /* jump, in1 */
60513 case OP_IfNot: {            /* jump, in1 */
60514 #if 0  /* local variables moved into u.al */
60515   int c;
60516 #endif /* local variables moved into u.al */
60517   pIn1 = &aMem[pOp->p1];
60518   if( pIn1->flags & MEM_Null ){
60519     u.al.c = pOp->p3;
60520   }else{
60521 #ifdef SQLITE_OMIT_FLOATING_POINT
60522     u.al.c = sqlite3VdbeIntValue(pIn1)!=0;
60523 #else
60524     u.al.c = sqlite3VdbeRealValue(pIn1)!=0.0;
60525 #endif
60526     if( pOp->opcode==OP_IfNot ) u.al.c = !u.al.c;
60527   }
60528   if( u.al.c ){
60529     pc = pOp->p2-1;
60530   }
60531   break;
60532 }
60533
60534 /* Opcode: IsNull P1 P2 * * *
60535 **
60536 ** Jump to P2 if the value in register P1 is NULL.
60537 */
60538 case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
60539   pIn1 = &aMem[pOp->p1];
60540   if( (pIn1->flags & MEM_Null)!=0 ){
60541     pc = pOp->p2 - 1;
60542   }
60543   break;
60544 }
60545
60546 /* Opcode: NotNull P1 P2 * * *
60547 **
60548 ** Jump to P2 if the value in register P1 is not NULL.  
60549 */
60550 case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
60551   pIn1 = &aMem[pOp->p1];
60552   if( (pIn1->flags & MEM_Null)==0 ){
60553     pc = pOp->p2 - 1;
60554   }
60555   break;
60556 }
60557
60558 /* Opcode: Column P1 P2 P3 P4 P5
60559 **
60560 ** Interpret the data that cursor P1 points to as a structure built using
60561 ** the MakeRecord instruction.  (See the MakeRecord opcode for additional
60562 ** information about the format of the data.)  Extract the P2-th column
60563 ** from this record.  If there are less that (P2+1) 
60564 ** values in the record, extract a NULL.
60565 **
60566 ** The value extracted is stored in register P3.
60567 **
60568 ** If the column contains fewer than P2 fields, then extract a NULL.  Or,
60569 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
60570 ** the result.
60571 **
60572 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
60573 ** then the cache of the cursor is reset prior to extracting the column.
60574 ** The first OP_Column against a pseudo-table after the value of the content
60575 ** register has changed should have this bit set.
60576 */
60577 case OP_Column: {
60578 #if 0  /* local variables moved into u.am */
60579   u32 payloadSize;   /* Number of bytes in the record */
60580   i64 payloadSize64; /* Number of bytes in the record */
60581   int p1;            /* P1 value of the opcode */
60582   int p2;            /* column number to retrieve */
60583   VdbeCursor *pC;    /* The VDBE cursor */
60584   char *zRec;        /* Pointer to complete record-data */
60585   BtCursor *pCrsr;   /* The BTree cursor */
60586   u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
60587   u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
60588   int nField;        /* number of fields in the record */
60589   int len;           /* The length of the serialized data for the column */
60590   int i;             /* Loop counter */
60591   char *zData;       /* Part of the record being decoded */
60592   Mem *pDest;        /* Where to write the extracted value */
60593   Mem sMem;          /* For storing the record being decoded */
60594   u8 *zIdx;          /* Index into header */
60595   u8 *zEndHdr;       /* Pointer to first byte after the header */
60596   u32 offset;        /* Offset into the data */
60597   u32 szField;       /* Number of bytes in the content of a field */
60598   int szHdr;         /* Size of the header size field at start of record */
60599   int avail;         /* Number of bytes of available data */
60600   Mem *pReg;         /* PseudoTable input register */
60601 #endif /* local variables moved into u.am */
60602
60603
60604   u.am.p1 = pOp->p1;
60605   u.am.p2 = pOp->p2;
60606   u.am.pC = 0;
60607   memset(&u.am.sMem, 0, sizeof(u.am.sMem));
60608   assert( u.am.p1<p->nCursor );
60609   assert( pOp->p3>0 && pOp->p3<=p->nMem );
60610   u.am.pDest = &aMem[pOp->p3];
60611   MemSetTypeFlag(u.am.pDest, MEM_Null);
60612   u.am.zRec = 0;
60613
60614   /* This block sets the variable u.am.payloadSize to be the total number of
60615   ** bytes in the record.
60616   **
60617   ** u.am.zRec is set to be the complete text of the record if it is available.
60618   ** The complete record text is always available for pseudo-tables
60619   ** If the record is stored in a cursor, the complete record text
60620   ** might be available in the  u.am.pC->aRow cache.  Or it might not be.
60621   ** If the data is unavailable,  u.am.zRec is set to NULL.
60622   **
60623   ** We also compute the number of columns in the record.  For cursors,
60624   ** the number of columns is stored in the VdbeCursor.nField element.
60625   */
60626   u.am.pC = p->apCsr[u.am.p1];
60627   assert( u.am.pC!=0 );
60628 #ifndef SQLITE_OMIT_VIRTUALTABLE
60629   assert( u.am.pC->pVtabCursor==0 );
60630 #endif
60631   u.am.pCrsr = u.am.pC->pCursor;
60632   if( u.am.pCrsr!=0 ){
60633     /* The record is stored in a B-Tree */
60634     rc = sqlite3VdbeCursorMoveto(u.am.pC);
60635     if( rc ) goto abort_due_to_error;
60636     if( u.am.pC->nullRow ){
60637       u.am.payloadSize = 0;
60638     }else if( u.am.pC->cacheStatus==p->cacheCtr ){
60639       u.am.payloadSize = u.am.pC->payloadSize;
60640       u.am.zRec = (char*)u.am.pC->aRow;
60641     }else if( u.am.pC->isIndex ){
60642       assert( sqlite3BtreeCursorIsValid(u.am.pCrsr) );
60643       rc = sqlite3BtreeKeySize(u.am.pCrsr, &u.am.payloadSize64);
60644       assert( rc==SQLITE_OK );   /* True because of CursorMoveto() call above */
60645       /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
60646       ** payload size, so it is impossible for u.am.payloadSize64 to be
60647       ** larger than 32 bits. */
60648       assert( (u.am.payloadSize64 & SQLITE_MAX_U32)==(u64)u.am.payloadSize64 );
60649       u.am.payloadSize = (u32)u.am.payloadSize64;
60650     }else{
60651       assert( sqlite3BtreeCursorIsValid(u.am.pCrsr) );
60652       rc = sqlite3BtreeDataSize(u.am.pCrsr, &u.am.payloadSize);
60653       assert( rc==SQLITE_OK );   /* DataSize() cannot fail */
60654     }
60655   }else if( u.am.pC->pseudoTableReg>0 ){
60656     u.am.pReg = &aMem[u.am.pC->pseudoTableReg];
60657     assert( u.am.pReg->flags & MEM_Blob );
60658     u.am.payloadSize = u.am.pReg->n;
60659     u.am.zRec = u.am.pReg->z;
60660     u.am.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;
60661     assert( u.am.payloadSize==0 || u.am.zRec!=0 );
60662   }else{
60663     /* Consider the row to be NULL */
60664     u.am.payloadSize = 0;
60665   }
60666
60667   /* If u.am.payloadSize is 0, then just store a NULL */
60668   if( u.am.payloadSize==0 ){
60669     assert( u.am.pDest->flags&MEM_Null );
60670     goto op_column_out;
60671   }
60672   assert( db->aLimit[SQLITE_LIMIT_LENGTH]>=0 );
60673   if( u.am.payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
60674     goto too_big;
60675   }
60676
60677   u.am.nField = u.am.pC->nField;
60678   assert( u.am.p2<u.am.nField );
60679
60680   /* Read and parse the table header.  Store the results of the parse
60681   ** into the record header cache fields of the cursor.
60682   */
60683   u.am.aType = u.am.pC->aType;
60684   if( u.am.pC->cacheStatus==p->cacheCtr ){
60685     u.am.aOffset = u.am.pC->aOffset;
60686   }else{
60687     assert(u.am.aType);
60688     u.am.avail = 0;
60689     u.am.pC->aOffset = u.am.aOffset = &u.am.aType[u.am.nField];
60690     u.am.pC->payloadSize = u.am.payloadSize;
60691     u.am.pC->cacheStatus = p->cacheCtr;
60692
60693     /* Figure out how many bytes are in the header */
60694     if( u.am.zRec ){
60695       u.am.zData = u.am.zRec;
60696     }else{
60697       if( u.am.pC->isIndex ){
60698         u.am.zData = (char*)sqlite3BtreeKeyFetch(u.am.pCrsr, &u.am.avail);
60699       }else{
60700         u.am.zData = (char*)sqlite3BtreeDataFetch(u.am.pCrsr, &u.am.avail);
60701       }
60702       /* If KeyFetch()/DataFetch() managed to get the entire payload,
60703       ** save the payload in the u.am.pC->aRow cache.  That will save us from
60704       ** having to make additional calls to fetch the content portion of
60705       ** the record.
60706       */
60707       assert( u.am.avail>=0 );
60708       if( u.am.payloadSize <= (u32)u.am.avail ){
60709         u.am.zRec = u.am.zData;
60710         u.am.pC->aRow = (u8*)u.am.zData;
60711       }else{
60712         u.am.pC->aRow = 0;
60713       }
60714     }
60715     /* The following assert is true in all cases accept when
60716     ** the database file has been corrupted externally.
60717     **    assert( u.am.zRec!=0 || u.am.avail>=u.am.payloadSize || u.am.avail>=9 ); */
60718     u.am.szHdr = getVarint32((u8*)u.am.zData, u.am.offset);
60719
60720     /* Make sure a corrupt database has not given us an oversize header.
60721     ** Do this now to avoid an oversize memory allocation.
60722     **
60723     ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
60724     ** types use so much data space that there can only be 4096 and 32 of
60725     ** them, respectively.  So the maximum header length results from a
60726     ** 3-byte type for each of the maximum of 32768 columns plus three
60727     ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
60728     */
60729     if( u.am.offset > 98307 ){
60730       rc = SQLITE_CORRUPT_BKPT;
60731       goto op_column_out;
60732     }
60733
60734     /* Compute in u.am.len the number of bytes of data we need to read in order
60735     ** to get u.am.nField type values.  u.am.offset is an upper bound on this.  But
60736     ** u.am.nField might be significantly less than the true number of columns
60737     ** in the table, and in that case, 5*u.am.nField+3 might be smaller than u.am.offset.
60738     ** We want to minimize u.am.len in order to limit the size of the memory
60739     ** allocation, especially if a corrupt database file has caused u.am.offset
60740     ** to be oversized. Offset is limited to 98307 above.  But 98307 might
60741     ** still exceed Robson memory allocation limits on some configurations.
60742     ** On systems that cannot tolerate large memory allocations, u.am.nField*5+3
60743     ** will likely be much smaller since u.am.nField will likely be less than
60744     ** 20 or so.  This insures that Robson memory allocation limits are
60745     ** not exceeded even for corrupt database files.
60746     */
60747     u.am.len = u.am.nField*5 + 3;
60748     if( u.am.len > (int)u.am.offset ) u.am.len = (int)u.am.offset;
60749
60750     /* The KeyFetch() or DataFetch() above are fast and will get the entire
60751     ** record header in most cases.  But they will fail to get the complete
60752     ** record header if the record header does not fit on a single page
60753     ** in the B-Tree.  When that happens, use sqlite3VdbeMemFromBtree() to
60754     ** acquire the complete header text.
60755     */
60756     if( !u.am.zRec && u.am.avail<u.am.len ){
60757       u.am.sMem.flags = 0;
60758       u.am.sMem.db = 0;
60759       rc = sqlite3VdbeMemFromBtree(u.am.pCrsr, 0, u.am.len, u.am.pC->isIndex, &u.am.sMem);
60760       if( rc!=SQLITE_OK ){
60761         goto op_column_out;
60762       }
60763       u.am.zData = u.am.sMem.z;
60764     }
60765     u.am.zEndHdr = (u8 *)&u.am.zData[u.am.len];
60766     u.am.zIdx = (u8 *)&u.am.zData[u.am.szHdr];
60767
60768     /* Scan the header and use it to fill in the u.am.aType[] and u.am.aOffset[]
60769     ** arrays.  u.am.aType[u.am.i] will contain the type integer for the u.am.i-th
60770     ** column and u.am.aOffset[u.am.i] will contain the u.am.offset from the beginning
60771     ** of the record to the start of the data for the u.am.i-th column
60772     */
60773     for(u.am.i=0; u.am.i<u.am.nField; u.am.i++){
60774       if( u.am.zIdx<u.am.zEndHdr ){
60775         u.am.aOffset[u.am.i] = u.am.offset;
60776         u.am.zIdx += getVarint32(u.am.zIdx, u.am.aType[u.am.i]);
60777         u.am.szField = sqlite3VdbeSerialTypeLen(u.am.aType[u.am.i]);
60778         u.am.offset += u.am.szField;
60779         if( u.am.offset<u.am.szField ){  /* True if u.am.offset overflows */
60780           u.am.zIdx = &u.am.zEndHdr[1];  /* Forces SQLITE_CORRUPT return below */
60781           break;
60782         }
60783       }else{
60784         /* If u.am.i is less that u.am.nField, then there are less fields in this
60785         ** record than SetNumColumns indicated there are columns in the
60786         ** table. Set the u.am.offset for any extra columns not present in
60787         ** the record to 0. This tells code below to store a NULL
60788         ** instead of deserializing a value from the record.
60789         */
60790         u.am.aOffset[u.am.i] = 0;
60791       }
60792     }
60793     sqlite3VdbeMemRelease(&u.am.sMem);
60794     u.am.sMem.flags = MEM_Null;
60795
60796     /* If we have read more header data than was contained in the header,
60797     ** or if the end of the last field appears to be past the end of the
60798     ** record, or if the end of the last field appears to be before the end
60799     ** of the record (when all fields present), then we must be dealing
60800     ** with a corrupt database.
60801     */
60802     if( (u.am.zIdx > u.am.zEndHdr) || (u.am.offset > u.am.payloadSize)
60803          || (u.am.zIdx==u.am.zEndHdr && u.am.offset!=u.am.payloadSize) ){
60804       rc = SQLITE_CORRUPT_BKPT;
60805       goto op_column_out;
60806     }
60807   }
60808
60809   /* Get the column information. If u.am.aOffset[u.am.p2] is non-zero, then
60810   ** deserialize the value from the record. If u.am.aOffset[u.am.p2] is zero,
60811   ** then there are not enough fields in the record to satisfy the
60812   ** request.  In this case, set the value NULL or to P4 if P4 is
60813   ** a pointer to a Mem object.
60814   */
60815   if( u.am.aOffset[u.am.p2] ){
60816     assert( rc==SQLITE_OK );
60817     if( u.am.zRec ){
60818       sqlite3VdbeMemReleaseExternal(u.am.pDest);
60819       sqlite3VdbeSerialGet((u8 *)&u.am.zRec[u.am.aOffset[u.am.p2]], u.am.aType[u.am.p2], u.am.pDest);
60820     }else{
60821       u.am.len = sqlite3VdbeSerialTypeLen(u.am.aType[u.am.p2]);
60822       sqlite3VdbeMemMove(&u.am.sMem, u.am.pDest);
60823       rc = sqlite3VdbeMemFromBtree(u.am.pCrsr, u.am.aOffset[u.am.p2], u.am.len, u.am.pC->isIndex, &u.am.sMem);
60824       if( rc!=SQLITE_OK ){
60825         goto op_column_out;
60826       }
60827       u.am.zData = u.am.sMem.z;
60828       sqlite3VdbeSerialGet((u8*)u.am.zData, u.am.aType[u.am.p2], u.am.pDest);
60829     }
60830     u.am.pDest->enc = encoding;
60831   }else{
60832     if( pOp->p4type==P4_MEM ){
60833       sqlite3VdbeMemShallowCopy(u.am.pDest, pOp->p4.pMem, MEM_Static);
60834     }else{
60835       assert( u.am.pDest->flags&MEM_Null );
60836     }
60837   }
60838
60839   /* If we dynamically allocated space to hold the data (in the
60840   ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
60841   ** dynamically allocated space over to the u.am.pDest structure.
60842   ** This prevents a memory copy.
60843   */
60844   if( u.am.sMem.zMalloc ){
60845     assert( u.am.sMem.z==u.am.sMem.zMalloc );
60846     assert( !(u.am.pDest->flags & MEM_Dyn) );
60847     assert( !(u.am.pDest->flags & (MEM_Blob|MEM_Str)) || u.am.pDest->z==u.am.sMem.z );
60848     u.am.pDest->flags &= ~(MEM_Ephem|MEM_Static);
60849     u.am.pDest->flags |= MEM_Term;
60850     u.am.pDest->z = u.am.sMem.z;
60851     u.am.pDest->zMalloc = u.am.sMem.zMalloc;
60852   }
60853
60854   rc = sqlite3VdbeMemMakeWriteable(u.am.pDest);
60855
60856 op_column_out:
60857   UPDATE_MAX_BLOBSIZE(u.am.pDest);
60858   REGISTER_TRACE(pOp->p3, u.am.pDest);
60859   break;
60860 }
60861
60862 /* Opcode: Affinity P1 P2 * P4 *
60863 **
60864 ** Apply affinities to a range of P2 registers starting with P1.
60865 **
60866 ** P4 is a string that is P2 characters long. The nth character of the
60867 ** string indicates the column affinity that should be used for the nth
60868 ** memory cell in the range.
60869 */
60870 case OP_Affinity: {
60871 #if 0  /* local variables moved into u.an */
60872   const char *zAffinity;   /* The affinity to be applied */
60873   char cAff;               /* A single character of affinity */
60874 #endif /* local variables moved into u.an */
60875
60876   u.an.zAffinity = pOp->p4.z;
60877   assert( u.an.zAffinity!=0 );
60878   assert( u.an.zAffinity[pOp->p2]==0 );
60879   pIn1 = &aMem[pOp->p1];
60880   while( (u.an.cAff = *(u.an.zAffinity++))!=0 ){
60881     assert( pIn1 <= &p->aMem[p->nMem] );
60882     ExpandBlob(pIn1);
60883     applyAffinity(pIn1, u.an.cAff, encoding);
60884     pIn1++;
60885   }
60886   break;
60887 }
60888
60889 /* Opcode: MakeRecord P1 P2 P3 P4 *
60890 **
60891 ** Convert P2 registers beginning with P1 into a single entry
60892 ** suitable for use as a data record in a database table or as a key
60893 ** in an index.  The details of the format are irrelevant as long as
60894 ** the OP_Column opcode can decode the record later.
60895 ** Refer to source code comments for the details of the record
60896 ** format.
60897 **
60898 ** P4 may be a string that is P2 characters long.  The nth character of the
60899 ** string indicates the column affinity that should be used for the nth
60900 ** field of the index key.
60901 **
60902 ** The mapping from character to affinity is given by the SQLITE_AFF_
60903 ** macros defined in sqliteInt.h.
60904 **
60905 ** If P4 is NULL then all index fields have the affinity NONE.
60906 */
60907 case OP_MakeRecord: {
60908 #if 0  /* local variables moved into u.ao */
60909   u8 *zNewRecord;        /* A buffer to hold the data for the new record */
60910   Mem *pRec;             /* The new record */
60911   u64 nData;             /* Number of bytes of data space */
60912   int nHdr;              /* Number of bytes of header space */
60913   i64 nByte;             /* Data space required for this record */
60914   int nZero;             /* Number of zero bytes at the end of the record */
60915   int nVarint;           /* Number of bytes in a varint */
60916   u32 serial_type;       /* Type field */
60917   Mem *pData0;           /* First field to be combined into the record */
60918   Mem *pLast;            /* Last field of the record */
60919   int nField;            /* Number of fields in the record */
60920   char *zAffinity;       /* The affinity string for the record */
60921   int file_format;       /* File format to use for encoding */
60922   int i;                 /* Space used in zNewRecord[] */
60923   int len;               /* Length of a field */
60924 #endif /* local variables moved into u.ao */
60925
60926   /* Assuming the record contains N fields, the record format looks
60927   ** like this:
60928   **
60929   ** ------------------------------------------------------------------------
60930   ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
60931   ** ------------------------------------------------------------------------
60932   **
60933   ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
60934   ** and so froth.
60935   **
60936   ** Each type field is a varint representing the serial type of the
60937   ** corresponding data element (see sqlite3VdbeSerialType()). The
60938   ** hdr-size field is also a varint which is the offset from the beginning
60939   ** of the record to data0.
60940   */
60941   u.ao.nData = 0;         /* Number of bytes of data space */
60942   u.ao.nHdr = 0;          /* Number of bytes of header space */
60943   u.ao.nByte = 0;         /* Data space required for this record */
60944   u.ao.nZero = 0;         /* Number of zero bytes at the end of the record */
60945   u.ao.nField = pOp->p1;
60946   u.ao.zAffinity = pOp->p4.z;
60947   assert( u.ao.nField>0 && pOp->p2>0 && pOp->p2+u.ao.nField<=p->nMem+1 );
60948   u.ao.pData0 = &aMem[u.ao.nField];
60949   u.ao.nField = pOp->p2;
60950   u.ao.pLast = &u.ao.pData0[u.ao.nField-1];
60951   u.ao.file_format = p->minWriteFileFormat;
60952
60953   /* Loop through the elements that will make up the record to figure
60954   ** out how much space is required for the new record.
60955   */
60956   for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
60957     if( u.ao.zAffinity ){
60958       applyAffinity(u.ao.pRec, u.ao.zAffinity[u.ao.pRec-u.ao.pData0], encoding);
60959     }
60960     if( u.ao.pRec->flags&MEM_Zero && u.ao.pRec->n>0 ){
60961       sqlite3VdbeMemExpandBlob(u.ao.pRec);
60962     }
60963     u.ao.serial_type = sqlite3VdbeSerialType(u.ao.pRec, u.ao.file_format);
60964     u.ao.len = sqlite3VdbeSerialTypeLen(u.ao.serial_type);
60965     u.ao.nData += u.ao.len;
60966     u.ao.nHdr += sqlite3VarintLen(u.ao.serial_type);
60967     if( u.ao.pRec->flags & MEM_Zero ){
60968       /* Only pure zero-filled BLOBs can be input to this Opcode.
60969       ** We do not allow blobs with a prefix and a zero-filled tail. */
60970       u.ao.nZero += u.ao.pRec->u.nZero;
60971     }else if( u.ao.len ){
60972       u.ao.nZero = 0;
60973     }
60974   }
60975
60976   /* Add the initial header varint and total the size */
60977   u.ao.nHdr += u.ao.nVarint = sqlite3VarintLen(u.ao.nHdr);
60978   if( u.ao.nVarint<sqlite3VarintLen(u.ao.nHdr) ){
60979     u.ao.nHdr++;
60980   }
60981   u.ao.nByte = u.ao.nHdr+u.ao.nData-u.ao.nZero;
60982   if( u.ao.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
60983     goto too_big;
60984   }
60985
60986   /* Make sure the output register has a buffer large enough to store
60987   ** the new record. The output register (pOp->p3) is not allowed to
60988   ** be one of the input registers (because the following call to
60989   ** sqlite3VdbeMemGrow() could clobber the value before it is used).
60990   */
60991   assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
60992   pOut = &aMem[pOp->p3];
60993   if( sqlite3VdbeMemGrow(pOut, (int)u.ao.nByte, 0) ){
60994     goto no_mem;
60995   }
60996   u.ao.zNewRecord = (u8 *)pOut->z;
60997
60998   /* Write the record */
60999   u.ao.i = putVarint32(u.ao.zNewRecord, u.ao.nHdr);
61000   for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
61001     u.ao.serial_type = sqlite3VdbeSerialType(u.ao.pRec, u.ao.file_format);
61002     u.ao.i += putVarint32(&u.ao.zNewRecord[u.ao.i], u.ao.serial_type);      /* serial type */
61003   }
61004   for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){  /* serial data */
61005     u.ao.i += sqlite3VdbeSerialPut(&u.ao.zNewRecord[u.ao.i], (int)(u.ao.nByte-u.ao.i), u.ao.pRec,u.ao.file_format);
61006   }
61007   assert( u.ao.i==u.ao.nByte );
61008
61009   assert( pOp->p3>0 && pOp->p3<=p->nMem );
61010   pOut->n = (int)u.ao.nByte;
61011   pOut->flags = MEM_Blob | MEM_Dyn;
61012   pOut->xDel = 0;
61013   if( u.ao.nZero ){
61014     pOut->u.nZero = u.ao.nZero;
61015     pOut->flags |= MEM_Zero;
61016   }
61017   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
61018   REGISTER_TRACE(pOp->p3, pOut);
61019   UPDATE_MAX_BLOBSIZE(pOut);
61020   break;
61021 }
61022
61023 /* Opcode: Count P1 P2 * * *
61024 **
61025 ** Store the number of entries (an integer value) in the table or index 
61026 ** opened by cursor P1 in register P2
61027 */
61028 #ifndef SQLITE_OMIT_BTREECOUNT
61029 case OP_Count: {         /* out2-prerelease */
61030 #if 0  /* local variables moved into u.ap */
61031   i64 nEntry;
61032   BtCursor *pCrsr;
61033 #endif /* local variables moved into u.ap */
61034
61035   u.ap.pCrsr = p->apCsr[pOp->p1]->pCursor;
61036   if( u.ap.pCrsr ){
61037     rc = sqlite3BtreeCount(u.ap.pCrsr, &u.ap.nEntry);
61038   }else{
61039     u.ap.nEntry = 0;
61040   }
61041   pOut->u.i = u.ap.nEntry;
61042   break;
61043 }
61044 #endif
61045
61046 /* Opcode: Savepoint P1 * * P4 *
61047 **
61048 ** Open, release or rollback the savepoint named by parameter P4, depending
61049 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
61050 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
61051 */
61052 case OP_Savepoint: {
61053 #if 0  /* local variables moved into u.aq */
61054   int p1;                         /* Value of P1 operand */
61055   char *zName;                    /* Name of savepoint */
61056   int nName;
61057   Savepoint *pNew;
61058   Savepoint *pSavepoint;
61059   Savepoint *pTmp;
61060   int iSavepoint;
61061   int ii;
61062 #endif /* local variables moved into u.aq */
61063
61064   u.aq.p1 = pOp->p1;
61065   u.aq.zName = pOp->p4.z;
61066
61067   /* Assert that the u.aq.p1 parameter is valid. Also that if there is no open
61068   ** transaction, then there cannot be any savepoints.
61069   */
61070   assert( db->pSavepoint==0 || db->autoCommit==0 );
61071   assert( u.aq.p1==SAVEPOINT_BEGIN||u.aq.p1==SAVEPOINT_RELEASE||u.aq.p1==SAVEPOINT_ROLLBACK );
61072   assert( db->pSavepoint || db->isTransactionSavepoint==0 );
61073   assert( checkSavepointCount(db) );
61074
61075   if( u.aq.p1==SAVEPOINT_BEGIN ){
61076     if( db->writeVdbeCnt>0 ){
61077       /* A new savepoint cannot be created if there are active write
61078       ** statements (i.e. open read/write incremental blob handles).
61079       */
61080       sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
61081         "SQL statements in progress");
61082       rc = SQLITE_BUSY;
61083     }else{
61084       u.aq.nName = sqlite3Strlen30(u.aq.zName);
61085
61086       /* Create a new savepoint structure. */
61087       u.aq.pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+u.aq.nName+1);
61088       if( u.aq.pNew ){
61089         u.aq.pNew->zName = (char *)&u.aq.pNew[1];
61090         memcpy(u.aq.pNew->zName, u.aq.zName, u.aq.nName+1);
61091
61092         /* If there is no open transaction, then mark this as a special
61093         ** "transaction savepoint". */
61094         if( db->autoCommit ){
61095           db->autoCommit = 0;
61096           db->isTransactionSavepoint = 1;
61097         }else{
61098           db->nSavepoint++;
61099         }
61100
61101         /* Link the new savepoint into the database handle's list. */
61102         u.aq.pNew->pNext = db->pSavepoint;
61103         db->pSavepoint = u.aq.pNew;
61104         u.aq.pNew->nDeferredCons = db->nDeferredCons;
61105       }
61106     }
61107   }else{
61108     u.aq.iSavepoint = 0;
61109
61110     /* Find the named savepoint. If there is no such savepoint, then an
61111     ** an error is returned to the user.  */
61112     for(
61113       u.aq.pSavepoint = db->pSavepoint;
61114       u.aq.pSavepoint && sqlite3StrICmp(u.aq.pSavepoint->zName, u.aq.zName);
61115       u.aq.pSavepoint = u.aq.pSavepoint->pNext
61116     ){
61117       u.aq.iSavepoint++;
61118     }
61119     if( !u.aq.pSavepoint ){
61120       sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", u.aq.zName);
61121       rc = SQLITE_ERROR;
61122     }else if(
61123         db->writeVdbeCnt>0 || (u.aq.p1==SAVEPOINT_ROLLBACK && db->activeVdbeCnt>1)
61124     ){
61125       /* It is not possible to release (commit) a savepoint if there are
61126       ** active write statements. It is not possible to rollback a savepoint
61127       ** if there are any active statements at all.
61128       */
61129       sqlite3SetString(&p->zErrMsg, db,
61130         "cannot %s savepoint - SQL statements in progress",
61131         (u.aq.p1==SAVEPOINT_ROLLBACK ? "rollback": "release")
61132       );
61133       rc = SQLITE_BUSY;
61134     }else{
61135
61136       /* Determine whether or not this is a transaction savepoint. If so,
61137       ** and this is a RELEASE command, then the current transaction
61138       ** is committed.
61139       */
61140       int isTransaction = u.aq.pSavepoint->pNext==0 && db->isTransactionSavepoint;
61141       if( isTransaction && u.aq.p1==SAVEPOINT_RELEASE ){
61142         if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
61143           goto vdbe_return;
61144         }
61145         db->autoCommit = 1;
61146         if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
61147           p->pc = pc;
61148           db->autoCommit = 0;
61149           p->rc = rc = SQLITE_BUSY;
61150           goto vdbe_return;
61151         }
61152         db->isTransactionSavepoint = 0;
61153         rc = p->rc;
61154       }else{
61155         u.aq.iSavepoint = db->nSavepoint - u.aq.iSavepoint - 1;
61156         for(u.aq.ii=0; u.aq.ii<db->nDb; u.aq.ii++){
61157           rc = sqlite3BtreeSavepoint(db->aDb[u.aq.ii].pBt, u.aq.p1, u.aq.iSavepoint);
61158           if( rc!=SQLITE_OK ){
61159             goto abort_due_to_error;
61160           }
61161         }
61162         if( u.aq.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
61163           sqlite3ExpirePreparedStatements(db);
61164           sqlite3ResetInternalSchema(db, 0);
61165         }
61166       }
61167
61168       /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
61169       ** savepoints nested inside of the savepoint being operated on. */
61170       while( db->pSavepoint!=u.aq.pSavepoint ){
61171         u.aq.pTmp = db->pSavepoint;
61172         db->pSavepoint = u.aq.pTmp->pNext;
61173         sqlite3DbFree(db, u.aq.pTmp);
61174         db->nSavepoint--;
61175       }
61176
61177       /* If it is a RELEASE, then destroy the savepoint being operated on
61178       ** too. If it is a ROLLBACK TO, then set the number of deferred
61179       ** constraint violations present in the database to the value stored
61180       ** when the savepoint was created.  */
61181       if( u.aq.p1==SAVEPOINT_RELEASE ){
61182         assert( u.aq.pSavepoint==db->pSavepoint );
61183         db->pSavepoint = u.aq.pSavepoint->pNext;
61184         sqlite3DbFree(db, u.aq.pSavepoint);
61185         if( !isTransaction ){
61186           db->nSavepoint--;
61187         }
61188       }else{
61189         db->nDeferredCons = u.aq.pSavepoint->nDeferredCons;
61190       }
61191     }
61192   }
61193
61194   break;
61195 }
61196
61197 /* Opcode: AutoCommit P1 P2 * * *
61198 **
61199 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
61200 ** back any currently active btree transactions. If there are any active
61201 ** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
61202 ** there are active writing VMs or active VMs that use shared cache.
61203 **
61204 ** This instruction causes the VM to halt.
61205 */
61206 case OP_AutoCommit: {
61207 #if 0  /* local variables moved into u.ar */
61208   int desiredAutoCommit;
61209   int iRollback;
61210   int turnOnAC;
61211 #endif /* local variables moved into u.ar */
61212
61213   u.ar.desiredAutoCommit = pOp->p1;
61214   u.ar.iRollback = pOp->p2;
61215   u.ar.turnOnAC = u.ar.desiredAutoCommit && !db->autoCommit;
61216   assert( u.ar.desiredAutoCommit==1 || u.ar.desiredAutoCommit==0 );
61217   assert( u.ar.desiredAutoCommit==1 || u.ar.iRollback==0 );
61218   assert( db->activeVdbeCnt>0 );  /* At least this one VM is active */
61219
61220   if( u.ar.turnOnAC && u.ar.iRollback && db->activeVdbeCnt>1 ){
61221     /* If this instruction implements a ROLLBACK and other VMs are
61222     ** still running, and a transaction is active, return an error indicating
61223     ** that the other VMs must complete first.
61224     */
61225     sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
61226         "SQL statements in progress");
61227     rc = SQLITE_BUSY;
61228   }else if( u.ar.turnOnAC && !u.ar.iRollback && db->writeVdbeCnt>0 ){
61229     /* If this instruction implements a COMMIT and other VMs are writing
61230     ** return an error indicating that the other VMs must complete first.
61231     */
61232     sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
61233         "SQL statements in progress");
61234     rc = SQLITE_BUSY;
61235   }else if( u.ar.desiredAutoCommit!=db->autoCommit ){
61236     if( u.ar.iRollback ){
61237       assert( u.ar.desiredAutoCommit==1 );
61238       sqlite3RollbackAll(db);
61239       db->autoCommit = 1;
61240     }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
61241       goto vdbe_return;
61242     }else{
61243       db->autoCommit = (u8)u.ar.desiredAutoCommit;
61244       if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
61245         p->pc = pc;
61246         db->autoCommit = (u8)(1-u.ar.desiredAutoCommit);
61247         p->rc = rc = SQLITE_BUSY;
61248         goto vdbe_return;
61249       }
61250     }
61251     assert( db->nStatement==0 );
61252     sqlite3CloseSavepoints(db);
61253     if( p->rc==SQLITE_OK ){
61254       rc = SQLITE_DONE;
61255     }else{
61256       rc = SQLITE_ERROR;
61257     }
61258     goto vdbe_return;
61259   }else{
61260     sqlite3SetString(&p->zErrMsg, db,
61261         (!u.ar.desiredAutoCommit)?"cannot start a transaction within a transaction":(
61262         (u.ar.iRollback)?"cannot rollback - no transaction is active":
61263                    "cannot commit - no transaction is active"));
61264
61265     rc = SQLITE_ERROR;
61266   }
61267   break;
61268 }
61269
61270 /* Opcode: Transaction P1 P2 * * *
61271 **
61272 ** Begin a transaction.  The transaction ends when a Commit or Rollback
61273 ** opcode is encountered.  Depending on the ON CONFLICT setting, the
61274 ** transaction might also be rolled back if an error is encountered.
61275 **
61276 ** P1 is the index of the database file on which the transaction is
61277 ** started.  Index 0 is the main database file and index 1 is the
61278 ** file used for temporary tables.  Indices of 2 or more are used for
61279 ** attached databases.
61280 **
61281 ** If P2 is non-zero, then a write-transaction is started.  A RESERVED lock is
61282 ** obtained on the database file when a write-transaction is started.  No
61283 ** other process can start another write transaction while this transaction is
61284 ** underway.  Starting a write transaction also creates a rollback journal. A
61285 ** write transaction must be started before any changes can be made to the
61286 ** database.  If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
61287 ** on the file.
61288 **
61289 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
61290 ** true (this flag is set if the Vdbe may modify more than one row and may
61291 ** throw an ABORT exception), a statement transaction may also be opened.
61292 ** More specifically, a statement transaction is opened iff the database
61293 ** connection is currently not in autocommit mode, or if there are other
61294 ** active statements. A statement transaction allows the affects of this
61295 ** VDBE to be rolled back after an error without having to roll back the
61296 ** entire transaction. If no error is encountered, the statement transaction
61297 ** will automatically commit when the VDBE halts.
61298 **
61299 ** If P2 is zero, then a read-lock is obtained on the database file.
61300 */
61301 case OP_Transaction: {
61302 #if 0  /* local variables moved into u.as */
61303   Btree *pBt;
61304 #endif /* local variables moved into u.as */
61305
61306   assert( pOp->p1>=0 && pOp->p1<db->nDb );
61307   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
61308   u.as.pBt = db->aDb[pOp->p1].pBt;
61309
61310   if( u.as.pBt ){
61311     rc = sqlite3BtreeBeginTrans(u.as.pBt, pOp->p2);
61312     if( rc==SQLITE_BUSY ){
61313       p->pc = pc;
61314       p->rc = rc = SQLITE_BUSY;
61315       goto vdbe_return;
61316     }
61317     if( rc!=SQLITE_OK ){
61318       goto abort_due_to_error;
61319     }
61320
61321     if( pOp->p2 && p->usesStmtJournal
61322      && (db->autoCommit==0 || db->activeVdbeCnt>1)
61323     ){
61324       assert( sqlite3BtreeIsInTrans(u.as.pBt) );
61325       if( p->iStatement==0 ){
61326         assert( db->nStatement>=0 && db->nSavepoint>=0 );
61327         db->nStatement++;
61328         p->iStatement = db->nSavepoint + db->nStatement;
61329       }
61330       rc = sqlite3BtreeBeginStmt(u.as.pBt, p->iStatement);
61331
61332       /* Store the current value of the database handles deferred constraint
61333       ** counter. If the statement transaction needs to be rolled back,
61334       ** the value of this counter needs to be restored too.  */
61335       p->nStmtDefCons = db->nDeferredCons;
61336     }
61337   }
61338   break;
61339 }
61340
61341 /* Opcode: ReadCookie P1 P2 P3 * *
61342 **
61343 ** Read cookie number P3 from database P1 and write it into register P2.
61344 ** P3==1 is the schema version.  P3==2 is the database format.
61345 ** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
61346 ** the main database file and P1==1 is the database file used to store
61347 ** temporary tables.
61348 **
61349 ** There must be a read-lock on the database (either a transaction
61350 ** must be started or there must be an open cursor) before
61351 ** executing this instruction.
61352 */
61353 case OP_ReadCookie: {               /* out2-prerelease */
61354 #if 0  /* local variables moved into u.at */
61355   int iMeta;
61356   int iDb;
61357   int iCookie;
61358 #endif /* local variables moved into u.at */
61359
61360   u.at.iDb = pOp->p1;
61361   u.at.iCookie = pOp->p3;
61362   assert( pOp->p3<SQLITE_N_BTREE_META );
61363   assert( u.at.iDb>=0 && u.at.iDb<db->nDb );
61364   assert( db->aDb[u.at.iDb].pBt!=0 );
61365   assert( (p->btreeMask & (1<<u.at.iDb))!=0 );
61366
61367   sqlite3BtreeGetMeta(db->aDb[u.at.iDb].pBt, u.at.iCookie, (u32 *)&u.at.iMeta);
61368   pOut->u.i = u.at.iMeta;
61369   break;
61370 }
61371
61372 /* Opcode: SetCookie P1 P2 P3 * *
61373 **
61374 ** Write the content of register P3 (interpreted as an integer)
61375 ** into cookie number P2 of database P1.  P2==1 is the schema version.  
61376 ** P2==2 is the database format. P2==3 is the recommended pager cache 
61377 ** size, and so forth.  P1==0 is the main database file and P1==1 is the 
61378 ** database file used to store temporary tables.
61379 **
61380 ** A transaction must be started before executing this opcode.
61381 */
61382 case OP_SetCookie: {       /* in3 */
61383 #if 0  /* local variables moved into u.au */
61384   Db *pDb;
61385 #endif /* local variables moved into u.au */
61386   assert( pOp->p2<SQLITE_N_BTREE_META );
61387   assert( pOp->p1>=0 && pOp->p1<db->nDb );
61388   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
61389   u.au.pDb = &db->aDb[pOp->p1];
61390   assert( u.au.pDb->pBt!=0 );
61391   pIn3 = &aMem[pOp->p3];
61392   sqlite3VdbeMemIntegerify(pIn3);
61393   /* See note about index shifting on OP_ReadCookie */
61394   rc = sqlite3BtreeUpdateMeta(u.au.pDb->pBt, pOp->p2, (int)pIn3->u.i);
61395   if( pOp->p2==BTREE_SCHEMA_VERSION ){
61396     /* When the schema cookie changes, record the new cookie internally */
61397     u.au.pDb->pSchema->schema_cookie = (int)pIn3->u.i;
61398     db->flags |= SQLITE_InternChanges;
61399   }else if( pOp->p2==BTREE_FILE_FORMAT ){
61400     /* Record changes in the file format */
61401     u.au.pDb->pSchema->file_format = (u8)pIn3->u.i;
61402   }
61403   if( pOp->p1==1 ){
61404     /* Invalidate all prepared statements whenever the TEMP database
61405     ** schema is changed.  Ticket #1644 */
61406     sqlite3ExpirePreparedStatements(db);
61407     p->expired = 0;
61408   }
61409   break;
61410 }
61411
61412 /* Opcode: VerifyCookie P1 P2 *
61413 **
61414 ** Check the value of global database parameter number 0 (the
61415 ** schema version) and make sure it is equal to P2.  
61416 ** P1 is the database number which is 0 for the main database file
61417 ** and 1 for the file holding temporary tables and some higher number
61418 ** for auxiliary databases.
61419 **
61420 ** The cookie changes its value whenever the database schema changes.
61421 ** This operation is used to detect when that the cookie has changed
61422 ** and that the current process needs to reread the schema.
61423 **
61424 ** Either a transaction needs to have been started or an OP_Open needs
61425 ** to be executed (to establish a read lock) before this opcode is
61426 ** invoked.
61427 */
61428 case OP_VerifyCookie: {
61429 #if 0  /* local variables moved into u.av */
61430   int iMeta;
61431   Btree *pBt;
61432 #endif /* local variables moved into u.av */
61433   assert( pOp->p1>=0 && pOp->p1<db->nDb );
61434   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
61435   u.av.pBt = db->aDb[pOp->p1].pBt;
61436   if( u.av.pBt ){
61437     sqlite3BtreeGetMeta(u.av.pBt, BTREE_SCHEMA_VERSION, (u32 *)&u.av.iMeta);
61438   }else{
61439     u.av.iMeta = 0;
61440   }
61441   if( u.av.iMeta!=pOp->p2 ){
61442     sqlite3DbFree(db, p->zErrMsg);
61443     p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
61444     /* If the schema-cookie from the database file matches the cookie
61445     ** stored with the in-memory representation of the schema, do
61446     ** not reload the schema from the database file.
61447     **
61448     ** If virtual-tables are in use, this is not just an optimization.
61449     ** Often, v-tables store their data in other SQLite tables, which
61450     ** are queried from within xNext() and other v-table methods using
61451     ** prepared queries. If such a query is out-of-date, we do not want to
61452     ** discard the database schema, as the user code implementing the
61453     ** v-table would have to be ready for the sqlite3_vtab structure itself
61454     ** to be invalidated whenever sqlite3_step() is called from within
61455     ** a v-table method.
61456     */
61457     if( db->aDb[pOp->p1].pSchema->schema_cookie!=u.av.iMeta ){
61458       sqlite3ResetInternalSchema(db, pOp->p1);
61459     }
61460
61461     sqlite3ExpirePreparedStatements(db);
61462     rc = SQLITE_SCHEMA;
61463   }
61464   break;
61465 }
61466
61467 /* Opcode: OpenRead P1 P2 P3 P4 P5
61468 **
61469 ** Open a read-only cursor for the database table whose root page is
61470 ** P2 in a database file.  The database file is determined by P3. 
61471 ** P3==0 means the main database, P3==1 means the database used for 
61472 ** temporary tables, and P3>1 means used the corresponding attached
61473 ** database.  Give the new cursor an identifier of P1.  The P1
61474 ** values need not be contiguous but all P1 values should be small integers.
61475 ** It is an error for P1 to be negative.
61476 **
61477 ** If P5!=0 then use the content of register P2 as the root page, not
61478 ** the value of P2 itself.
61479 **
61480 ** There will be a read lock on the database whenever there is an
61481 ** open cursor.  If the database was unlocked prior to this instruction
61482 ** then a read lock is acquired as part of this instruction.  A read
61483 ** lock allows other processes to read the database but prohibits
61484 ** any other process from modifying the database.  The read lock is
61485 ** released when all cursors are closed.  If this instruction attempts
61486 ** to get a read lock but fails, the script terminates with an
61487 ** SQLITE_BUSY error code.
61488 **
61489 ** The P4 value may be either an integer (P4_INT32) or a pointer to
61490 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 
61491 ** structure, then said structure defines the content and collating 
61492 ** sequence of the index being opened. Otherwise, if P4 is an integer 
61493 ** value, it is set to the number of columns in the table.
61494 **
61495 ** See also OpenWrite.
61496 */
61497 /* Opcode: OpenWrite P1 P2 P3 P4 P5
61498 **
61499 ** Open a read/write cursor named P1 on the table or index whose root
61500 ** page is P2.  Or if P5!=0 use the content of register P2 to find the
61501 ** root page.
61502 **
61503 ** The P4 value may be either an integer (P4_INT32) or a pointer to
61504 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 
61505 ** structure, then said structure defines the content and collating 
61506 ** sequence of the index being opened. Otherwise, if P4 is an integer 
61507 ** value, it is set to the number of columns in the table, or to the
61508 ** largest index of any column of the table that is actually used.
61509 **
61510 ** This instruction works just like OpenRead except that it opens the cursor
61511 ** in read/write mode.  For a given table, there can be one or more read-only
61512 ** cursors or a single read/write cursor but not both.
61513 **
61514 ** See also OpenRead.
61515 */
61516 case OP_OpenRead:
61517 case OP_OpenWrite: {
61518 #if 0  /* local variables moved into u.aw */
61519   int nField;
61520   KeyInfo *pKeyInfo;
61521   int p2;
61522   int iDb;
61523   int wrFlag;
61524   Btree *pX;
61525   VdbeCursor *pCur;
61526   Db *pDb;
61527 #endif /* local variables moved into u.aw */
61528
61529   if( p->expired ){
61530     rc = SQLITE_ABORT;
61531     break;
61532   }
61533
61534   u.aw.nField = 0;
61535   u.aw.pKeyInfo = 0;
61536   u.aw.p2 = pOp->p2;
61537   u.aw.iDb = pOp->p3;
61538   assert( u.aw.iDb>=0 && u.aw.iDb<db->nDb );
61539   assert( (p->btreeMask & (1<<u.aw.iDb))!=0 );
61540   u.aw.pDb = &db->aDb[u.aw.iDb];
61541   u.aw.pX = u.aw.pDb->pBt;
61542   assert( u.aw.pX!=0 );
61543   if( pOp->opcode==OP_OpenWrite ){
61544     u.aw.wrFlag = 1;
61545     if( u.aw.pDb->pSchema->file_format < p->minWriteFileFormat ){
61546       p->minWriteFileFormat = u.aw.pDb->pSchema->file_format;
61547     }
61548   }else{
61549     u.aw.wrFlag = 0;
61550   }
61551   if( pOp->p5 ){
61552     assert( u.aw.p2>0 );
61553     assert( u.aw.p2<=p->nMem );
61554     pIn2 = &aMem[u.aw.p2];
61555     sqlite3VdbeMemIntegerify(pIn2);
61556     u.aw.p2 = (int)pIn2->u.i;
61557     /* The u.aw.p2 value always comes from a prior OP_CreateTable opcode and
61558     ** that opcode will always set the u.aw.p2 value to 2 or more or else fail.
61559     ** If there were a failure, the prepared statement would have halted
61560     ** before reaching this instruction. */
61561     if( NEVER(u.aw.p2<2) ) {
61562       rc = SQLITE_CORRUPT_BKPT;
61563       goto abort_due_to_error;
61564     }
61565   }
61566   if( pOp->p4type==P4_KEYINFO ){
61567     u.aw.pKeyInfo = pOp->p4.pKeyInfo;
61568     u.aw.pKeyInfo->enc = ENC(p->db);
61569     u.aw.nField = u.aw.pKeyInfo->nField+1;
61570   }else if( pOp->p4type==P4_INT32 ){
61571     u.aw.nField = pOp->p4.i;
61572   }
61573   assert( pOp->p1>=0 );
61574   u.aw.pCur = allocateCursor(p, pOp->p1, u.aw.nField, u.aw.iDb, 1);
61575   if( u.aw.pCur==0 ) goto no_mem;
61576   u.aw.pCur->nullRow = 1;
61577   rc = sqlite3BtreeCursor(u.aw.pX, u.aw.p2, u.aw.wrFlag, u.aw.pKeyInfo, u.aw.pCur->pCursor);
61578   u.aw.pCur->pKeyInfo = u.aw.pKeyInfo;
61579
61580   /* Since it performs no memory allocation or IO, the only values that
61581   ** sqlite3BtreeCursor() may return are SQLITE_EMPTY and SQLITE_OK.
61582   ** SQLITE_EMPTY is only returned when attempting to open the table
61583   ** rooted at page 1 of a zero-byte database.  */
61584   assert( rc==SQLITE_EMPTY || rc==SQLITE_OK );
61585   if( rc==SQLITE_EMPTY ){
61586     u.aw.pCur->pCursor = 0;
61587     rc = SQLITE_OK;
61588   }
61589
61590   /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of
61591   ** SQLite used to check if the root-page flags were sane at this point
61592   ** and report database corruption if they were not, but this check has
61593   ** since moved into the btree layer.  */
61594   u.aw.pCur->isTable = pOp->p4type!=P4_KEYINFO;
61595   u.aw.pCur->isIndex = !u.aw.pCur->isTable;
61596   break;
61597 }
61598
61599 /* Opcode: OpenEphemeral P1 P2 * P4 *
61600 **
61601 ** Open a new cursor P1 to a transient table.
61602 ** The cursor is always opened read/write even if 
61603 ** the main database is read-only.  The ephemeral
61604 ** table is deleted automatically when the cursor is closed.
61605 **
61606 ** P2 is the number of columns in the ephemeral table.
61607 ** The cursor points to a BTree table if P4==0 and to a BTree index
61608 ** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
61609 ** that defines the format of keys in the index.
61610 **
61611 ** This opcode was once called OpenTemp.  But that created
61612 ** confusion because the term "temp table", might refer either
61613 ** to a TEMP table at the SQL level, or to a table opened by
61614 ** this opcode.  Then this opcode was call OpenVirtual.  But
61615 ** that created confusion with the whole virtual-table idea.
61616 */
61617 /* Opcode: OpenAutoindex P1 P2 * P4 *
61618 **
61619 ** This opcode works the same as OP_OpenEphemeral.  It has a
61620 ** different name to distinguish its use.  Tables created using
61621 ** by this opcode will be used for automatically created transient
61622 ** indices in joins.
61623 */
61624 case OP_OpenAutoindex: 
61625 case OP_OpenEphemeral: {
61626 #if 0  /* local variables moved into u.ax */
61627   VdbeCursor *pCx;
61628 #endif /* local variables moved into u.ax */
61629   static const int openFlags =
61630       SQLITE_OPEN_READWRITE |
61631       SQLITE_OPEN_CREATE |
61632       SQLITE_OPEN_EXCLUSIVE |
61633       SQLITE_OPEN_DELETEONCLOSE |
61634       SQLITE_OPEN_TRANSIENT_DB;
61635
61636   assert( pOp->p1>=0 );
61637   u.ax.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
61638   if( u.ax.pCx==0 ) goto no_mem;
61639   u.ax.pCx->nullRow = 1;
61640   rc = sqlite3BtreeFactory(db, 0, 1, SQLITE_DEFAULT_TEMP_CACHE_SIZE, openFlags,
61641                            &u.ax.pCx->pBt);
61642   if( rc==SQLITE_OK ){
61643     rc = sqlite3BtreeBeginTrans(u.ax.pCx->pBt, 1);
61644   }
61645   if( rc==SQLITE_OK ){
61646     /* If a transient index is required, create it by calling
61647     ** sqlite3BtreeCreateTable() with the BTREE_ZERODATA flag before
61648     ** opening it. If a transient table is required, just use the
61649     ** automatically created table with root-page 1 (an INTKEY table).
61650     */
61651     if( pOp->p4.pKeyInfo ){
61652       int pgno;
61653       assert( pOp->p4type==P4_KEYINFO );
61654       rc = sqlite3BtreeCreateTable(u.ax.pCx->pBt, &pgno, BTREE_ZERODATA);
61655       if( rc==SQLITE_OK ){
61656         assert( pgno==MASTER_ROOT+1 );
61657         rc = sqlite3BtreeCursor(u.ax.pCx->pBt, pgno, 1,
61658                                 (KeyInfo*)pOp->p4.z, u.ax.pCx->pCursor);
61659         u.ax.pCx->pKeyInfo = pOp->p4.pKeyInfo;
61660         u.ax.pCx->pKeyInfo->enc = ENC(p->db);
61661       }
61662       u.ax.pCx->isTable = 0;
61663     }else{
61664       rc = sqlite3BtreeCursor(u.ax.pCx->pBt, MASTER_ROOT, 1, 0, u.ax.pCx->pCursor);
61665       u.ax.pCx->isTable = 1;
61666     }
61667   }
61668   u.ax.pCx->isIndex = !u.ax.pCx->isTable;
61669   break;
61670 }
61671
61672 /* Opcode: OpenPseudo P1 P2 P3 * *
61673 **
61674 ** Open a new cursor that points to a fake table that contains a single
61675 ** row of data.  The content of that one row in the content of memory
61676 ** register P2.  In other words, cursor P1 becomes an alias for the 
61677 ** MEM_Blob content contained in register P2.
61678 **
61679 ** A pseudo-table created by this opcode is used to hold a single
61680 ** row output from the sorter so that the row can be decomposed into
61681 ** individual columns using the OP_Column opcode.  The OP_Column opcode
61682 ** is the only cursor opcode that works with a pseudo-table.
61683 **
61684 ** P3 is the number of fields in the records that will be stored by
61685 ** the pseudo-table.
61686 */
61687 case OP_OpenPseudo: {
61688 #if 0  /* local variables moved into u.ay */
61689   VdbeCursor *pCx;
61690 #endif /* local variables moved into u.ay */
61691
61692   assert( pOp->p1>=0 );
61693   u.ay.pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
61694   if( u.ay.pCx==0 ) goto no_mem;
61695   u.ay.pCx->nullRow = 1;
61696   u.ay.pCx->pseudoTableReg = pOp->p2;
61697   u.ay.pCx->isTable = 1;
61698   u.ay.pCx->isIndex = 0;
61699   break;
61700 }
61701
61702 /* Opcode: Close P1 * * * *
61703 **
61704 ** Close a cursor previously opened as P1.  If P1 is not
61705 ** currently open, this instruction is a no-op.
61706 */
61707 case OP_Close: {
61708   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
61709   sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
61710   p->apCsr[pOp->p1] = 0;
61711   break;
61712 }
61713
61714 /* Opcode: SeekGe P1 P2 P3 P4 *
61715 **
61716 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
61717 ** use the value in register P3 as the key.  If cursor P1 refers 
61718 ** to an SQL index, then P3 is the first in an array of P4 registers 
61719 ** that are used as an unpacked index key. 
61720 **
61721 ** Reposition cursor P1 so that  it points to the smallest entry that 
61722 ** is greater than or equal to the key value. If there are no records 
61723 ** greater than or equal to the key and P2 is not zero, then jump to P2.
61724 **
61725 ** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
61726 */
61727 /* Opcode: SeekGt P1 P2 P3 P4 *
61728 **
61729 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
61730 ** use the value in register P3 as a key. If cursor P1 refers 
61731 ** to an SQL index, then P3 is the first in an array of P4 registers 
61732 ** that are used as an unpacked index key. 
61733 **
61734 ** Reposition cursor P1 so that  it points to the smallest entry that 
61735 ** is greater than the key value. If there are no records greater than 
61736 ** the key and P2 is not zero, then jump to P2.
61737 **
61738 ** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
61739 */
61740 /* Opcode: SeekLt P1 P2 P3 P4 * 
61741 **
61742 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
61743 ** use the value in register P3 as a key. If cursor P1 refers 
61744 ** to an SQL index, then P3 is the first in an array of P4 registers 
61745 ** that are used as an unpacked index key. 
61746 **
61747 ** Reposition cursor P1 so that  it points to the largest entry that 
61748 ** is less than the key value. If there are no records less than 
61749 ** the key and P2 is not zero, then jump to P2.
61750 **
61751 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
61752 */
61753 /* Opcode: SeekLe P1 P2 P3 P4 *
61754 **
61755 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
61756 ** use the value in register P3 as a key. If cursor P1 refers 
61757 ** to an SQL index, then P3 is the first in an array of P4 registers 
61758 ** that are used as an unpacked index key. 
61759 **
61760 ** Reposition cursor P1 so that it points to the largest entry that 
61761 ** is less than or equal to the key value. If there are no records 
61762 ** less than or equal to the key and P2 is not zero, then jump to P2.
61763 **
61764 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
61765 */
61766 case OP_SeekLt:         /* jump, in3 */
61767 case OP_SeekLe:         /* jump, in3 */
61768 case OP_SeekGe:         /* jump, in3 */
61769 case OP_SeekGt: {       /* jump, in3 */
61770 #if 0  /* local variables moved into u.az */
61771   int res;
61772   int oc;
61773   VdbeCursor *pC;
61774   UnpackedRecord r;
61775   int nField;
61776   i64 iKey;      /* The rowid we are to seek to */
61777 #endif /* local variables moved into u.az */
61778
61779   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
61780   assert( pOp->p2!=0 );
61781   u.az.pC = p->apCsr[pOp->p1];
61782   assert( u.az.pC!=0 );
61783   assert( u.az.pC->pseudoTableReg==0 );
61784   assert( OP_SeekLe == OP_SeekLt+1 );
61785   assert( OP_SeekGe == OP_SeekLt+2 );
61786   assert( OP_SeekGt == OP_SeekLt+3 );
61787   if( u.az.pC->pCursor!=0 ){
61788     u.az.oc = pOp->opcode;
61789     u.az.pC->nullRow = 0;
61790     if( u.az.pC->isTable ){
61791       /* The input value in P3 might be of any type: integer, real, string,
61792       ** blob, or NULL.  But it needs to be an integer before we can do
61793       ** the seek, so covert it. */
61794       pIn3 = &aMem[pOp->p3];
61795       applyNumericAffinity(pIn3);
61796       u.az.iKey = sqlite3VdbeIntValue(pIn3);
61797       u.az.pC->rowidIsValid = 0;
61798
61799       /* If the P3 value could not be converted into an integer without
61800       ** loss of information, then special processing is required... */
61801       if( (pIn3->flags & MEM_Int)==0 ){
61802         if( (pIn3->flags & MEM_Real)==0 ){
61803           /* If the P3 value cannot be converted into any kind of a number,
61804           ** then the seek is not possible, so jump to P2 */
61805           pc = pOp->p2 - 1;
61806           break;
61807         }
61808         /* If we reach this point, then the P3 value must be a floating
61809         ** point number. */
61810         assert( (pIn3->flags & MEM_Real)!=0 );
61811
61812         if( u.az.iKey==SMALLEST_INT64 && (pIn3->r<(double)u.az.iKey || pIn3->r>0) ){
61813           /* The P3 value is too large in magnitude to be expressed as an
61814           ** integer. */
61815           u.az.res = 1;
61816           if( pIn3->r<0 ){
61817             if( u.az.oc>=OP_SeekGe ){  assert( u.az.oc==OP_SeekGe || u.az.oc==OP_SeekGt );
61818               rc = sqlite3BtreeFirst(u.az.pC->pCursor, &u.az.res);
61819               if( rc!=SQLITE_OK ) goto abort_due_to_error;
61820             }
61821           }else{
61822             if( u.az.oc<=OP_SeekLe ){  assert( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekLe );
61823               rc = sqlite3BtreeLast(u.az.pC->pCursor, &u.az.res);
61824               if( rc!=SQLITE_OK ) goto abort_due_to_error;
61825             }
61826           }
61827           if( u.az.res ){
61828             pc = pOp->p2 - 1;
61829           }
61830           break;
61831         }else if( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekGe ){
61832           /* Use the ceiling() function to convert real->int */
61833           if( pIn3->r > (double)u.az.iKey ) u.az.iKey++;
61834         }else{
61835           /* Use the floor() function to convert real->int */
61836           assert( u.az.oc==OP_SeekLe || u.az.oc==OP_SeekGt );
61837           if( pIn3->r < (double)u.az.iKey ) u.az.iKey--;
61838         }
61839       }
61840       rc = sqlite3BtreeMovetoUnpacked(u.az.pC->pCursor, 0, (u64)u.az.iKey, 0, &u.az.res);
61841       if( rc!=SQLITE_OK ){
61842         goto abort_due_to_error;
61843       }
61844       if( u.az.res==0 ){
61845         u.az.pC->rowidIsValid = 1;
61846         u.az.pC->lastRowid = u.az.iKey;
61847       }
61848     }else{
61849       u.az.nField = pOp->p4.i;
61850       assert( pOp->p4type==P4_INT32 );
61851       assert( u.az.nField>0 );
61852       u.az.r.pKeyInfo = u.az.pC->pKeyInfo;
61853       u.az.r.nField = (u16)u.az.nField;
61854
61855       /* The next line of code computes as follows, only faster:
61856       **   if( u.az.oc==OP_SeekGt || u.az.oc==OP_SeekLe ){
61857       **     u.az.r.flags = UNPACKED_INCRKEY;
61858       **   }else{
61859       **     u.az.r.flags = 0;
61860       **   }
61861       */
61862       u.az.r.flags = (u16)(UNPACKED_INCRKEY * (1 & (u.az.oc - OP_SeekLt)));
61863       assert( u.az.oc!=OP_SeekGt || u.az.r.flags==UNPACKED_INCRKEY );
61864       assert( u.az.oc!=OP_SeekLe || u.az.r.flags==UNPACKED_INCRKEY );
61865       assert( u.az.oc!=OP_SeekGe || u.az.r.flags==0 );
61866       assert( u.az.oc!=OP_SeekLt || u.az.r.flags==0 );
61867
61868       u.az.r.aMem = &aMem[pOp->p3];
61869       ExpandBlob(u.az.r.aMem);
61870       rc = sqlite3BtreeMovetoUnpacked(u.az.pC->pCursor, &u.az.r, 0, 0, &u.az.res);
61871       if( rc!=SQLITE_OK ){
61872         goto abort_due_to_error;
61873       }
61874       u.az.pC->rowidIsValid = 0;
61875     }
61876     u.az.pC->deferredMoveto = 0;
61877     u.az.pC->cacheStatus = CACHE_STALE;
61878 #ifdef SQLITE_TEST
61879     sqlite3_search_count++;
61880 #endif
61881     if( u.az.oc>=OP_SeekGe ){  assert( u.az.oc==OP_SeekGe || u.az.oc==OP_SeekGt );
61882       if( u.az.res<0 || (u.az.res==0 && u.az.oc==OP_SeekGt) ){
61883         rc = sqlite3BtreeNext(u.az.pC->pCursor, &u.az.res);
61884         if( rc!=SQLITE_OK ) goto abort_due_to_error;
61885         u.az.pC->rowidIsValid = 0;
61886       }else{
61887         u.az.res = 0;
61888       }
61889     }else{
61890       assert( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekLe );
61891       if( u.az.res>0 || (u.az.res==0 && u.az.oc==OP_SeekLt) ){
61892         rc = sqlite3BtreePrevious(u.az.pC->pCursor, &u.az.res);
61893         if( rc!=SQLITE_OK ) goto abort_due_to_error;
61894         u.az.pC->rowidIsValid = 0;
61895       }else{
61896         /* u.az.res might be negative because the table is empty.  Check to
61897         ** see if this is the case.
61898         */
61899         u.az.res = sqlite3BtreeEof(u.az.pC->pCursor);
61900       }
61901     }
61902     assert( pOp->p2>0 );
61903     if( u.az.res ){
61904       pc = pOp->p2 - 1;
61905     }
61906   }else{
61907     /* This happens when attempting to open the sqlite3_master table
61908     ** for read access returns SQLITE_EMPTY. In this case always
61909     ** take the jump (since there are no records in the table).
61910     */
61911     pc = pOp->p2 - 1;
61912   }
61913   break;
61914 }
61915
61916 /* Opcode: Seek P1 P2 * * *
61917 **
61918 ** P1 is an open table cursor and P2 is a rowid integer.  Arrange
61919 ** for P1 to move so that it points to the rowid given by P2.
61920 **
61921 ** This is actually a deferred seek.  Nothing actually happens until
61922 ** the cursor is used to read a record.  That way, if no reads
61923 ** occur, no unnecessary I/O happens.
61924 */
61925 case OP_Seek: {    /* in2 */
61926 #if 0  /* local variables moved into u.ba */
61927   VdbeCursor *pC;
61928 #endif /* local variables moved into u.ba */
61929
61930   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
61931   u.ba.pC = p->apCsr[pOp->p1];
61932   assert( u.ba.pC!=0 );
61933   if( ALWAYS(u.ba.pC->pCursor!=0) ){
61934     assert( u.ba.pC->isTable );
61935     u.ba.pC->nullRow = 0;
61936     pIn2 = &aMem[pOp->p2];
61937     u.ba.pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
61938     u.ba.pC->rowidIsValid = 0;
61939     u.ba.pC->deferredMoveto = 1;
61940   }
61941   break;
61942 }
61943   
61944
61945 /* Opcode: Found P1 P2 P3 P4 *
61946 **
61947 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
61948 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
61949 ** record.
61950 **
61951 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
61952 ** is a prefix of any entry in P1 then a jump is made to P2 and
61953 ** P1 is left pointing at the matching entry.
61954 */
61955 /* Opcode: NotFound P1 P2 P3 P4 *
61956 **
61957 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
61958 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
61959 ** record.
61960 ** 
61961 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
61962 ** is not the prefix of any entry in P1 then a jump is made to P2.  If P1 
61963 ** does contain an entry whose prefix matches the P3/P4 record then control
61964 ** falls through to the next instruction and P1 is left pointing at the
61965 ** matching entry.
61966 **
61967 ** See also: Found, NotExists, IsUnique
61968 */
61969 case OP_NotFound:       /* jump, in3 */
61970 case OP_Found: {        /* jump, in3 */
61971 #if 0  /* local variables moved into u.bb */
61972   int alreadyExists;
61973   VdbeCursor *pC;
61974   int res;
61975   UnpackedRecord *pIdxKey;
61976   UnpackedRecord r;
61977   char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
61978 #endif /* local variables moved into u.bb */
61979
61980 #ifdef SQLITE_TEST
61981   sqlite3_found_count++;
61982 #endif
61983
61984   u.bb.alreadyExists = 0;
61985   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
61986   assert( pOp->p4type==P4_INT32 );
61987   u.bb.pC = p->apCsr[pOp->p1];
61988   assert( u.bb.pC!=0 );
61989   pIn3 = &aMem[pOp->p3];
61990   if( ALWAYS(u.bb.pC->pCursor!=0) ){
61991
61992     assert( u.bb.pC->isTable==0 );
61993     if( pOp->p4.i>0 ){
61994       u.bb.r.pKeyInfo = u.bb.pC->pKeyInfo;
61995       u.bb.r.nField = (u16)pOp->p4.i;
61996       u.bb.r.aMem = pIn3;
61997       u.bb.r.flags = UNPACKED_PREFIX_MATCH;
61998       u.bb.pIdxKey = &u.bb.r;
61999     }else{
62000       assert( pIn3->flags & MEM_Blob );
62001       ExpandBlob(pIn3);
62002       u.bb.pIdxKey = sqlite3VdbeRecordUnpack(u.bb.pC->pKeyInfo, pIn3->n, pIn3->z,
62003                                         u.bb.aTempRec, sizeof(u.bb.aTempRec));
62004       if( u.bb.pIdxKey==0 ){
62005         goto no_mem;
62006       }
62007       u.bb.pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
62008     }
62009     rc = sqlite3BtreeMovetoUnpacked(u.bb.pC->pCursor, u.bb.pIdxKey, 0, 0, &u.bb.res);
62010     if( pOp->p4.i==0 ){
62011       sqlite3VdbeDeleteUnpackedRecord(u.bb.pIdxKey);
62012     }
62013     if( rc!=SQLITE_OK ){
62014       break;
62015     }
62016     u.bb.alreadyExists = (u.bb.res==0);
62017     u.bb.pC->deferredMoveto = 0;
62018     u.bb.pC->cacheStatus = CACHE_STALE;
62019   }
62020   if( pOp->opcode==OP_Found ){
62021     if( u.bb.alreadyExists ) pc = pOp->p2 - 1;
62022   }else{
62023     if( !u.bb.alreadyExists ) pc = pOp->p2 - 1;
62024   }
62025   break;
62026 }
62027
62028 /* Opcode: IsUnique P1 P2 P3 P4 *
62029 **
62030 ** Cursor P1 is open on an index b-tree - that is to say, a btree which
62031 ** no data and where the key are records generated by OP_MakeRecord with
62032 ** the list field being the integer ROWID of the entry that the index
62033 ** entry refers to.
62034 **
62035 ** The P3 register contains an integer record number. Call this record 
62036 ** number R. Register P4 is the first in a set of N contiguous registers
62037 ** that make up an unpacked index key that can be used with cursor P1.
62038 ** The value of N can be inferred from the cursor. N includes the rowid
62039 ** value appended to the end of the index record. This rowid value may
62040 ** or may not be the same as R.
62041 **
62042 ** If any of the N registers beginning with register P4 contains a NULL
62043 ** value, jump immediately to P2.
62044 **
62045 ** Otherwise, this instruction checks if cursor P1 contains an entry
62046 ** where the first (N-1) fields match but the rowid value at the end
62047 ** of the index entry is not R. If there is no such entry, control jumps
62048 ** to instruction P2. Otherwise, the rowid of the conflicting index
62049 ** entry is copied to register P3 and control falls through to the next
62050 ** instruction.
62051 **
62052 ** See also: NotFound, NotExists, Found
62053 */
62054 case OP_IsUnique: {        /* jump, in3 */
62055 #if 0  /* local variables moved into u.bc */
62056   u16 ii;
62057   VdbeCursor *pCx;
62058   BtCursor *pCrsr;
62059   u16 nField;
62060   Mem *aMx;
62061   UnpackedRecord r;                  /* B-Tree index search key */
62062   i64 R;                             /* Rowid stored in register P3 */
62063 #endif /* local variables moved into u.bc */
62064
62065   pIn3 = &aMem[pOp->p3];
62066   u.bc.aMx = &aMem[pOp->p4.i];
62067   /* Assert that the values of parameters P1 and P4 are in range. */
62068   assert( pOp->p4type==P4_INT32 );
62069   assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
62070   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
62071
62072   /* Find the index cursor. */
62073   u.bc.pCx = p->apCsr[pOp->p1];
62074   assert( u.bc.pCx->deferredMoveto==0 );
62075   u.bc.pCx->seekResult = 0;
62076   u.bc.pCx->cacheStatus = CACHE_STALE;
62077   u.bc.pCrsr = u.bc.pCx->pCursor;
62078
62079   /* If any of the values are NULL, take the jump. */
62080   u.bc.nField = u.bc.pCx->pKeyInfo->nField;
62081   for(u.bc.ii=0; u.bc.ii<u.bc.nField; u.bc.ii++){
62082     if( u.bc.aMx[u.bc.ii].flags & MEM_Null ){
62083       pc = pOp->p2 - 1;
62084       u.bc.pCrsr = 0;
62085       break;
62086     }
62087   }
62088   assert( (u.bc.aMx[u.bc.nField].flags & MEM_Null)==0 );
62089
62090   if( u.bc.pCrsr!=0 ){
62091     /* Populate the index search key. */
62092     u.bc.r.pKeyInfo = u.bc.pCx->pKeyInfo;
62093     u.bc.r.nField = u.bc.nField + 1;
62094     u.bc.r.flags = UNPACKED_PREFIX_SEARCH;
62095     u.bc.r.aMem = u.bc.aMx;
62096
62097     /* Extract the value of u.bc.R from register P3. */
62098     sqlite3VdbeMemIntegerify(pIn3);
62099     u.bc.R = pIn3->u.i;
62100
62101     /* Search the B-Tree index. If no conflicting record is found, jump
62102     ** to P2. Otherwise, copy the rowid of the conflicting record to
62103     ** register P3 and fall through to the next instruction.  */
62104     rc = sqlite3BtreeMovetoUnpacked(u.bc.pCrsr, &u.bc.r, 0, 0, &u.bc.pCx->seekResult);
62105     if( (u.bc.r.flags & UNPACKED_PREFIX_SEARCH) || u.bc.r.rowid==u.bc.R ){
62106       pc = pOp->p2 - 1;
62107     }else{
62108       pIn3->u.i = u.bc.r.rowid;
62109     }
62110   }
62111   break;
62112 }
62113
62114 /* Opcode: NotExists P1 P2 P3 * *
62115 **
62116 ** Use the content of register P3 as a integer key.  If a record 
62117 ** with that key does not exist in table of P1, then jump to P2. 
62118 ** If the record does exist, then fall thru.  The cursor is left 
62119 ** pointing to the record if it exists.
62120 **
62121 ** The difference between this operation and NotFound is that this
62122 ** operation assumes the key is an integer and that P1 is a table whereas
62123 ** NotFound assumes key is a blob constructed from MakeRecord and
62124 ** P1 is an index.
62125 **
62126 ** See also: Found, NotFound, IsUnique
62127 */
62128 case OP_NotExists: {        /* jump, in3 */
62129 #if 0  /* local variables moved into u.bd */
62130   VdbeCursor *pC;
62131   BtCursor *pCrsr;
62132   int res;
62133   u64 iKey;
62134 #endif /* local variables moved into u.bd */
62135
62136   pIn3 = &aMem[pOp->p3];
62137   assert( pIn3->flags & MEM_Int );
62138   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
62139   u.bd.pC = p->apCsr[pOp->p1];
62140   assert( u.bd.pC!=0 );
62141   assert( u.bd.pC->isTable );
62142   assert( u.bd.pC->pseudoTableReg==0 );
62143   u.bd.pCrsr = u.bd.pC->pCursor;
62144   if( u.bd.pCrsr!=0 ){
62145     u.bd.res = 0;
62146     u.bd.iKey = pIn3->u.i;
62147     rc = sqlite3BtreeMovetoUnpacked(u.bd.pCrsr, 0, u.bd.iKey, 0, &u.bd.res);
62148     u.bd.pC->lastRowid = pIn3->u.i;
62149     u.bd.pC->rowidIsValid = u.bd.res==0 ?1:0;
62150     u.bd.pC->nullRow = 0;
62151     u.bd.pC->cacheStatus = CACHE_STALE;
62152     u.bd.pC->deferredMoveto = 0;
62153     if( u.bd.res!=0 ){
62154       pc = pOp->p2 - 1;
62155       assert( u.bd.pC->rowidIsValid==0 );
62156     }
62157     u.bd.pC->seekResult = u.bd.res;
62158   }else{
62159     /* This happens when an attempt to open a read cursor on the
62160     ** sqlite_master table returns SQLITE_EMPTY.
62161     */
62162     pc = pOp->p2 - 1;
62163     assert( u.bd.pC->rowidIsValid==0 );
62164     u.bd.pC->seekResult = 0;
62165   }
62166   break;
62167 }
62168
62169 /* Opcode: Sequence P1 P2 * * *
62170 **
62171 ** Find the next available sequence number for cursor P1.
62172 ** Write the sequence number into register P2.
62173 ** The sequence number on the cursor is incremented after this
62174 ** instruction.  
62175 */
62176 case OP_Sequence: {           /* out2-prerelease */
62177   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
62178   assert( p->apCsr[pOp->p1]!=0 );
62179   pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
62180   break;
62181 }
62182
62183
62184 /* Opcode: NewRowid P1 P2 P3 * *
62185 **
62186 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
62187 ** The record number is not previously used as a key in the database
62188 ** table that cursor P1 points to.  The new record number is written
62189 ** written to register P2.
62190 **
62191 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds 
62192 ** the largest previously generated record number. No new record numbers are
62193 ** allowed to be less than this value. When this value reaches its maximum, 
62194 ** a SQLITE_FULL error is generated. The P3 register is updated with the '
62195 ** generated record number. This P3 mechanism is used to help implement the
62196 ** AUTOINCREMENT feature.
62197 */
62198 case OP_NewRowid: {           /* out2-prerelease */
62199 #if 0  /* local variables moved into u.be */
62200   i64 v;                 /* The new rowid */
62201   VdbeCursor *pC;        /* Cursor of table to get the new rowid */
62202   int res;               /* Result of an sqlite3BtreeLast() */
62203   int cnt;               /* Counter to limit the number of searches */
62204   Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
62205   VdbeFrame *pFrame;     /* Root frame of VDBE */
62206 #endif /* local variables moved into u.be */
62207
62208   u.be.v = 0;
62209   u.be.res = 0;
62210   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
62211   u.be.pC = p->apCsr[pOp->p1];
62212   assert( u.be.pC!=0 );
62213   if( NEVER(u.be.pC->pCursor==0) ){
62214     /* The zero initialization above is all that is needed */
62215   }else{
62216     /* The next rowid or record number (different terms for the same
62217     ** thing) is obtained in a two-step algorithm.
62218     **
62219     ** First we attempt to find the largest existing rowid and add one
62220     ** to that.  But if the largest existing rowid is already the maximum
62221     ** positive integer, we have to fall through to the second
62222     ** probabilistic algorithm
62223     **
62224     ** The second algorithm is to select a rowid at random and see if
62225     ** it already exists in the table.  If it does not exist, we have
62226     ** succeeded.  If the random rowid does exist, we select a new one
62227     ** and try again, up to 100 times.
62228     */
62229     assert( u.be.pC->isTable );
62230     u.be.cnt = 0;
62231
62232 #ifdef SQLITE_32BIT_ROWID
62233 #   define MAX_ROWID 0x7fffffff
62234 #else
62235     /* Some compilers complain about constants of the form 0x7fffffffffffffff.
62236     ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
62237     ** to provide the constant while making all compilers happy.
62238     */
62239 #   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
62240 #endif
62241
62242     if( !u.be.pC->useRandomRowid ){
62243       u.be.v = sqlite3BtreeGetCachedRowid(u.be.pC->pCursor);
62244       if( u.be.v==0 ){
62245         rc = sqlite3BtreeLast(u.be.pC->pCursor, &u.be.res);
62246         if( rc!=SQLITE_OK ){
62247           goto abort_due_to_error;
62248         }
62249         if( u.be.res ){
62250           u.be.v = 1;   /* IMP: R-61914-48074 */
62251         }else{
62252           assert( sqlite3BtreeCursorIsValid(u.be.pC->pCursor) );
62253           rc = sqlite3BtreeKeySize(u.be.pC->pCursor, &u.be.v);
62254           assert( rc==SQLITE_OK );   /* Cannot fail following BtreeLast() */
62255           if( u.be.v==MAX_ROWID ){
62256             u.be.pC->useRandomRowid = 1;
62257           }else{
62258             u.be.v++;   /* IMP: R-29538-34987 */
62259           }
62260         }
62261       }
62262
62263 #ifndef SQLITE_OMIT_AUTOINCREMENT
62264       if( pOp->p3 ){
62265         /* Assert that P3 is a valid memory cell. */
62266         assert( pOp->p3>0 );
62267         if( p->pFrame ){
62268           for(u.be.pFrame=p->pFrame; u.be.pFrame->pParent; u.be.pFrame=u.be.pFrame->pParent);
62269           /* Assert that P3 is a valid memory cell. */
62270           assert( pOp->p3<=u.be.pFrame->nMem );
62271           u.be.pMem = &u.be.pFrame->aMem[pOp->p3];
62272         }else{
62273           /* Assert that P3 is a valid memory cell. */
62274           assert( pOp->p3<=p->nMem );
62275           u.be.pMem = &aMem[pOp->p3];
62276         }
62277
62278         REGISTER_TRACE(pOp->p3, u.be.pMem);
62279         sqlite3VdbeMemIntegerify(u.be.pMem);
62280         assert( (u.be.pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
62281         if( u.be.pMem->u.i==MAX_ROWID || u.be.pC->useRandomRowid ){
62282           rc = SQLITE_FULL;   /* IMP: R-12275-61338 */
62283           goto abort_due_to_error;
62284         }
62285         if( u.be.v<u.be.pMem->u.i+1 ){
62286           u.be.v = u.be.pMem->u.i + 1;
62287         }
62288         u.be.pMem->u.i = u.be.v;
62289       }
62290 #endif
62291
62292       sqlite3BtreeSetCachedRowid(u.be.pC->pCursor, u.be.v<MAX_ROWID ? u.be.v+1 : 0);
62293     }
62294     if( u.be.pC->useRandomRowid ){
62295       /* IMPLEMENTATION-OF: R-48598-02938 If the largest ROWID is equal to the
62296       ** largest possible integer (9223372036854775807) then the database
62297       ** engine starts picking candidate ROWIDs at random until it finds one
62298       ** that is not previously used.
62299       */
62300       assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
62301                              ** an AUTOINCREMENT table. */
62302       u.be.v = db->lastRowid;
62303       u.be.cnt = 0;
62304       do{
62305         if( u.be.cnt==0 && (u.be.v&0xffffff)==u.be.v ){
62306           u.be.v++;
62307         }else{
62308           sqlite3_randomness(sizeof(u.be.v), &u.be.v);
62309           if( u.be.cnt<5 ) u.be.v &= 0xffffff;
62310         }
62311         rc = sqlite3BtreeMovetoUnpacked(u.be.pC->pCursor, 0, (u64)u.be.v, 0, &u.be.res);
62312         u.be.cnt++;
62313       }while( u.be.cnt<100 && rc==SQLITE_OK && u.be.res==0 );
62314       if( rc==SQLITE_OK && u.be.res==0 ){
62315         rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
62316         goto abort_due_to_error;
62317       }
62318     }
62319     u.be.pC->rowidIsValid = 0;
62320     u.be.pC->deferredMoveto = 0;
62321     u.be.pC->cacheStatus = CACHE_STALE;
62322   }
62323   pOut->u.i = u.be.v;
62324   break;
62325 }
62326
62327 /* Opcode: Insert P1 P2 P3 P4 P5
62328 **
62329 ** Write an entry into the table of cursor P1.  A new entry is
62330 ** created if it doesn't already exist or the data for an existing
62331 ** entry is overwritten.  The data is the value MEM_Blob stored in register
62332 ** number P2. The key is stored in register P3. The key must
62333 ** be a MEM_Int.
62334 **
62335 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
62336 ** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
62337 ** then rowid is stored for subsequent return by the
62338 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
62339 **
62340 ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
62341 ** the last seek operation (OP_NotExists) was a success, then this
62342 ** operation will not attempt to find the appropriate row before doing
62343 ** the insert but will instead overwrite the row that the cursor is
62344 ** currently pointing to.  Presumably, the prior OP_NotExists opcode
62345 ** has already positioned the cursor correctly.  This is an optimization
62346 ** that boosts performance by avoiding redundant seeks.
62347 **
62348 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
62349 ** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
62350 ** is part of an INSERT operation.  The difference is only important to
62351 ** the update hook.
62352 **
62353 ** Parameter P4 may point to a string containing the table-name, or
62354 ** may be NULL. If it is not NULL, then the update-hook 
62355 ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
62356 **
62357 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
62358 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
62359 ** and register P2 becomes ephemeral.  If the cursor is changed, the
62360 ** value of register P2 will then change.  Make sure this does not
62361 ** cause any problems.)
62362 **
62363 ** This instruction only works on tables.  The equivalent instruction
62364 ** for indices is OP_IdxInsert.
62365 */
62366 /* Opcode: InsertInt P1 P2 P3 P4 P5
62367 **
62368 ** This works exactly like OP_Insert except that the key is the
62369 ** integer value P3, not the value of the integer stored in register P3.
62370 */
62371 case OP_Insert: 
62372 case OP_InsertInt: {
62373 #if 0  /* local variables moved into u.bf */
62374   Mem *pData;       /* MEM cell holding data for the record to be inserted */
62375   Mem *pKey;        /* MEM cell holding key  for the record */
62376   i64 iKey;         /* The integer ROWID or key for the record to be inserted */
62377   VdbeCursor *pC;   /* Cursor to table into which insert is written */
62378   int nZero;        /* Number of zero-bytes to append */
62379   int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
62380   const char *zDb;  /* database name - used by the update hook */
62381   const char *zTbl; /* Table name - used by the opdate hook */
62382   int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
62383 #endif /* local variables moved into u.bf */
62384
62385   u.bf.pData = &aMem[pOp->p2];
62386   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
62387   u.bf.pC = p->apCsr[pOp->p1];
62388   assert( u.bf.pC!=0 );
62389   assert( u.bf.pC->pCursor!=0 );
62390   assert( u.bf.pC->pseudoTableReg==0 );
62391   assert( u.bf.pC->isTable );
62392   REGISTER_TRACE(pOp->p2, u.bf.pData);
62393
62394   if( pOp->opcode==OP_Insert ){
62395     u.bf.pKey = &aMem[pOp->p3];
62396     assert( u.bf.pKey->flags & MEM_Int );
62397     REGISTER_TRACE(pOp->p3, u.bf.pKey);
62398     u.bf.iKey = u.bf.pKey->u.i;
62399   }else{
62400     assert( pOp->opcode==OP_InsertInt );
62401     u.bf.iKey = pOp->p3;
62402   }
62403
62404   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
62405   if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = u.bf.iKey;
62406   if( u.bf.pData->flags & MEM_Null ){
62407     u.bf.pData->z = 0;
62408     u.bf.pData->n = 0;
62409   }else{
62410     assert( u.bf.pData->flags & (MEM_Blob|MEM_Str) );
62411   }
62412   u.bf.seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bf.pC->seekResult : 0);
62413   if( u.bf.pData->flags & MEM_Zero ){
62414     u.bf.nZero = u.bf.pData->u.nZero;
62415   }else{
62416     u.bf.nZero = 0;
62417   }
62418   sqlite3BtreeSetCachedRowid(u.bf.pC->pCursor, 0);
62419   rc = sqlite3BtreeInsert(u.bf.pC->pCursor, 0, u.bf.iKey,
62420                           u.bf.pData->z, u.bf.pData->n, u.bf.nZero,
62421                           pOp->p5 & OPFLAG_APPEND, u.bf.seekResult
62422   );
62423   u.bf.pC->rowidIsValid = 0;
62424   u.bf.pC->deferredMoveto = 0;
62425   u.bf.pC->cacheStatus = CACHE_STALE;
62426
62427   /* Invoke the update-hook if required. */
62428   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
62429     u.bf.zDb = db->aDb[u.bf.pC->iDb].zName;
62430     u.bf.zTbl = pOp->p4.z;
62431     u.bf.op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
62432     assert( u.bf.pC->isTable );
62433     db->xUpdateCallback(db->pUpdateArg, u.bf.op, u.bf.zDb, u.bf.zTbl, u.bf.iKey);
62434     assert( u.bf.pC->iDb>=0 );
62435   }
62436   break;
62437 }
62438
62439 /* Opcode: Delete P1 P2 * P4 *
62440 **
62441 ** Delete the record at which the P1 cursor is currently pointing.
62442 **
62443 ** The cursor will be left pointing at either the next or the previous
62444 ** record in the table. If it is left pointing at the next record, then
62445 ** the next Next instruction will be a no-op.  Hence it is OK to delete
62446 ** a record from within an Next loop.
62447 **
62448 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
62449 ** incremented (otherwise not).
62450 **
62451 ** P1 must not be pseudo-table.  It has to be a real table with
62452 ** multiple rows.
62453 **
62454 ** If P4 is not NULL, then it is the name of the table that P1 is
62455 ** pointing to.  The update hook will be invoked, if it exists.
62456 ** If P4 is not NULL then the P1 cursor must have been positioned
62457 ** using OP_NotFound prior to invoking this opcode.
62458 */
62459 case OP_Delete: {
62460 #if 0  /* local variables moved into u.bg */
62461   i64 iKey;
62462   VdbeCursor *pC;
62463 #endif /* local variables moved into u.bg */
62464
62465   u.bg.iKey = 0;
62466   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
62467   u.bg.pC = p->apCsr[pOp->p1];
62468   assert( u.bg.pC!=0 );
62469   assert( u.bg.pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
62470
62471   /* If the update-hook will be invoked, set u.bg.iKey to the rowid of the
62472   ** row being deleted.
62473   */
62474   if( db->xUpdateCallback && pOp->p4.z ){
62475     assert( u.bg.pC->isTable );
62476     assert( u.bg.pC->rowidIsValid );  /* lastRowid set by previous OP_NotFound */
62477     u.bg.iKey = u.bg.pC->lastRowid;
62478   }
62479
62480   /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
62481   ** OP_Column on the same table without any intervening operations that
62482   ** might move or invalidate the cursor.  Hence cursor u.bg.pC is always pointing
62483   ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
62484   ** below is always a no-op and cannot fail.  We will run it anyhow, though,
62485   ** to guard against future changes to the code generator.
62486   **/
62487   assert( u.bg.pC->deferredMoveto==0 );
62488   rc = sqlite3VdbeCursorMoveto(u.bg.pC);
62489   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
62490
62491   sqlite3BtreeSetCachedRowid(u.bg.pC->pCursor, 0);
62492   rc = sqlite3BtreeDelete(u.bg.pC->pCursor);
62493   u.bg.pC->cacheStatus = CACHE_STALE;
62494
62495   /* Invoke the update-hook if required. */
62496   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
62497     const char *zDb = db->aDb[u.bg.pC->iDb].zName;
62498     const char *zTbl = pOp->p4.z;
62499     db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, u.bg.iKey);
62500     assert( u.bg.pC->iDb>=0 );
62501   }
62502   if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
62503   break;
62504 }
62505 /* Opcode: ResetCount * * * * *
62506 **
62507 ** The value of the change counter is copied to the database handle
62508 ** change counter (returned by subsequent calls to sqlite3_changes()).
62509 ** Then the VMs internal change counter resets to 0.
62510 ** This is used by trigger programs.
62511 */
62512 case OP_ResetCount: {
62513   sqlite3VdbeSetChanges(db, p->nChange);
62514   p->nChange = 0;
62515   break;
62516 }
62517
62518 /* Opcode: RowData P1 P2 * * *
62519 **
62520 ** Write into register P2 the complete row data for cursor P1.
62521 ** There is no interpretation of the data.  
62522 ** It is just copied onto the P2 register exactly as 
62523 ** it is found in the database file.
62524 **
62525 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
62526 ** of a real table, not a pseudo-table.
62527 */
62528 /* Opcode: RowKey P1 P2 * * *
62529 **
62530 ** Write into register P2 the complete row key for cursor P1.
62531 ** There is no interpretation of the data.  
62532 ** The key is copied onto the P3 register exactly as 
62533 ** it is found in the database file.
62534 **
62535 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
62536 ** of a real table, not a pseudo-table.
62537 */
62538 case OP_RowKey:
62539 case OP_RowData: {
62540 #if 0  /* local variables moved into u.bh */
62541   VdbeCursor *pC;
62542   BtCursor *pCrsr;
62543   u32 n;
62544   i64 n64;
62545 #endif /* local variables moved into u.bh */
62546
62547   pOut = &aMem[pOp->p2];
62548
62549   /* Note that RowKey and RowData are really exactly the same instruction */
62550   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
62551   u.bh.pC = p->apCsr[pOp->p1];
62552   assert( u.bh.pC->isTable || pOp->opcode==OP_RowKey );
62553   assert( u.bh.pC->isIndex || pOp->opcode==OP_RowData );
62554   assert( u.bh.pC!=0 );
62555   assert( u.bh.pC->nullRow==0 );
62556   assert( u.bh.pC->pseudoTableReg==0 );
62557   assert( u.bh.pC->pCursor!=0 );
62558   u.bh.pCrsr = u.bh.pC->pCursor;
62559   assert( sqlite3BtreeCursorIsValid(u.bh.pCrsr) );
62560
62561   /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
62562   ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
62563   ** the cursor.  Hence the following sqlite3VdbeCursorMoveto() call is always
62564   ** a no-op and can never fail.  But we leave it in place as a safety.
62565   */
62566   assert( u.bh.pC->deferredMoveto==0 );
62567   rc = sqlite3VdbeCursorMoveto(u.bh.pC);
62568   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
62569
62570   if( u.bh.pC->isIndex ){
62571     assert( !u.bh.pC->isTable );
62572     rc = sqlite3BtreeKeySize(u.bh.pCrsr, &u.bh.n64);
62573     assert( rc==SQLITE_OK );    /* True because of CursorMoveto() call above */
62574     if( u.bh.n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
62575       goto too_big;
62576     }
62577     u.bh.n = (u32)u.bh.n64;
62578   }else{
62579     rc = sqlite3BtreeDataSize(u.bh.pCrsr, &u.bh.n);
62580     assert( rc==SQLITE_OK );    /* DataSize() cannot fail */
62581     if( u.bh.n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
62582       goto too_big;
62583     }
62584   }
62585   if( sqlite3VdbeMemGrow(pOut, u.bh.n, 0) ){
62586     goto no_mem;
62587   }
62588   pOut->n = u.bh.n;
62589   MemSetTypeFlag(pOut, MEM_Blob);
62590   if( u.bh.pC->isIndex ){
62591     rc = sqlite3BtreeKey(u.bh.pCrsr, 0, u.bh.n, pOut->z);
62592   }else{
62593     rc = sqlite3BtreeData(u.bh.pCrsr, 0, u.bh.n, pOut->z);
62594   }
62595   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
62596   UPDATE_MAX_BLOBSIZE(pOut);
62597   break;
62598 }
62599
62600 /* Opcode: Rowid P1 P2 * * *
62601 **
62602 ** Store in register P2 an integer which is the key of the table entry that
62603 ** P1 is currently point to.
62604 **
62605 ** P1 can be either an ordinary table or a virtual table.  There used to
62606 ** be a separate OP_VRowid opcode for use with virtual tables, but this
62607 ** one opcode now works for both table types.
62608 */
62609 case OP_Rowid: {                 /* out2-prerelease */
62610 #if 0  /* local variables moved into u.bi */
62611   VdbeCursor *pC;
62612   i64 v;
62613   sqlite3_vtab *pVtab;
62614   const sqlite3_module *pModule;
62615 #endif /* local variables moved into u.bi */
62616
62617   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
62618   u.bi.pC = p->apCsr[pOp->p1];
62619   assert( u.bi.pC!=0 );
62620   assert( u.bi.pC->pseudoTableReg==0 );
62621   if( u.bi.pC->nullRow ){
62622     pOut->flags = MEM_Null;
62623     break;
62624   }else if( u.bi.pC->deferredMoveto ){
62625     u.bi.v = u.bi.pC->movetoTarget;
62626 #ifndef SQLITE_OMIT_VIRTUALTABLE
62627   }else if( u.bi.pC->pVtabCursor ){
62628     u.bi.pVtab = u.bi.pC->pVtabCursor->pVtab;
62629     u.bi.pModule = u.bi.pVtab->pModule;
62630     assert( u.bi.pModule->xRowid );
62631     rc = u.bi.pModule->xRowid(u.bi.pC->pVtabCursor, &u.bi.v);
62632     sqlite3DbFree(db, p->zErrMsg);
62633     p->zErrMsg = u.bi.pVtab->zErrMsg;
62634     u.bi.pVtab->zErrMsg = 0;
62635 #endif /* SQLITE_OMIT_VIRTUALTABLE */
62636   }else{
62637     assert( u.bi.pC->pCursor!=0 );
62638     rc = sqlite3VdbeCursorMoveto(u.bi.pC);
62639     if( rc ) goto abort_due_to_error;
62640     if( u.bi.pC->rowidIsValid ){
62641       u.bi.v = u.bi.pC->lastRowid;
62642     }else{
62643       rc = sqlite3BtreeKeySize(u.bi.pC->pCursor, &u.bi.v);
62644       assert( rc==SQLITE_OK );  /* Always so because of CursorMoveto() above */
62645     }
62646   }
62647   pOut->u.i = u.bi.v;
62648   break;
62649 }
62650
62651 /* Opcode: NullRow P1 * * * *
62652 **
62653 ** Move the cursor P1 to a null row.  Any OP_Column operations
62654 ** that occur while the cursor is on the null row will always
62655 ** write a NULL.
62656 */
62657 case OP_NullRow: {
62658 #if 0  /* local variables moved into u.bj */
62659   VdbeCursor *pC;
62660 #endif /* local variables moved into u.bj */
62661
62662   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
62663   u.bj.pC = p->apCsr[pOp->p1];
62664   assert( u.bj.pC!=0 );
62665   u.bj.pC->nullRow = 1;
62666   u.bj.pC->rowidIsValid = 0;
62667   if( u.bj.pC->pCursor ){
62668     sqlite3BtreeClearCursor(u.bj.pC->pCursor);
62669   }
62670   break;
62671 }
62672
62673 /* Opcode: Last P1 P2 * * *
62674 **
62675 ** The next use of the Rowid or Column or Next instruction for P1 
62676 ** will refer to the last entry in the database table or index.
62677 ** If the table or index is empty and P2>0, then jump immediately to P2.
62678 ** If P2 is 0 or if the table or index is not empty, fall through
62679 ** to the following instruction.
62680 */
62681 case OP_Last: {        /* jump */
62682 #if 0  /* local variables moved into u.bk */
62683   VdbeCursor *pC;
62684   BtCursor *pCrsr;
62685   int res;
62686 #endif /* local variables moved into u.bk */
62687
62688   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
62689   u.bk.pC = p->apCsr[pOp->p1];
62690   assert( u.bk.pC!=0 );
62691   u.bk.pCrsr = u.bk.pC->pCursor;
62692   if( u.bk.pCrsr==0 ){
62693     u.bk.res = 1;
62694   }else{
62695     rc = sqlite3BtreeLast(u.bk.pCrsr, &u.bk.res);
62696   }
62697   u.bk.pC->nullRow = (u8)u.bk.res;
62698   u.bk.pC->deferredMoveto = 0;
62699   u.bk.pC->rowidIsValid = 0;
62700   u.bk.pC->cacheStatus = CACHE_STALE;
62701   if( pOp->p2>0 && u.bk.res ){
62702     pc = pOp->p2 - 1;
62703   }
62704   break;
62705 }
62706
62707
62708 /* Opcode: Sort P1 P2 * * *
62709 **
62710 ** This opcode does exactly the same thing as OP_Rewind except that
62711 ** it increments an undocumented global variable used for testing.
62712 **
62713 ** Sorting is accomplished by writing records into a sorting index,
62714 ** then rewinding that index and playing it back from beginning to
62715 ** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
62716 ** rewinding so that the global variable will be incremented and
62717 ** regression tests can determine whether or not the optimizer is
62718 ** correctly optimizing out sorts.
62719 */
62720 case OP_Sort: {        /* jump */
62721 #ifdef SQLITE_TEST
62722   sqlite3_sort_count++;
62723   sqlite3_search_count--;
62724 #endif
62725   p->aCounter[SQLITE_STMTSTATUS_SORT-1]++;
62726   /* Fall through into OP_Rewind */
62727 }
62728 /* Opcode: Rewind P1 P2 * * *
62729 **
62730 ** The next use of the Rowid or Column or Next instruction for P1 
62731 ** will refer to the first entry in the database table or index.
62732 ** If the table or index is empty and P2>0, then jump immediately to P2.
62733 ** If P2 is 0 or if the table or index is not empty, fall through
62734 ** to the following instruction.
62735 */
62736 case OP_Rewind: {        /* jump */
62737 #if 0  /* local variables moved into u.bl */
62738   VdbeCursor *pC;
62739   BtCursor *pCrsr;
62740   int res;
62741 #endif /* local variables moved into u.bl */
62742
62743   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
62744   u.bl.pC = p->apCsr[pOp->p1];
62745   assert( u.bl.pC!=0 );
62746   u.bl.res = 1;
62747   if( (u.bl.pCrsr = u.bl.pC->pCursor)!=0 ){
62748     rc = sqlite3BtreeFirst(u.bl.pCrsr, &u.bl.res);
62749     u.bl.pC->atFirst = u.bl.res==0 ?1:0;
62750     u.bl.pC->deferredMoveto = 0;
62751     u.bl.pC->cacheStatus = CACHE_STALE;
62752     u.bl.pC->rowidIsValid = 0;
62753   }
62754   u.bl.pC->nullRow = (u8)u.bl.res;
62755   assert( pOp->p2>0 && pOp->p2<p->nOp );
62756   if( u.bl.res ){
62757     pc = pOp->p2 - 1;
62758   }
62759   break;
62760 }
62761
62762 /* Opcode: Next P1 P2 * * P5
62763 **
62764 ** Advance cursor P1 so that it points to the next key/data pair in its
62765 ** table or index.  If there are no more key/value pairs then fall through
62766 ** to the following instruction.  But if the cursor advance was successful,
62767 ** jump immediately to P2.
62768 **
62769 ** The P1 cursor must be for a real table, not a pseudo-table.
62770 **
62771 ** If P5 is positive and the jump is taken, then event counter
62772 ** number P5-1 in the prepared statement is incremented.
62773 **
62774 ** See also: Prev
62775 */
62776 /* Opcode: Prev P1 P2 * * P5
62777 **
62778 ** Back up cursor P1 so that it points to the previous key/data pair in its
62779 ** table or index.  If there is no previous key/value pairs then fall through
62780 ** to the following instruction.  But if the cursor backup was successful,
62781 ** jump immediately to P2.
62782 **
62783 ** The P1 cursor must be for a real table, not a pseudo-table.
62784 **
62785 ** If P5 is positive and the jump is taken, then event counter
62786 ** number P5-1 in the prepared statement is incremented.
62787 */
62788 case OP_Prev:          /* jump */
62789 case OP_Next: {        /* jump */
62790 #if 0  /* local variables moved into u.bm */
62791   VdbeCursor *pC;
62792   BtCursor *pCrsr;
62793   int res;
62794 #endif /* local variables moved into u.bm */
62795
62796   CHECK_FOR_INTERRUPT;
62797   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
62798   assert( pOp->p5<=ArraySize(p->aCounter) );
62799   u.bm.pC = p->apCsr[pOp->p1];
62800   if( u.bm.pC==0 ){
62801     break;  /* See ticket #2273 */
62802   }
62803   u.bm.pCrsr = u.bm.pC->pCursor;
62804   if( u.bm.pCrsr==0 ){
62805     u.bm.pC->nullRow = 1;
62806     break;
62807   }
62808   u.bm.res = 1;
62809   assert( u.bm.pC->deferredMoveto==0 );
62810   rc = pOp->opcode==OP_Next ? sqlite3BtreeNext(u.bm.pCrsr, &u.bm.res) :
62811                               sqlite3BtreePrevious(u.bm.pCrsr, &u.bm.res);
62812   u.bm.pC->nullRow = (u8)u.bm.res;
62813   u.bm.pC->cacheStatus = CACHE_STALE;
62814   if( u.bm.res==0 ){
62815     pc = pOp->p2 - 1;
62816     if( pOp->p5 ) p->aCounter[pOp->p5-1]++;
62817 #ifdef SQLITE_TEST
62818     sqlite3_search_count++;
62819 #endif
62820   }
62821   u.bm.pC->rowidIsValid = 0;
62822   break;
62823 }
62824
62825 /* Opcode: IdxInsert P1 P2 P3 * P5
62826 **
62827 ** Register P2 holds a SQL index key made using the
62828 ** MakeRecord instructions.  This opcode writes that key
62829 ** into the index P1.  Data for the entry is nil.
62830 **
62831 ** P3 is a flag that provides a hint to the b-tree layer that this
62832 ** insert is likely to be an append.
62833 **
62834 ** This instruction only works for indices.  The equivalent instruction
62835 ** for tables is OP_Insert.
62836 */
62837 case OP_IdxInsert: {        /* in2 */
62838 #if 0  /* local variables moved into u.bn */
62839   VdbeCursor *pC;
62840   BtCursor *pCrsr;
62841   int nKey;
62842   const char *zKey;
62843 #endif /* local variables moved into u.bn */
62844
62845   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
62846   u.bn.pC = p->apCsr[pOp->p1];
62847   assert( u.bn.pC!=0 );
62848   pIn2 = &aMem[pOp->p2];
62849   assert( pIn2->flags & MEM_Blob );
62850   u.bn.pCrsr = u.bn.pC->pCursor;
62851   if( ALWAYS(u.bn.pCrsr!=0) ){
62852     assert( u.bn.pC->isTable==0 );
62853     rc = ExpandBlob(pIn2);
62854     if( rc==SQLITE_OK ){
62855       u.bn.nKey = pIn2->n;
62856       u.bn.zKey = pIn2->z;
62857       rc = sqlite3BtreeInsert(u.bn.pCrsr, u.bn.zKey, u.bn.nKey, "", 0, 0, pOp->p3,
62858           ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bn.pC->seekResult : 0)
62859       );
62860       assert( u.bn.pC->deferredMoveto==0 );
62861       u.bn.pC->cacheStatus = CACHE_STALE;
62862     }
62863   }
62864   break;
62865 }
62866
62867 /* Opcode: IdxDelete P1 P2 P3 * *
62868 **
62869 ** The content of P3 registers starting at register P2 form
62870 ** an unpacked index key. This opcode removes that entry from the 
62871 ** index opened by cursor P1.
62872 */
62873 case OP_IdxDelete: {
62874 #if 0  /* local variables moved into u.bo */
62875   VdbeCursor *pC;
62876   BtCursor *pCrsr;
62877   int res;
62878   UnpackedRecord r;
62879 #endif /* local variables moved into u.bo */
62880
62881   assert( pOp->p3>0 );
62882   assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem+1 );
62883   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
62884   u.bo.pC = p->apCsr[pOp->p1];
62885   assert( u.bo.pC!=0 );
62886   u.bo.pCrsr = u.bo.pC->pCursor;
62887   if( ALWAYS(u.bo.pCrsr!=0) ){
62888     u.bo.r.pKeyInfo = u.bo.pC->pKeyInfo;
62889     u.bo.r.nField = (u16)pOp->p3;
62890     u.bo.r.flags = 0;
62891     u.bo.r.aMem = &aMem[pOp->p2];
62892     rc = sqlite3BtreeMovetoUnpacked(u.bo.pCrsr, &u.bo.r, 0, 0, &u.bo.res);
62893     if( rc==SQLITE_OK && u.bo.res==0 ){
62894       rc = sqlite3BtreeDelete(u.bo.pCrsr);
62895     }
62896     assert( u.bo.pC->deferredMoveto==0 );
62897     u.bo.pC->cacheStatus = CACHE_STALE;
62898   }
62899   break;
62900 }
62901
62902 /* Opcode: IdxRowid P1 P2 * * *
62903 **
62904 ** Write into register P2 an integer which is the last entry in the record at
62905 ** the end of the index key pointed to by cursor P1.  This integer should be
62906 ** the rowid of the table entry to which this index entry points.
62907 **
62908 ** See also: Rowid, MakeRecord.
62909 */
62910 case OP_IdxRowid: {              /* out2-prerelease */
62911 #if 0  /* local variables moved into u.bp */
62912   BtCursor *pCrsr;
62913   VdbeCursor *pC;
62914   i64 rowid;
62915 #endif /* local variables moved into u.bp */
62916
62917   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
62918   u.bp.pC = p->apCsr[pOp->p1];
62919   assert( u.bp.pC!=0 );
62920   u.bp.pCrsr = u.bp.pC->pCursor;
62921   pOut->flags = MEM_Null;
62922   if( ALWAYS(u.bp.pCrsr!=0) ){
62923     rc = sqlite3VdbeCursorMoveto(u.bp.pC);
62924     if( NEVER(rc) ) goto abort_due_to_error;
62925     assert( u.bp.pC->deferredMoveto==0 );
62926     assert( u.bp.pC->isTable==0 );
62927     if( !u.bp.pC->nullRow ){
62928       rc = sqlite3VdbeIdxRowid(db, u.bp.pCrsr, &u.bp.rowid);
62929       if( rc!=SQLITE_OK ){
62930         goto abort_due_to_error;
62931       }
62932       pOut->u.i = u.bp.rowid;
62933       pOut->flags = MEM_Int;
62934     }
62935   }
62936   break;
62937 }
62938
62939 /* Opcode: IdxGE P1 P2 P3 P4 P5
62940 **
62941 ** The P4 register values beginning with P3 form an unpacked index 
62942 ** key that omits the ROWID.  Compare this key value against the index 
62943 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
62944 **
62945 ** If the P1 index entry is greater than or equal to the key value
62946 ** then jump to P2.  Otherwise fall through to the next instruction.
62947 **
62948 ** If P5 is non-zero then the key value is increased by an epsilon 
62949 ** prior to the comparison.  This make the opcode work like IdxGT except
62950 ** that if the key from register P3 is a prefix of the key in the cursor,
62951 ** the result is false whereas it would be true with IdxGT.
62952 */
62953 /* Opcode: IdxLT P1 P2 P3 * P5
62954 **
62955 ** The P4 register values beginning with P3 form an unpacked index 
62956 ** key that omits the ROWID.  Compare this key value against the index 
62957 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
62958 **
62959 ** If the P1 index entry is less than the key value then jump to P2.
62960 ** Otherwise fall through to the next instruction.
62961 **
62962 ** If P5 is non-zero then the key value is increased by an epsilon prior 
62963 ** to the comparison.  This makes the opcode work like IdxLE.
62964 */
62965 case OP_IdxLT:          /* jump */
62966 case OP_IdxGE: {        /* jump */
62967 #if 0  /* local variables moved into u.bq */
62968   VdbeCursor *pC;
62969   int res;
62970   UnpackedRecord r;
62971 #endif /* local variables moved into u.bq */
62972
62973   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
62974   u.bq.pC = p->apCsr[pOp->p1];
62975   assert( u.bq.pC!=0 );
62976   if( ALWAYS(u.bq.pC->pCursor!=0) ){
62977     assert( u.bq.pC->deferredMoveto==0 );
62978     assert( pOp->p5==0 || pOp->p5==1 );
62979     assert( pOp->p4type==P4_INT32 );
62980     u.bq.r.pKeyInfo = u.bq.pC->pKeyInfo;
62981     u.bq.r.nField = (u16)pOp->p4.i;
62982     if( pOp->p5 ){
62983       u.bq.r.flags = UNPACKED_INCRKEY | UNPACKED_IGNORE_ROWID;
62984     }else{
62985       u.bq.r.flags = UNPACKED_IGNORE_ROWID;
62986     }
62987     u.bq.r.aMem = &aMem[pOp->p3];
62988     rc = sqlite3VdbeIdxKeyCompare(u.bq.pC, &u.bq.r, &u.bq.res);
62989     if( pOp->opcode==OP_IdxLT ){
62990       u.bq.res = -u.bq.res;
62991     }else{
62992       assert( pOp->opcode==OP_IdxGE );
62993       u.bq.res++;
62994     }
62995     if( u.bq.res>0 ){
62996       pc = pOp->p2 - 1 ;
62997     }
62998   }
62999   break;
63000 }
63001
63002 /* Opcode: Destroy P1 P2 P3 * *
63003 **
63004 ** Delete an entire database table or index whose root page in the database
63005 ** file is given by P1.
63006 **
63007 ** The table being destroyed is in the main database file if P3==0.  If
63008 ** P3==1 then the table to be clear is in the auxiliary database file
63009 ** that is used to store tables create using CREATE TEMPORARY TABLE.
63010 **
63011 ** If AUTOVACUUM is enabled then it is possible that another root page
63012 ** might be moved into the newly deleted root page in order to keep all
63013 ** root pages contiguous at the beginning of the database.  The former
63014 ** value of the root page that moved - its value before the move occurred -
63015 ** is stored in register P2.  If no page 
63016 ** movement was required (because the table being dropped was already 
63017 ** the last one in the database) then a zero is stored in register P2.
63018 ** If AUTOVACUUM is disabled then a zero is stored in register P2.
63019 **
63020 ** See also: Clear
63021 */
63022 case OP_Destroy: {     /* out2-prerelease */
63023 #if 0  /* local variables moved into u.br */
63024   int iMoved;
63025   int iCnt;
63026   Vdbe *pVdbe;
63027   int iDb;
63028 #endif /* local variables moved into u.br */
63029 #ifndef SQLITE_OMIT_VIRTUALTABLE
63030   u.br.iCnt = 0;
63031   for(u.br.pVdbe=db->pVdbe; u.br.pVdbe; u.br.pVdbe = u.br.pVdbe->pNext){
63032     if( u.br.pVdbe->magic==VDBE_MAGIC_RUN && u.br.pVdbe->inVtabMethod<2 && u.br.pVdbe->pc>=0 ){
63033       u.br.iCnt++;
63034     }
63035   }
63036 #else
63037   u.br.iCnt = db->activeVdbeCnt;
63038 #endif
63039   pOut->flags = MEM_Null;
63040   if( u.br.iCnt>1 ){
63041     rc = SQLITE_LOCKED;
63042     p->errorAction = OE_Abort;
63043   }else{
63044     u.br.iDb = pOp->p3;
63045     assert( u.br.iCnt==1 );
63046     assert( (p->btreeMask & (1<<u.br.iDb))!=0 );
63047     rc = sqlite3BtreeDropTable(db->aDb[u.br.iDb].pBt, pOp->p1, &u.br.iMoved);
63048     pOut->flags = MEM_Int;
63049     pOut->u.i = u.br.iMoved;
63050 #ifndef SQLITE_OMIT_AUTOVACUUM
63051     if( rc==SQLITE_OK && u.br.iMoved!=0 ){
63052       sqlite3RootPageMoved(&db->aDb[u.br.iDb], u.br.iMoved, pOp->p1);
63053       resetSchemaOnFault = 1;
63054     }
63055 #endif
63056   }
63057   break;
63058 }
63059
63060 /* Opcode: Clear P1 P2 P3
63061 **
63062 ** Delete all contents of the database table or index whose root page
63063 ** in the database file is given by P1.  But, unlike Destroy, do not
63064 ** remove the table or index from the database file.
63065 **
63066 ** The table being clear is in the main database file if P2==0.  If
63067 ** P2==1 then the table to be clear is in the auxiliary database file
63068 ** that is used to store tables create using CREATE TEMPORARY TABLE.
63069 **
63070 ** If the P3 value is non-zero, then the table referred to must be an
63071 ** intkey table (an SQL table, not an index). In this case the row change 
63072 ** count is incremented by the number of rows in the table being cleared. 
63073 ** If P3 is greater than zero, then the value stored in register P3 is
63074 ** also incremented by the number of rows in the table being cleared.
63075 **
63076 ** See also: Destroy
63077 */
63078 case OP_Clear: {
63079 #if 0  /* local variables moved into u.bs */
63080   int nChange;
63081 #endif /* local variables moved into u.bs */
63082
63083   u.bs.nChange = 0;
63084   assert( (p->btreeMask & (1<<pOp->p2))!=0 );
63085   rc = sqlite3BtreeClearTable(
63086       db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bs.nChange : 0)
63087   );
63088   if( pOp->p3 ){
63089     p->nChange += u.bs.nChange;
63090     if( pOp->p3>0 ){
63091       aMem[pOp->p3].u.i += u.bs.nChange;
63092     }
63093   }
63094   break;
63095 }
63096
63097 /* Opcode: CreateTable P1 P2 * * *
63098 **
63099 ** Allocate a new table in the main database file if P1==0 or in the
63100 ** auxiliary database file if P1==1 or in an attached database if
63101 ** P1>1.  Write the root page number of the new table into
63102 ** register P2
63103 **
63104 ** The difference between a table and an index is this:  A table must
63105 ** have a 4-byte integer key and can have arbitrary data.  An index
63106 ** has an arbitrary key but no data.
63107 **
63108 ** See also: CreateIndex
63109 */
63110 /* Opcode: CreateIndex P1 P2 * * *
63111 **
63112 ** Allocate a new index in the main database file if P1==0 or in the
63113 ** auxiliary database file if P1==1 or in an attached database if
63114 ** P1>1.  Write the root page number of the new table into
63115 ** register P2.
63116 **
63117 ** See documentation on OP_CreateTable for additional information.
63118 */
63119 case OP_CreateIndex:            /* out2-prerelease */
63120 case OP_CreateTable: {          /* out2-prerelease */
63121 #if 0  /* local variables moved into u.bt */
63122   int pgno;
63123   int flags;
63124   Db *pDb;
63125 #endif /* local variables moved into u.bt */
63126
63127   u.bt.pgno = 0;
63128   assert( pOp->p1>=0 && pOp->p1<db->nDb );
63129   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
63130   u.bt.pDb = &db->aDb[pOp->p1];
63131   assert( u.bt.pDb->pBt!=0 );
63132   if( pOp->opcode==OP_CreateTable ){
63133     /* u.bt.flags = BTREE_INTKEY; */
63134     u.bt.flags = BTREE_LEAFDATA|BTREE_INTKEY;
63135   }else{
63136     u.bt.flags = BTREE_ZERODATA;
63137   }
63138   rc = sqlite3BtreeCreateTable(u.bt.pDb->pBt, &u.bt.pgno, u.bt.flags);
63139   pOut->u.i = u.bt.pgno;
63140   break;
63141 }
63142
63143 /* Opcode: ParseSchema P1 P2 * P4 *
63144 **
63145 ** Read and parse all entries from the SQLITE_MASTER table of database P1
63146 ** that match the WHERE clause P4.  P2 is the "force" flag.   Always do
63147 ** the parsing if P2 is true.  If P2 is false, then this routine is a
63148 ** no-op if the schema is not currently loaded.  In other words, if P2
63149 ** is false, the SQLITE_MASTER table is only parsed if the rest of the
63150 ** schema is already loaded into the symbol table.
63151 **
63152 ** This opcode invokes the parser to create a new virtual machine,
63153 ** then runs the new virtual machine.  It is thus a re-entrant opcode.
63154 */
63155 case OP_ParseSchema: {
63156 #if 0  /* local variables moved into u.bu */
63157   int iDb;
63158   const char *zMaster;
63159   char *zSql;
63160   InitData initData;
63161 #endif /* local variables moved into u.bu */
63162
63163   u.bu.iDb = pOp->p1;
63164   assert( u.bu.iDb>=0 && u.bu.iDb<db->nDb );
63165
63166   /* If pOp->p2 is 0, then this opcode is being executed to read a
63167   ** single row, for example the row corresponding to a new index
63168   ** created by this VDBE, from the sqlite_master table. It only
63169   ** does this if the corresponding in-memory schema is currently
63170   ** loaded. Otherwise, the new index definition can be loaded along
63171   ** with the rest of the schema when it is required.
63172   **
63173   ** Although the mutex on the BtShared object that corresponds to
63174   ** database u.bu.iDb (the database containing the sqlite_master table
63175   ** read by this instruction) is currently held, it is necessary to
63176   ** obtain the mutexes on all attached databases before checking if
63177   ** the schema of u.bu.iDb is loaded. This is because, at the start of
63178   ** the sqlite3_exec() call below, SQLite will invoke
63179   ** sqlite3BtreeEnterAll(). If all mutexes are not already held, the
63180   ** u.bu.iDb mutex may be temporarily released to avoid deadlock. If
63181   ** this happens, then some other thread may delete the in-memory
63182   ** schema of database u.bu.iDb before the SQL statement runs. The schema
63183   ** will not be reloaded becuase the db->init.busy flag is set. This
63184   ** can result in a "no such table: sqlite_master" or "malformed
63185   ** database schema" error being returned to the user.
63186   */
63187   assert( sqlite3BtreeHoldsMutex(db->aDb[u.bu.iDb].pBt) );
63188   sqlite3BtreeEnterAll(db);
63189   if( pOp->p2 || DbHasProperty(db, u.bu.iDb, DB_SchemaLoaded) ){
63190     u.bu.zMaster = SCHEMA_TABLE(u.bu.iDb);
63191     u.bu.initData.db = db;
63192     u.bu.initData.iDb = pOp->p1;
63193     u.bu.initData.pzErrMsg = &p->zErrMsg;
63194     u.bu.zSql = sqlite3MPrintf(db,
63195        "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
63196        db->aDb[u.bu.iDb].zName, u.bu.zMaster, pOp->p4.z);
63197     if( u.bu.zSql==0 ){
63198       rc = SQLITE_NOMEM;
63199     }else{
63200       assert( db->init.busy==0 );
63201       db->init.busy = 1;
63202       u.bu.initData.rc = SQLITE_OK;
63203       assert( !db->mallocFailed );
63204       rc = sqlite3_exec(db, u.bu.zSql, sqlite3InitCallback, &u.bu.initData, 0);
63205       if( rc==SQLITE_OK ) rc = u.bu.initData.rc;
63206       sqlite3DbFree(db, u.bu.zSql);
63207       db->init.busy = 0;
63208     }
63209   }
63210   sqlite3BtreeLeaveAll(db);
63211   if( rc==SQLITE_NOMEM ){
63212     goto no_mem;
63213   }
63214   break;
63215 }
63216
63217 #if !defined(SQLITE_OMIT_ANALYZE)
63218 /* Opcode: LoadAnalysis P1 * * * *
63219 **
63220 ** Read the sqlite_stat1 table for database P1 and load the content
63221 ** of that table into the internal index hash table.  This will cause
63222 ** the analysis to be used when preparing all subsequent queries.
63223 */
63224 case OP_LoadAnalysis: {
63225   assert( pOp->p1>=0 && pOp->p1<db->nDb );
63226   rc = sqlite3AnalysisLoad(db, pOp->p1);
63227   break;  
63228 }
63229 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
63230
63231 /* Opcode: DropTable P1 * * P4 *
63232 **
63233 ** Remove the internal (in-memory) data structures that describe
63234 ** the table named P4 in database P1.  This is called after a table
63235 ** is dropped in order to keep the internal representation of the
63236 ** schema consistent with what is on disk.
63237 */
63238 case OP_DropTable: {
63239   sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
63240   break;
63241 }
63242
63243 /* Opcode: DropIndex P1 * * P4 *
63244 **
63245 ** Remove the internal (in-memory) data structures that describe
63246 ** the index named P4 in database P1.  This is called after an index
63247 ** is dropped in order to keep the internal representation of the
63248 ** schema consistent with what is on disk.
63249 */
63250 case OP_DropIndex: {
63251   sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
63252   break;
63253 }
63254
63255 /* Opcode: DropTrigger P1 * * P4 *
63256 **
63257 ** Remove the internal (in-memory) data structures that describe
63258 ** the trigger named P4 in database P1.  This is called after a trigger
63259 ** is dropped in order to keep the internal representation of the
63260 ** schema consistent with what is on disk.
63261 */
63262 case OP_DropTrigger: {
63263   sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
63264   break;
63265 }
63266
63267
63268 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
63269 /* Opcode: IntegrityCk P1 P2 P3 * P5
63270 **
63271 ** Do an analysis of the currently open database.  Store in
63272 ** register P1 the text of an error message describing any problems.
63273 ** If no problems are found, store a NULL in register P1.
63274 **
63275 ** The register P3 contains the maximum number of allowed errors.
63276 ** At most reg(P3) errors will be reported.
63277 ** In other words, the analysis stops as soon as reg(P1) errors are 
63278 ** seen.  Reg(P1) is updated with the number of errors remaining.
63279 **
63280 ** The root page numbers of all tables in the database are integer
63281 ** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
63282 ** total.
63283 **
63284 ** If P5 is not zero, the check is done on the auxiliary database
63285 ** file, not the main database file.
63286 **
63287 ** This opcode is used to implement the integrity_check pragma.
63288 */
63289 case OP_IntegrityCk: {
63290 #if 0  /* local variables moved into u.bv */
63291   int nRoot;      /* Number of tables to check.  (Number of root pages.) */
63292   int *aRoot;     /* Array of rootpage numbers for tables to be checked */
63293   int j;          /* Loop counter */
63294   int nErr;       /* Number of errors reported */
63295   char *z;        /* Text of the error report */
63296   Mem *pnErr;     /* Register keeping track of errors remaining */
63297 #endif /* local variables moved into u.bv */
63298
63299   u.bv.nRoot = pOp->p2;
63300   assert( u.bv.nRoot>0 );
63301   u.bv.aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(u.bv.nRoot+1) );
63302   if( u.bv.aRoot==0 ) goto no_mem;
63303   assert( pOp->p3>0 && pOp->p3<=p->nMem );
63304   u.bv.pnErr = &aMem[pOp->p3];
63305   assert( (u.bv.pnErr->flags & MEM_Int)!=0 );
63306   assert( (u.bv.pnErr->flags & (MEM_Str|MEM_Blob))==0 );
63307   pIn1 = &aMem[pOp->p1];
63308   for(u.bv.j=0; u.bv.j<u.bv.nRoot; u.bv.j++){
63309     u.bv.aRoot[u.bv.j] = (int)sqlite3VdbeIntValue(&pIn1[u.bv.j]);
63310   }
63311   u.bv.aRoot[u.bv.j] = 0;
63312   assert( pOp->p5<db->nDb );
63313   assert( (p->btreeMask & (1<<pOp->p5))!=0 );
63314   u.bv.z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, u.bv.aRoot, u.bv.nRoot,
63315                                  (int)u.bv.pnErr->u.i, &u.bv.nErr);
63316   sqlite3DbFree(db, u.bv.aRoot);
63317   u.bv.pnErr->u.i -= u.bv.nErr;
63318   sqlite3VdbeMemSetNull(pIn1);
63319   if( u.bv.nErr==0 ){
63320     assert( u.bv.z==0 );
63321   }else if( u.bv.z==0 ){
63322     goto no_mem;
63323   }else{
63324     sqlite3VdbeMemSetStr(pIn1, u.bv.z, -1, SQLITE_UTF8, sqlite3_free);
63325   }
63326   UPDATE_MAX_BLOBSIZE(pIn1);
63327   sqlite3VdbeChangeEncoding(pIn1, encoding);
63328   break;
63329 }
63330 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
63331
63332 /* Opcode: RowSetAdd P1 P2 * * *
63333 **
63334 ** Insert the integer value held by register P2 into a boolean index
63335 ** held in register P1.
63336 **
63337 ** An assertion fails if P2 is not an integer.
63338 */
63339 case OP_RowSetAdd: {       /* in1, in2 */
63340   pIn1 = &aMem[pOp->p1];
63341   pIn2 = &aMem[pOp->p2];
63342   assert( (pIn2->flags & MEM_Int)!=0 );
63343   if( (pIn1->flags & MEM_RowSet)==0 ){
63344     sqlite3VdbeMemSetRowSet(pIn1);
63345     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
63346   }
63347   sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
63348   break;
63349 }
63350
63351 /* Opcode: RowSetRead P1 P2 P3 * *
63352 **
63353 ** Extract the smallest value from boolean index P1 and put that value into
63354 ** register P3.  Or, if boolean index P1 is initially empty, leave P3
63355 ** unchanged and jump to instruction P2.
63356 */
63357 case OP_RowSetRead: {       /* jump, in1, out3 */
63358 #if 0  /* local variables moved into u.bw */
63359   i64 val;
63360 #endif /* local variables moved into u.bw */
63361   CHECK_FOR_INTERRUPT;
63362   pIn1 = &aMem[pOp->p1];
63363   if( (pIn1->flags & MEM_RowSet)==0
63364    || sqlite3RowSetNext(pIn1->u.pRowSet, &u.bw.val)==0
63365   ){
63366     /* The boolean index is empty */
63367     sqlite3VdbeMemSetNull(pIn1);
63368     pc = pOp->p2 - 1;
63369   }else{
63370     /* A value was pulled from the index */
63371     sqlite3VdbeMemSetInt64(&aMem[pOp->p3], u.bw.val);
63372   }
63373   break;
63374 }
63375
63376 /* Opcode: RowSetTest P1 P2 P3 P4
63377 **
63378 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
63379 ** contains a RowSet object and that RowSet object contains
63380 ** the value held in P3, jump to register P2. Otherwise, insert the
63381 ** integer in P3 into the RowSet and continue on to the
63382 ** next opcode.
63383 **
63384 ** The RowSet object is optimized for the case where successive sets
63385 ** of integers, where each set contains no duplicates. Each set
63386 ** of values is identified by a unique P4 value. The first set
63387 ** must have P4==0, the final set P4=-1.  P4 must be either -1 or
63388 ** non-negative.  For non-negative values of P4 only the lower 4
63389 ** bits are significant.
63390 **
63391 ** This allows optimizations: (a) when P4==0 there is no need to test
63392 ** the rowset object for P3, as it is guaranteed not to contain it,
63393 ** (b) when P4==-1 there is no need to insert the value, as it will
63394 ** never be tested for, and (c) when a value that is part of set X is
63395 ** inserted, there is no need to search to see if the same value was
63396 ** previously inserted as part of set X (only if it was previously
63397 ** inserted as part of some other set).
63398 */
63399 case OP_RowSetTest: {                     /* jump, in1, in3 */
63400 #if 0  /* local variables moved into u.bx */
63401   int iSet;
63402   int exists;
63403 #endif /* local variables moved into u.bx */
63404
63405   pIn1 = &aMem[pOp->p1];
63406   pIn3 = &aMem[pOp->p3];
63407   u.bx.iSet = pOp->p4.i;
63408   assert( pIn3->flags&MEM_Int );
63409
63410   /* If there is anything other than a rowset object in memory cell P1,
63411   ** delete it now and initialize P1 with an empty rowset
63412   */
63413   if( (pIn1->flags & MEM_RowSet)==0 ){
63414     sqlite3VdbeMemSetRowSet(pIn1);
63415     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
63416   }
63417
63418   assert( pOp->p4type==P4_INT32 );
63419   assert( u.bx.iSet==-1 || u.bx.iSet>=0 );
63420   if( u.bx.iSet ){
63421     u.bx.exists = sqlite3RowSetTest(pIn1->u.pRowSet,
63422                                (u8)(u.bx.iSet>=0 ? u.bx.iSet & 0xf : 0xff),
63423                                pIn3->u.i);
63424     if( u.bx.exists ){
63425       pc = pOp->p2 - 1;
63426       break;
63427     }
63428   }
63429   if( u.bx.iSet>=0 ){
63430     sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
63431   }
63432   break;
63433 }
63434
63435
63436 #ifndef SQLITE_OMIT_TRIGGER
63437
63438 /* Opcode: Program P1 P2 P3 P4 *
63439 **
63440 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM). 
63441 **
63442 ** P1 contains the address of the memory cell that contains the first memory 
63443 ** cell in an array of values used as arguments to the sub-program. P2 
63444 ** contains the address to jump to if the sub-program throws an IGNORE 
63445 ** exception using the RAISE() function. Register P3 contains the address 
63446 ** of a memory cell in this (the parent) VM that is used to allocate the 
63447 ** memory required by the sub-vdbe at runtime.
63448 **
63449 ** P4 is a pointer to the VM containing the trigger program.
63450 */
63451 case OP_Program: {        /* jump */
63452 #if 0  /* local variables moved into u.by */
63453   int nMem;               /* Number of memory registers for sub-program */
63454   int nByte;              /* Bytes of runtime space required for sub-program */
63455   Mem *pRt;               /* Register to allocate runtime space */
63456   Mem *pMem;              /* Used to iterate through memory cells */
63457   Mem *pEnd;              /* Last memory cell in new array */
63458   VdbeFrame *pFrame;      /* New vdbe frame to execute in */
63459   SubProgram *pProgram;   /* Sub-program to execute */
63460   void *t;                /* Token identifying trigger */
63461 #endif /* local variables moved into u.by */
63462
63463   u.by.pProgram = pOp->p4.pProgram;
63464   u.by.pRt = &aMem[pOp->p3];
63465   assert( u.by.pProgram->nOp>0 );
63466
63467   /* If the p5 flag is clear, then recursive invocation of triggers is
63468   ** disabled for backwards compatibility (p5 is set if this sub-program
63469   ** is really a trigger, not a foreign key action, and the flag set
63470   ** and cleared by the "PRAGMA recursive_triggers" command is clear).
63471   **
63472   ** It is recursive invocation of triggers, at the SQL level, that is
63473   ** disabled. In some cases a single trigger may generate more than one
63474   ** SubProgram (if the trigger may be executed with more than one different
63475   ** ON CONFLICT algorithm). SubProgram structures associated with a
63476   ** single trigger all have the same value for the SubProgram.token
63477   ** variable.  */
63478   if( pOp->p5 ){
63479     u.by.t = u.by.pProgram->token;
63480     for(u.by.pFrame=p->pFrame; u.by.pFrame && u.by.pFrame->token!=u.by.t; u.by.pFrame=u.by.pFrame->pParent);
63481     if( u.by.pFrame ) break;
63482   }
63483
63484   if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
63485     rc = SQLITE_ERROR;
63486     sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
63487     break;
63488   }
63489
63490   /* Register u.by.pRt is used to store the memory required to save the state
63491   ** of the current program, and the memory required at runtime to execute
63492   ** the trigger program. If this trigger has been fired before, then u.by.pRt
63493   ** is already allocated. Otherwise, it must be initialized.  */
63494   if( (u.by.pRt->flags&MEM_Frame)==0 ){
63495     /* SubProgram.nMem is set to the number of memory cells used by the
63496     ** program stored in SubProgram.aOp. As well as these, one memory
63497     ** cell is required for each cursor used by the program. Set local
63498     ** variable u.by.nMem (and later, VdbeFrame.nChildMem) to this value.
63499     */
63500     u.by.nMem = u.by.pProgram->nMem + u.by.pProgram->nCsr;
63501     u.by.nByte = ROUND8(sizeof(VdbeFrame))
63502               + u.by.nMem * sizeof(Mem)
63503               + u.by.pProgram->nCsr * sizeof(VdbeCursor *);
63504     u.by.pFrame = sqlite3DbMallocZero(db, u.by.nByte);
63505     if( !u.by.pFrame ){
63506       goto no_mem;
63507     }
63508     sqlite3VdbeMemRelease(u.by.pRt);
63509     u.by.pRt->flags = MEM_Frame;
63510     u.by.pRt->u.pFrame = u.by.pFrame;
63511
63512     u.by.pFrame->v = p;
63513     u.by.pFrame->nChildMem = u.by.nMem;
63514     u.by.pFrame->nChildCsr = u.by.pProgram->nCsr;
63515     u.by.pFrame->pc = pc;
63516     u.by.pFrame->aMem = p->aMem;
63517     u.by.pFrame->nMem = p->nMem;
63518     u.by.pFrame->apCsr = p->apCsr;
63519     u.by.pFrame->nCursor = p->nCursor;
63520     u.by.pFrame->aOp = p->aOp;
63521     u.by.pFrame->nOp = p->nOp;
63522     u.by.pFrame->token = u.by.pProgram->token;
63523
63524     u.by.pEnd = &VdbeFrameMem(u.by.pFrame)[u.by.pFrame->nChildMem];
63525     for(u.by.pMem=VdbeFrameMem(u.by.pFrame); u.by.pMem!=u.by.pEnd; u.by.pMem++){
63526       u.by.pMem->flags = MEM_Null;
63527       u.by.pMem->db = db;
63528     }
63529   }else{
63530     u.by.pFrame = u.by.pRt->u.pFrame;
63531     assert( u.by.pProgram->nMem+u.by.pProgram->nCsr==u.by.pFrame->nChildMem );
63532     assert( u.by.pProgram->nCsr==u.by.pFrame->nChildCsr );
63533     assert( pc==u.by.pFrame->pc );
63534   }
63535
63536   p->nFrame++;
63537   u.by.pFrame->pParent = p->pFrame;
63538   u.by.pFrame->lastRowid = db->lastRowid;
63539   u.by.pFrame->nChange = p->nChange;
63540   p->nChange = 0;
63541   p->pFrame = u.by.pFrame;
63542   p->aMem = aMem = &VdbeFrameMem(u.by.pFrame)[-1];
63543   p->nMem = u.by.pFrame->nChildMem;
63544   p->nCursor = (u16)u.by.pFrame->nChildCsr;
63545   p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
63546   p->aOp = aOp = u.by.pProgram->aOp;
63547   p->nOp = u.by.pProgram->nOp;
63548   pc = -1;
63549
63550   break;
63551 }
63552
63553 /* Opcode: Param P1 P2 * * *
63554 **
63555 ** This opcode is only ever present in sub-programs called via the 
63556 ** OP_Program instruction. Copy a value currently stored in a memory 
63557 ** cell of the calling (parent) frame to cell P2 in the current frames 
63558 ** address space. This is used by trigger programs to access the new.* 
63559 ** and old.* values.
63560 **
63561 ** The address of the cell in the parent frame is determined by adding
63562 ** the value of the P1 argument to the value of the P1 argument to the
63563 ** calling OP_Program instruction.
63564 */
63565 case OP_Param: {           /* out2-prerelease */
63566 #if 0  /* local variables moved into u.bz */
63567   VdbeFrame *pFrame;
63568   Mem *pIn;
63569 #endif /* local variables moved into u.bz */
63570   u.bz.pFrame = p->pFrame;
63571   u.bz.pIn = &u.bz.pFrame->aMem[pOp->p1 + u.bz.pFrame->aOp[u.bz.pFrame->pc].p1];
63572   sqlite3VdbeMemShallowCopy(pOut, u.bz.pIn, MEM_Ephem);
63573   break;
63574 }
63575
63576 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
63577
63578 #ifndef SQLITE_OMIT_FOREIGN_KEY
63579 /* Opcode: FkCounter P1 P2 * * *
63580 **
63581 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
63582 ** If P1 is non-zero, the database constraint counter is incremented 
63583 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the 
63584 ** statement counter is incremented (immediate foreign key constraints).
63585 */
63586 case OP_FkCounter: {
63587   if( pOp->p1 ){
63588     db->nDeferredCons += pOp->p2;
63589   }else{
63590     p->nFkConstraint += pOp->p2;
63591   }
63592   break;
63593 }
63594
63595 /* Opcode: FkIfZero P1 P2 * * *
63596 **
63597 ** This opcode tests if a foreign key constraint-counter is currently zero.
63598 ** If so, jump to instruction P2. Otherwise, fall through to the next 
63599 ** instruction.
63600 **
63601 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
63602 ** is zero (the one that counts deferred constraint violations). If P1 is
63603 ** zero, the jump is taken if the statement constraint-counter is zero
63604 ** (immediate foreign key constraint violations).
63605 */
63606 case OP_FkIfZero: {         /* jump */
63607   if( pOp->p1 ){
63608     if( db->nDeferredCons==0 ) pc = pOp->p2-1;
63609   }else{
63610     if( p->nFkConstraint==0 ) pc = pOp->p2-1;
63611   }
63612   break;
63613 }
63614 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
63615
63616 #ifndef SQLITE_OMIT_AUTOINCREMENT
63617 /* Opcode: MemMax P1 P2 * * *
63618 **
63619 ** P1 is a register in the root frame of this VM (the root frame is
63620 ** different from the current frame if this instruction is being executed
63621 ** within a sub-program). Set the value of register P1 to the maximum of 
63622 ** its current value and the value in register P2.
63623 **
63624 ** This instruction throws an error if the memory cell is not initially
63625 ** an integer.
63626 */
63627 case OP_MemMax: {        /* in2 */
63628 #if 0  /* local variables moved into u.ca */
63629   Mem *pIn1;
63630   VdbeFrame *pFrame;
63631 #endif /* local variables moved into u.ca */
63632   if( p->pFrame ){
63633     for(u.ca.pFrame=p->pFrame; u.ca.pFrame->pParent; u.ca.pFrame=u.ca.pFrame->pParent);
63634     u.ca.pIn1 = &u.ca.pFrame->aMem[pOp->p1];
63635   }else{
63636     u.ca.pIn1 = &aMem[pOp->p1];
63637   }
63638   sqlite3VdbeMemIntegerify(u.ca.pIn1);
63639   pIn2 = &aMem[pOp->p2];
63640   sqlite3VdbeMemIntegerify(pIn2);
63641   if( u.ca.pIn1->u.i<pIn2->u.i){
63642     u.ca.pIn1->u.i = pIn2->u.i;
63643   }
63644   break;
63645 }
63646 #endif /* SQLITE_OMIT_AUTOINCREMENT */
63647
63648 /* Opcode: IfPos P1 P2 * * *
63649 **
63650 ** If the value of register P1 is 1 or greater, jump to P2.
63651 **
63652 ** It is illegal to use this instruction on a register that does
63653 ** not contain an integer.  An assertion fault will result if you try.
63654 */
63655 case OP_IfPos: {        /* jump, in1 */
63656   pIn1 = &aMem[pOp->p1];
63657   assert( pIn1->flags&MEM_Int );
63658   if( pIn1->u.i>0 ){
63659      pc = pOp->p2 - 1;
63660   }
63661   break;
63662 }
63663
63664 /* Opcode: IfNeg P1 P2 * * *
63665 **
63666 ** If the value of register P1 is less than zero, jump to P2. 
63667 **
63668 ** It is illegal to use this instruction on a register that does
63669 ** not contain an integer.  An assertion fault will result if you try.
63670 */
63671 case OP_IfNeg: {        /* jump, in1 */
63672   pIn1 = &aMem[pOp->p1];
63673   assert( pIn1->flags&MEM_Int );
63674   if( pIn1->u.i<0 ){
63675      pc = pOp->p2 - 1;
63676   }
63677   break;
63678 }
63679
63680 /* Opcode: IfZero P1 P2 P3 * *
63681 **
63682 ** The register P1 must contain an integer.  Add literal P3 to the
63683 ** value in register P1.  If the result is exactly 0, jump to P2. 
63684 **
63685 ** It is illegal to use this instruction on a register that does
63686 ** not contain an integer.  An assertion fault will result if you try.
63687 */
63688 case OP_IfZero: {        /* jump, in1 */
63689   pIn1 = &aMem[pOp->p1];
63690   assert( pIn1->flags&MEM_Int );
63691   pIn1->u.i += pOp->p3;
63692   if( pIn1->u.i==0 ){
63693      pc = pOp->p2 - 1;
63694   }
63695   break;
63696 }
63697
63698 /* Opcode: AggStep * P2 P3 P4 P5
63699 **
63700 ** Execute the step function for an aggregate.  The
63701 ** function has P5 arguments.   P4 is a pointer to the FuncDef
63702 ** structure that specifies the function.  Use register
63703 ** P3 as the accumulator.
63704 **
63705 ** The P5 arguments are taken from register P2 and its
63706 ** successors.
63707 */
63708 case OP_AggStep: {
63709 #if 0  /* local variables moved into u.cb */
63710   int n;
63711   int i;
63712   Mem *pMem;
63713   Mem *pRec;
63714   sqlite3_context ctx;
63715   sqlite3_value **apVal;
63716 #endif /* local variables moved into u.cb */
63717
63718   u.cb.n = pOp->p5;
63719   assert( u.cb.n>=0 );
63720   u.cb.pRec = &aMem[pOp->p2];
63721   u.cb.apVal = p->apArg;
63722   assert( u.cb.apVal || u.cb.n==0 );
63723   for(u.cb.i=0; u.cb.i<u.cb.n; u.cb.i++, u.cb.pRec++){
63724     u.cb.apVal[u.cb.i] = u.cb.pRec;
63725     sqlite3VdbeMemStoreType(u.cb.pRec);
63726   }
63727   u.cb.ctx.pFunc = pOp->p4.pFunc;
63728   assert( pOp->p3>0 && pOp->p3<=p->nMem );
63729   u.cb.ctx.pMem = u.cb.pMem = &aMem[pOp->p3];
63730   u.cb.pMem->n++;
63731   u.cb.ctx.s.flags = MEM_Null;
63732   u.cb.ctx.s.z = 0;
63733   u.cb.ctx.s.zMalloc = 0;
63734   u.cb.ctx.s.xDel = 0;
63735   u.cb.ctx.s.db = db;
63736   u.cb.ctx.isError = 0;
63737   u.cb.ctx.pColl = 0;
63738   if( u.cb.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
63739     assert( pOp>p->aOp );
63740     assert( pOp[-1].p4type==P4_COLLSEQ );
63741     assert( pOp[-1].opcode==OP_CollSeq );
63742     u.cb.ctx.pColl = pOp[-1].p4.pColl;
63743   }
63744   (u.cb.ctx.pFunc->xStep)(&u.cb.ctx, u.cb.n, u.cb.apVal);
63745   if( u.cb.ctx.isError ){
63746     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.cb.ctx.s));
63747     rc = u.cb.ctx.isError;
63748   }
63749   sqlite3VdbeMemRelease(&u.cb.ctx.s);
63750   break;
63751 }
63752
63753 /* Opcode: AggFinal P1 P2 * P4 *
63754 **
63755 ** Execute the finalizer function for an aggregate.  P1 is
63756 ** the memory location that is the accumulator for the aggregate.
63757 **
63758 ** P2 is the number of arguments that the step function takes and
63759 ** P4 is a pointer to the FuncDef for this function.  The P2
63760 ** argument is not used by this opcode.  It is only there to disambiguate
63761 ** functions that can take varying numbers of arguments.  The
63762 ** P4 argument is only needed for the degenerate case where
63763 ** the step function was not previously called.
63764 */
63765 case OP_AggFinal: {
63766 #if 0  /* local variables moved into u.cc */
63767   Mem *pMem;
63768 #endif /* local variables moved into u.cc */
63769   assert( pOp->p1>0 && pOp->p1<=p->nMem );
63770   u.cc.pMem = &aMem[pOp->p1];
63771   assert( (u.cc.pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
63772   rc = sqlite3VdbeMemFinalize(u.cc.pMem, pOp->p4.pFunc);
63773   if( rc ){
63774     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(u.cc.pMem));
63775   }
63776   sqlite3VdbeChangeEncoding(u.cc.pMem, encoding);
63777   UPDATE_MAX_BLOBSIZE(u.cc.pMem);
63778   if( sqlite3VdbeMemTooBig(u.cc.pMem) ){
63779     goto too_big;
63780   }
63781   break;
63782 }
63783
63784 #ifndef SQLITE_OMIT_WAL
63785 /* Opcode: Checkpoint P1 * * * *
63786 **
63787 ** Checkpoint database P1. This is a no-op if P1 is not currently in
63788 ** WAL mode.
63789 */
63790 case OP_Checkpoint: {
63791   rc = sqlite3Checkpoint(db, pOp->p1);
63792   break;
63793 };  
63794 #endif
63795
63796 #ifndef SQLITE_OMIT_PRAGMA
63797 /* Opcode: JournalMode P1 P2 P3 * P5
63798 **
63799 ** Change the journal mode of database P1 to P3. P3 must be one of the
63800 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
63801 ** modes (delete, truncate, persist, off and memory), this is a simple
63802 ** operation. No IO is required.
63803 **
63804 ** If changing into or out of WAL mode the procedure is more complicated.
63805 **
63806 ** Write a string containing the final journal-mode to register P2.
63807 */
63808 case OP_JournalMode: {    /* out2-prerelease */
63809 #if 0  /* local variables moved into u.cd */
63810   Btree *pBt;                     /* Btree to change journal mode of */
63811   Pager *pPager;                  /* Pager associated with pBt */
63812   int eNew;                       /* New journal mode */
63813   int eOld;                       /* The old journal mode */
63814   const char *zFilename;          /* Name of database file for pPager */
63815 #endif /* local variables moved into u.cd */
63816
63817   u.cd.eNew = pOp->p3;
63818   assert( u.cd.eNew==PAGER_JOURNALMODE_DELETE
63819        || u.cd.eNew==PAGER_JOURNALMODE_TRUNCATE
63820        || u.cd.eNew==PAGER_JOURNALMODE_PERSIST
63821        || u.cd.eNew==PAGER_JOURNALMODE_OFF
63822        || u.cd.eNew==PAGER_JOURNALMODE_MEMORY
63823        || u.cd.eNew==PAGER_JOURNALMODE_WAL
63824        || u.cd.eNew==PAGER_JOURNALMODE_QUERY
63825   );
63826   assert( pOp->p1>=0 && pOp->p1<db->nDb );
63827
63828   /* This opcode is used in two places: PRAGMA journal_mode and ATTACH.
63829   ** In PRAGMA journal_mode, the sqlite3VdbeUsesBtree() routine is called
63830   ** when the statment is prepared and so p->aMutex.nMutex>0.  All mutexes
63831   ** are already acquired.  But when used in ATTACH, sqlite3VdbeUsesBtree()
63832   ** is not called when the statement is prepared because it requires the
63833   ** iDb index of the database as a parameter, and the database has not
63834   ** yet been attached so that index is unavailable.  We have to wait
63835   ** until runtime (now) to get the mutex on the newly attached database.
63836   ** No other mutexes are required by the ATTACH command so this is safe
63837   ** to do.
63838   */
63839   assert( (p->btreeMask & (1<<pOp->p1))!=0 || p->aMutex.nMutex==0 );
63840   if( p->aMutex.nMutex==0 ){
63841     /* This occurs right after ATTACH.  Get a mutex on the newly ATTACHed
63842     ** database. */
63843     sqlite3VdbeUsesBtree(p, pOp->p1);
63844     sqlite3VdbeMutexArrayEnter(p);
63845   }
63846
63847   u.cd.pBt = db->aDb[pOp->p1].pBt;
63848   u.cd.pPager = sqlite3BtreePager(u.cd.pBt);
63849   u.cd.eOld = sqlite3PagerGetJournalMode(u.cd.pPager);
63850   if( u.cd.eNew==PAGER_JOURNALMODE_QUERY ) u.cd.eNew = u.cd.eOld;
63851   if( !sqlite3PagerOkToChangeJournalMode(u.cd.pPager) ) u.cd.eNew = u.cd.eOld;
63852
63853 #ifndef SQLITE_OMIT_WAL
63854   u.cd.zFilename = sqlite3PagerFilename(u.cd.pPager);
63855
63856   /* Do not allow a transition to journal_mode=WAL for a database
63857   ** in temporary storage or if the VFS does not support shared memory
63858   */
63859   if( u.cd.eNew==PAGER_JOURNALMODE_WAL
63860    && (u.cd.zFilename[0]==0                         /* Temp file */
63861        || !sqlite3PagerWalSupported(u.cd.pPager))   /* No shared-memory support */
63862   ){
63863     u.cd.eNew = u.cd.eOld;
63864   }
63865
63866   if( (u.cd.eNew!=u.cd.eOld)
63867    && (u.cd.eOld==PAGER_JOURNALMODE_WAL || u.cd.eNew==PAGER_JOURNALMODE_WAL)
63868   ){
63869     if( !db->autoCommit || db->activeVdbeCnt>1 ){
63870       rc = SQLITE_ERROR;
63871       sqlite3SetString(&p->zErrMsg, db,
63872           "cannot change %s wal mode from within a transaction",
63873           (u.cd.eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
63874       );
63875       break;
63876     }else{
63877
63878       if( u.cd.eOld==PAGER_JOURNALMODE_WAL ){
63879         /* If leaving WAL mode, close the log file. If successful, the call
63880         ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
63881         ** file. An EXCLUSIVE lock may still be held on the database file
63882         ** after a successful return.
63883         */
63884         rc = sqlite3PagerCloseWal(u.cd.pPager);
63885         if( rc==SQLITE_OK ){
63886           sqlite3PagerSetJournalMode(u.cd.pPager, u.cd.eNew);
63887         }
63888       }else if( u.cd.eOld==PAGER_JOURNALMODE_MEMORY ){
63889         /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
63890         ** as an intermediate */
63891         sqlite3PagerSetJournalMode(u.cd.pPager, PAGER_JOURNALMODE_OFF);
63892       }
63893
63894       /* Open a transaction on the database file. Regardless of the journal
63895       ** mode, this transaction always uses a rollback journal.
63896       */
63897       assert( sqlite3BtreeIsInTrans(u.cd.pBt)==0 );
63898       if( rc==SQLITE_OK ){
63899         rc = sqlite3BtreeSetVersion(u.cd.pBt, (u.cd.eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
63900       }
63901     }
63902   }
63903 #endif /* ifndef SQLITE_OMIT_WAL */
63904
63905   if( rc ){
63906     u.cd.eNew = u.cd.eOld;
63907   }
63908   u.cd.eNew = sqlite3PagerSetJournalMode(u.cd.pPager, u.cd.eNew);
63909
63910   pOut = &aMem[pOp->p2];
63911   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
63912   pOut->z = (char *)sqlite3JournalModename(u.cd.eNew);
63913   pOut->n = sqlite3Strlen30(pOut->z);
63914   pOut->enc = SQLITE_UTF8;
63915   sqlite3VdbeChangeEncoding(pOut, encoding);
63916   break;
63917 };
63918 #endif /* SQLITE_OMIT_PRAGMA */
63919
63920 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
63921 /* Opcode: Vacuum * * * * *
63922 **
63923 ** Vacuum the entire database.  This opcode will cause other virtual
63924 ** machines to be created and run.  It may not be called from within
63925 ** a transaction.
63926 */
63927 case OP_Vacuum: {
63928   rc = sqlite3RunVacuum(&p->zErrMsg, db);
63929   break;
63930 }
63931 #endif
63932
63933 #if !defined(SQLITE_OMIT_AUTOVACUUM)
63934 /* Opcode: IncrVacuum P1 P2 * * *
63935 **
63936 ** Perform a single step of the incremental vacuum procedure on
63937 ** the P1 database. If the vacuum has finished, jump to instruction
63938 ** P2. Otherwise, fall through to the next instruction.
63939 */
63940 case OP_IncrVacuum: {        /* jump */
63941 #if 0  /* local variables moved into u.ce */
63942   Btree *pBt;
63943 #endif /* local variables moved into u.ce */
63944
63945   assert( pOp->p1>=0 && pOp->p1<db->nDb );
63946   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
63947   u.ce.pBt = db->aDb[pOp->p1].pBt;
63948   rc = sqlite3BtreeIncrVacuum(u.ce.pBt);
63949   if( rc==SQLITE_DONE ){
63950     pc = pOp->p2 - 1;
63951     rc = SQLITE_OK;
63952   }
63953   break;
63954 }
63955 #endif
63956
63957 /* Opcode: Expire P1 * * * *
63958 **
63959 ** Cause precompiled statements to become expired. An expired statement
63960 ** fails with an error code of SQLITE_SCHEMA if it is ever executed 
63961 ** (via sqlite3_step()).
63962 ** 
63963 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
63964 ** then only the currently executing statement is affected. 
63965 */
63966 case OP_Expire: {
63967   if( !pOp->p1 ){
63968     sqlite3ExpirePreparedStatements(db);
63969   }else{
63970     p->expired = 1;
63971   }
63972   break;
63973 }
63974
63975 #ifndef SQLITE_OMIT_SHARED_CACHE
63976 /* Opcode: TableLock P1 P2 P3 P4 *
63977 **
63978 ** Obtain a lock on a particular table. This instruction is only used when
63979 ** the shared-cache feature is enabled. 
63980 **
63981 ** P1 is the index of the database in sqlite3.aDb[] of the database
63982 ** on which the lock is acquired.  A readlock is obtained if P3==0 or
63983 ** a write lock if P3==1.
63984 **
63985 ** P2 contains the root-page of the table to lock.
63986 **
63987 ** P4 contains a pointer to the name of the table being locked. This is only
63988 ** used to generate an error message if the lock cannot be obtained.
63989 */
63990 case OP_TableLock: {
63991   u8 isWriteLock = (u8)pOp->p3;
63992   if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
63993     int p1 = pOp->p1; 
63994     assert( p1>=0 && p1<db->nDb );
63995     assert( (p->btreeMask & (1<<p1))!=0 );
63996     assert( isWriteLock==0 || isWriteLock==1 );
63997     rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
63998     if( (rc&0xFF)==SQLITE_LOCKED ){
63999       const char *z = pOp->p4.z;
64000       sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
64001     }
64002   }
64003   break;
64004 }
64005 #endif /* SQLITE_OMIT_SHARED_CACHE */
64006
64007 #ifndef SQLITE_OMIT_VIRTUALTABLE
64008 /* Opcode: VBegin * * * P4 *
64009 **
64010 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the 
64011 ** xBegin method for that table.
64012 **
64013 ** Also, whether or not P4 is set, check that this is not being called from
64014 ** within a callback to a virtual table xSync() method. If it is, the error
64015 ** code will be set to SQLITE_LOCKED.
64016 */
64017 case OP_VBegin: {
64018 #if 0  /* local variables moved into u.cf */
64019   VTable *pVTab;
64020 #endif /* local variables moved into u.cf */
64021   u.cf.pVTab = pOp->p4.pVtab;
64022   rc = sqlite3VtabBegin(db, u.cf.pVTab);
64023   if( u.cf.pVTab ){
64024     sqlite3DbFree(db, p->zErrMsg);
64025     p->zErrMsg = u.cf.pVTab->pVtab->zErrMsg;
64026     u.cf.pVTab->pVtab->zErrMsg = 0;
64027   }
64028   break;
64029 }
64030 #endif /* SQLITE_OMIT_VIRTUALTABLE */
64031
64032 #ifndef SQLITE_OMIT_VIRTUALTABLE
64033 /* Opcode: VCreate P1 * * P4 *
64034 **
64035 ** P4 is the name of a virtual table in database P1. Call the xCreate method
64036 ** for that table.
64037 */
64038 case OP_VCreate: {
64039   rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
64040   break;
64041 }
64042 #endif /* SQLITE_OMIT_VIRTUALTABLE */
64043
64044 #ifndef SQLITE_OMIT_VIRTUALTABLE
64045 /* Opcode: VDestroy P1 * * P4 *
64046 **
64047 ** P4 is the name of a virtual table in database P1.  Call the xDestroy method
64048 ** of that table.
64049 */
64050 case OP_VDestroy: {
64051   p->inVtabMethod = 2;
64052   rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
64053   p->inVtabMethod = 0;
64054   break;
64055 }
64056 #endif /* SQLITE_OMIT_VIRTUALTABLE */
64057
64058 #ifndef SQLITE_OMIT_VIRTUALTABLE
64059 /* Opcode: VOpen P1 * * P4 *
64060 **
64061 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
64062 ** P1 is a cursor number.  This opcode opens a cursor to the virtual
64063 ** table and stores that cursor in P1.
64064 */
64065 case OP_VOpen: {
64066 #if 0  /* local variables moved into u.cg */
64067   VdbeCursor *pCur;
64068   sqlite3_vtab_cursor *pVtabCursor;
64069   sqlite3_vtab *pVtab;
64070   sqlite3_module *pModule;
64071 #endif /* local variables moved into u.cg */
64072
64073   u.cg.pCur = 0;
64074   u.cg.pVtabCursor = 0;
64075   u.cg.pVtab = pOp->p4.pVtab->pVtab;
64076   u.cg.pModule = (sqlite3_module *)u.cg.pVtab->pModule;
64077   assert(u.cg.pVtab && u.cg.pModule);
64078   rc = u.cg.pModule->xOpen(u.cg.pVtab, &u.cg.pVtabCursor);
64079   sqlite3DbFree(db, p->zErrMsg);
64080   p->zErrMsg = u.cg.pVtab->zErrMsg;
64081   u.cg.pVtab->zErrMsg = 0;
64082   if( SQLITE_OK==rc ){
64083     /* Initialize sqlite3_vtab_cursor base class */
64084     u.cg.pVtabCursor->pVtab = u.cg.pVtab;
64085
64086     /* Initialise vdbe cursor object */
64087     u.cg.pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
64088     if( u.cg.pCur ){
64089       u.cg.pCur->pVtabCursor = u.cg.pVtabCursor;
64090       u.cg.pCur->pModule = u.cg.pVtabCursor->pVtab->pModule;
64091     }else{
64092       db->mallocFailed = 1;
64093       u.cg.pModule->xClose(u.cg.pVtabCursor);
64094     }
64095   }
64096   break;
64097 }
64098 #endif /* SQLITE_OMIT_VIRTUALTABLE */
64099
64100 #ifndef SQLITE_OMIT_VIRTUALTABLE
64101 /* Opcode: VFilter P1 P2 P3 P4 *
64102 **
64103 ** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
64104 ** the filtered result set is empty.
64105 **
64106 ** P4 is either NULL or a string that was generated by the xBestIndex
64107 ** method of the module.  The interpretation of the P4 string is left
64108 ** to the module implementation.
64109 **
64110 ** This opcode invokes the xFilter method on the virtual table specified
64111 ** by P1.  The integer query plan parameter to xFilter is stored in register
64112 ** P3. Register P3+1 stores the argc parameter to be passed to the
64113 ** xFilter method. Registers P3+2..P3+1+argc are the argc
64114 ** additional parameters which are passed to
64115 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
64116 **
64117 ** A jump is made to P2 if the result set after filtering would be empty.
64118 */
64119 case OP_VFilter: {   /* jump */
64120 #if 0  /* local variables moved into u.ch */
64121   int nArg;
64122   int iQuery;
64123   const sqlite3_module *pModule;
64124   Mem *pQuery;
64125   Mem *pArgc;
64126   sqlite3_vtab_cursor *pVtabCursor;
64127   sqlite3_vtab *pVtab;
64128   VdbeCursor *pCur;
64129   int res;
64130   int i;
64131   Mem **apArg;
64132 #endif /* local variables moved into u.ch */
64133
64134   u.ch.pQuery = &aMem[pOp->p3];
64135   u.ch.pArgc = &u.ch.pQuery[1];
64136   u.ch.pCur = p->apCsr[pOp->p1];
64137   REGISTER_TRACE(pOp->p3, u.ch.pQuery);
64138   assert( u.ch.pCur->pVtabCursor );
64139   u.ch.pVtabCursor = u.ch.pCur->pVtabCursor;
64140   u.ch.pVtab = u.ch.pVtabCursor->pVtab;
64141   u.ch.pModule = u.ch.pVtab->pModule;
64142
64143   /* Grab the index number and argc parameters */
64144   assert( (u.ch.pQuery->flags&MEM_Int)!=0 && u.ch.pArgc->flags==MEM_Int );
64145   u.ch.nArg = (int)u.ch.pArgc->u.i;
64146   u.ch.iQuery = (int)u.ch.pQuery->u.i;
64147
64148   /* Invoke the xFilter method */
64149   {
64150     u.ch.res = 0;
64151     u.ch.apArg = p->apArg;
64152     for(u.ch.i = 0; u.ch.i<u.ch.nArg; u.ch.i++){
64153       u.ch.apArg[u.ch.i] = &u.ch.pArgc[u.ch.i+1];
64154       sqlite3VdbeMemStoreType(u.ch.apArg[u.ch.i]);
64155     }
64156
64157     p->inVtabMethod = 1;
64158     rc = u.ch.pModule->xFilter(u.ch.pVtabCursor, u.ch.iQuery, pOp->p4.z, u.ch.nArg, u.ch.apArg);
64159     p->inVtabMethod = 0;
64160     sqlite3DbFree(db, p->zErrMsg);
64161     p->zErrMsg = u.ch.pVtab->zErrMsg;
64162     u.ch.pVtab->zErrMsg = 0;
64163     if( rc==SQLITE_OK ){
64164       u.ch.res = u.ch.pModule->xEof(u.ch.pVtabCursor);
64165     }
64166
64167     if( u.ch.res ){
64168       pc = pOp->p2 - 1;
64169     }
64170   }
64171   u.ch.pCur->nullRow = 0;
64172
64173   break;
64174 }
64175 #endif /* SQLITE_OMIT_VIRTUALTABLE */
64176
64177 #ifndef SQLITE_OMIT_VIRTUALTABLE
64178 /* Opcode: VColumn P1 P2 P3 * *
64179 **
64180 ** Store the value of the P2-th column of
64181 ** the row of the virtual-table that the 
64182 ** P1 cursor is pointing to into register P3.
64183 */
64184 case OP_VColumn: {
64185 #if 0  /* local variables moved into u.ci */
64186   sqlite3_vtab *pVtab;
64187   const sqlite3_module *pModule;
64188   Mem *pDest;
64189   sqlite3_context sContext;
64190 #endif /* local variables moved into u.ci */
64191
64192   VdbeCursor *pCur = p->apCsr[pOp->p1];
64193   assert( pCur->pVtabCursor );
64194   assert( pOp->p3>0 && pOp->p3<=p->nMem );
64195   u.ci.pDest = &aMem[pOp->p3];
64196   if( pCur->nullRow ){
64197     sqlite3VdbeMemSetNull(u.ci.pDest);
64198     break;
64199   }
64200   u.ci.pVtab = pCur->pVtabCursor->pVtab;
64201   u.ci.pModule = u.ci.pVtab->pModule;
64202   assert( u.ci.pModule->xColumn );
64203   memset(&u.ci.sContext, 0, sizeof(u.ci.sContext));
64204
64205   /* The output cell may already have a buffer allocated. Move
64206   ** the current contents to u.ci.sContext.s so in case the user-function
64207   ** can use the already allocated buffer instead of allocating a
64208   ** new one.
64209   */
64210   sqlite3VdbeMemMove(&u.ci.sContext.s, u.ci.pDest);
64211   MemSetTypeFlag(&u.ci.sContext.s, MEM_Null);
64212
64213   rc = u.ci.pModule->xColumn(pCur->pVtabCursor, &u.ci.sContext, pOp->p2);
64214   sqlite3DbFree(db, p->zErrMsg);
64215   p->zErrMsg = u.ci.pVtab->zErrMsg;
64216   u.ci.pVtab->zErrMsg = 0;
64217   if( u.ci.sContext.isError ){
64218     rc = u.ci.sContext.isError;
64219   }
64220
64221   /* Copy the result of the function to the P3 register. We
64222   ** do this regardless of whether or not an error occurred to ensure any
64223   ** dynamic allocation in u.ci.sContext.s (a Mem struct) is  released.
64224   */
64225   sqlite3VdbeChangeEncoding(&u.ci.sContext.s, encoding);
64226   sqlite3VdbeMemMove(u.ci.pDest, &u.ci.sContext.s);
64227   REGISTER_TRACE(pOp->p3, u.ci.pDest);
64228   UPDATE_MAX_BLOBSIZE(u.ci.pDest);
64229
64230   if( sqlite3VdbeMemTooBig(u.ci.pDest) ){
64231     goto too_big;
64232   }
64233   break;
64234 }
64235 #endif /* SQLITE_OMIT_VIRTUALTABLE */
64236
64237 #ifndef SQLITE_OMIT_VIRTUALTABLE
64238 /* Opcode: VNext P1 P2 * * *
64239 **
64240 ** Advance virtual table P1 to the next row in its result set and
64241 ** jump to instruction P2.  Or, if the virtual table has reached
64242 ** the end of its result set, then fall through to the next instruction.
64243 */
64244 case OP_VNext: {   /* jump */
64245 #if 0  /* local variables moved into u.cj */
64246   sqlite3_vtab *pVtab;
64247   const sqlite3_module *pModule;
64248   int res;
64249   VdbeCursor *pCur;
64250 #endif /* local variables moved into u.cj */
64251
64252   u.cj.res = 0;
64253   u.cj.pCur = p->apCsr[pOp->p1];
64254   assert( u.cj.pCur->pVtabCursor );
64255   if( u.cj.pCur->nullRow ){
64256     break;
64257   }
64258   u.cj.pVtab = u.cj.pCur->pVtabCursor->pVtab;
64259   u.cj.pModule = u.cj.pVtab->pModule;
64260   assert( u.cj.pModule->xNext );
64261
64262   /* Invoke the xNext() method of the module. There is no way for the
64263   ** underlying implementation to return an error if one occurs during
64264   ** xNext(). Instead, if an error occurs, true is returned (indicating that
64265   ** data is available) and the error code returned when xColumn or
64266   ** some other method is next invoked on the save virtual table cursor.
64267   */
64268   p->inVtabMethod = 1;
64269   rc = u.cj.pModule->xNext(u.cj.pCur->pVtabCursor);
64270   p->inVtabMethod = 0;
64271   sqlite3DbFree(db, p->zErrMsg);
64272   p->zErrMsg = u.cj.pVtab->zErrMsg;
64273   u.cj.pVtab->zErrMsg = 0;
64274   if( rc==SQLITE_OK ){
64275     u.cj.res = u.cj.pModule->xEof(u.cj.pCur->pVtabCursor);
64276   }
64277
64278   if( !u.cj.res ){
64279     /* If there is data, jump to P2 */
64280     pc = pOp->p2 - 1;
64281   }
64282   break;
64283 }
64284 #endif /* SQLITE_OMIT_VIRTUALTABLE */
64285
64286 #ifndef SQLITE_OMIT_VIRTUALTABLE
64287 /* Opcode: VRename P1 * * P4 *
64288 **
64289 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
64290 ** This opcode invokes the corresponding xRename method. The value
64291 ** in register P1 is passed as the zName argument to the xRename method.
64292 */
64293 case OP_VRename: {
64294 #if 0  /* local variables moved into u.ck */
64295   sqlite3_vtab *pVtab;
64296   Mem *pName;
64297 #endif /* local variables moved into u.ck */
64298
64299   u.ck.pVtab = pOp->p4.pVtab->pVtab;
64300   u.ck.pName = &aMem[pOp->p1];
64301   assert( u.ck.pVtab->pModule->xRename );
64302   REGISTER_TRACE(pOp->p1, u.ck.pName);
64303   assert( u.ck.pName->flags & MEM_Str );
64304   rc = u.ck.pVtab->pModule->xRename(u.ck.pVtab, u.ck.pName->z);
64305   sqlite3DbFree(db, p->zErrMsg);
64306   p->zErrMsg = u.ck.pVtab->zErrMsg;
64307   u.ck.pVtab->zErrMsg = 0;
64308
64309   break;
64310 }
64311 #endif
64312
64313 #ifndef SQLITE_OMIT_VIRTUALTABLE
64314 /* Opcode: VUpdate P1 P2 P3 P4 *
64315 **
64316 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
64317 ** This opcode invokes the corresponding xUpdate method. P2 values
64318 ** are contiguous memory cells starting at P3 to pass to the xUpdate 
64319 ** invocation. The value in register (P3+P2-1) corresponds to the 
64320 ** p2th element of the argv array passed to xUpdate.
64321 **
64322 ** The xUpdate method will do a DELETE or an INSERT or both.
64323 ** The argv[0] element (which corresponds to memory cell P3)
64324 ** is the rowid of a row to delete.  If argv[0] is NULL then no 
64325 ** deletion occurs.  The argv[1] element is the rowid of the new 
64326 ** row.  This can be NULL to have the virtual table select the new 
64327 ** rowid for itself.  The subsequent elements in the array are 
64328 ** the values of columns in the new row.
64329 **
64330 ** If P2==1 then no insert is performed.  argv[0] is the rowid of
64331 ** a row to delete.
64332 **
64333 ** P1 is a boolean flag. If it is set to true and the xUpdate call
64334 ** is successful, then the value returned by sqlite3_last_insert_rowid() 
64335 ** is set to the value of the rowid for the row just inserted.
64336 */
64337 case OP_VUpdate: {
64338 #if 0  /* local variables moved into u.cl */
64339   sqlite3_vtab *pVtab;
64340   sqlite3_module *pModule;
64341   int nArg;
64342   int i;
64343   sqlite_int64 rowid;
64344   Mem **apArg;
64345   Mem *pX;
64346 #endif /* local variables moved into u.cl */
64347
64348   u.cl.pVtab = pOp->p4.pVtab->pVtab;
64349   u.cl.pModule = (sqlite3_module *)u.cl.pVtab->pModule;
64350   u.cl.nArg = pOp->p2;
64351   assert( pOp->p4type==P4_VTAB );
64352   if( ALWAYS(u.cl.pModule->xUpdate) ){
64353     u.cl.apArg = p->apArg;
64354     u.cl.pX = &aMem[pOp->p3];
64355     for(u.cl.i=0; u.cl.i<u.cl.nArg; u.cl.i++){
64356       sqlite3VdbeMemStoreType(u.cl.pX);
64357       u.cl.apArg[u.cl.i] = u.cl.pX;
64358       u.cl.pX++;
64359     }
64360     rc = u.cl.pModule->xUpdate(u.cl.pVtab, u.cl.nArg, u.cl.apArg, &u.cl.rowid);
64361     sqlite3DbFree(db, p->zErrMsg);
64362     p->zErrMsg = u.cl.pVtab->zErrMsg;
64363     u.cl.pVtab->zErrMsg = 0;
64364     if( rc==SQLITE_OK && pOp->p1 ){
64365       assert( u.cl.nArg>1 && u.cl.apArg[0] && (u.cl.apArg[0]->flags&MEM_Null) );
64366       db->lastRowid = u.cl.rowid;
64367     }
64368     p->nChange++;
64369   }
64370   break;
64371 }
64372 #endif /* SQLITE_OMIT_VIRTUALTABLE */
64373
64374 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
64375 /* Opcode: Pagecount P1 P2 * * *
64376 **
64377 ** Write the current number of pages in database P1 to memory cell P2.
64378 */
64379 case OP_Pagecount: {            /* out2-prerelease */
64380   pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
64381   break;
64382 }
64383 #endif
64384
64385 #ifndef SQLITE_OMIT_TRACE
64386 /* Opcode: Trace * * * P4 *
64387 **
64388 ** If tracing is enabled (by the sqlite3_trace()) interface, then
64389 ** the UTF-8 string contained in P4 is emitted on the trace callback.
64390 */
64391 case OP_Trace: {
64392 #if 0  /* local variables moved into u.cm */
64393   char *zTrace;
64394 #endif /* local variables moved into u.cm */
64395
64396   u.cm.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
64397   if( u.cm.zTrace ){
64398     if( db->xTrace ){
64399       char *z = sqlite3VdbeExpandSql(p, u.cm.zTrace);
64400       db->xTrace(db->pTraceArg, z);
64401       sqlite3DbFree(db, z);
64402     }
64403 #ifdef SQLITE_DEBUG
64404     if( (db->flags & SQLITE_SqlTrace)!=0 ){
64405       sqlite3DebugPrintf("SQL-trace: %s\n", u.cm.zTrace);
64406     }
64407 #endif /* SQLITE_DEBUG */
64408   }
64409   break;
64410 }
64411 #endif
64412
64413
64414 /* Opcode: Noop * * * * *
64415 **
64416 ** Do nothing.  This instruction is often useful as a jump
64417 ** destination.
64418 */
64419 /*
64420 ** The magic Explain opcode are only inserted when explain==2 (which
64421 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
64422 ** This opcode records information from the optimizer.  It is the
64423 ** the same as a no-op.  This opcodesnever appears in a real VM program.
64424 */
64425 default: {          /* This is really OP_Noop and OP_Explain */
64426   assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
64427   break;
64428 }
64429
64430 /*****************************************************************************
64431 ** The cases of the switch statement above this line should all be indented
64432 ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
64433 ** readability.  From this point on down, the normal indentation rules are
64434 ** restored.
64435 *****************************************************************************/
64436     }
64437
64438 #ifdef VDBE_PROFILE
64439     {
64440       u64 elapsed = sqlite3Hwtime() - start;
64441       pOp->cycles += elapsed;
64442       pOp->cnt++;
64443 #if 0
64444         fprintf(stdout, "%10llu ", elapsed);
64445         sqlite3VdbePrintOp(stdout, origPc, &aOp[origPc]);
64446 #endif
64447     }
64448 #endif
64449
64450     /* The following code adds nothing to the actual functionality
64451     ** of the program.  It is only here for testing and debugging.
64452     ** On the other hand, it does burn CPU cycles every time through
64453     ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
64454     */
64455 #ifndef NDEBUG
64456     assert( pc>=-1 && pc<p->nOp );
64457
64458 #ifdef SQLITE_DEBUG
64459     if( p->trace ){
64460       if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
64461       if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
64462         registerTrace(p->trace, pOp->p2, &aMem[pOp->p2]);
64463       }
64464       if( pOp->opflags & OPFLG_OUT3 ){
64465         registerTrace(p->trace, pOp->p3, &aMem[pOp->p3]);
64466       }
64467     }
64468 #endif  /* SQLITE_DEBUG */
64469 #endif  /* NDEBUG */
64470   }  /* The end of the for(;;) loop the loops through opcodes */
64471
64472   /* If we reach this point, it means that execution is finished with
64473   ** an error of some kind.
64474   */
64475 vdbe_error_halt:
64476   assert( rc );
64477   p->rc = rc;
64478   testcase( sqlite3GlobalConfig.xLog!=0 );
64479   sqlite3_log(rc, "statement aborts at %d: [%s] %s", 
64480                    pc, p->zSql, p->zErrMsg);
64481   sqlite3VdbeHalt(p);
64482   if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
64483   rc = SQLITE_ERROR;
64484   if( resetSchemaOnFault ) sqlite3ResetInternalSchema(db, 0);
64485
64486   /* This is the only way out of this procedure.  We have to
64487   ** release the mutexes on btrees that were acquired at the
64488   ** top. */
64489 vdbe_return:
64490   sqlite3BtreeMutexArrayLeave(&p->aMutex);
64491   return rc;
64492
64493   /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
64494   ** is encountered.
64495   */
64496 too_big:
64497   sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
64498   rc = SQLITE_TOOBIG;
64499   goto vdbe_error_halt;
64500
64501   /* Jump to here if a malloc() fails.
64502   */
64503 no_mem:
64504   db->mallocFailed = 1;
64505   sqlite3SetString(&p->zErrMsg, db, "out of memory");
64506   rc = SQLITE_NOMEM;
64507   goto vdbe_error_halt;
64508
64509   /* Jump to here for any other kind of fatal error.  The "rc" variable
64510   ** should hold the error number.
64511   */
64512 abort_due_to_error:
64513   assert( p->zErrMsg==0 );
64514   if( db->mallocFailed ) rc = SQLITE_NOMEM;
64515   if( rc!=SQLITE_IOERR_NOMEM ){
64516     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
64517   }
64518   goto vdbe_error_halt;
64519
64520   /* Jump to here if the sqlite3_interrupt() API sets the interrupt
64521   ** flag.
64522   */
64523 abort_due_to_interrupt:
64524   assert( db->u1.isInterrupted );
64525   rc = SQLITE_INTERRUPT;
64526   p->rc = rc;
64527   sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
64528   goto vdbe_error_halt;
64529 }
64530
64531 /************** End of vdbe.c ************************************************/
64532 /************** Begin file vdbeblob.c ****************************************/
64533 /*
64534 ** 2007 May 1
64535 **
64536 ** The author disclaims copyright to this source code.  In place of
64537 ** a legal notice, here is a blessing:
64538 **
64539 **    May you do good and not evil.
64540 **    May you find forgiveness for yourself and forgive others.
64541 **    May you share freely, never taking more than you give.
64542 **
64543 *************************************************************************
64544 **
64545 ** This file contains code used to implement incremental BLOB I/O.
64546 */
64547
64548
64549 #ifndef SQLITE_OMIT_INCRBLOB
64550
64551 /*
64552 ** Valid sqlite3_blob* handles point to Incrblob structures.
64553 */
64554 typedef struct Incrblob Incrblob;
64555 struct Incrblob {
64556   int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
64557   int nByte;              /* Size of open blob, in bytes */
64558   int iOffset;            /* Byte offset of blob in cursor data */
64559   BtCursor *pCsr;         /* Cursor pointing at blob row */
64560   sqlite3_stmt *pStmt;    /* Statement holding cursor open */
64561   sqlite3 *db;            /* The associated database */
64562 };
64563
64564 /*
64565 ** Open a blob handle.
64566 */
64567 SQLITE_API int sqlite3_blob_open(
64568   sqlite3* db,            /* The database connection */
64569   const char *zDb,        /* The attached database containing the blob */
64570   const char *zTable,     /* The table containing the blob */
64571   const char *zColumn,    /* The column containing the blob */
64572   sqlite_int64 iRow,      /* The row containing the glob */
64573   int flags,              /* True -> read/write access, false -> read-only */
64574   sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
64575 ){
64576   int nAttempt = 0;
64577   int iCol;               /* Index of zColumn in row-record */
64578
64579   /* This VDBE program seeks a btree cursor to the identified 
64580   ** db/table/row entry. The reason for using a vdbe program instead
64581   ** of writing code to use the b-tree layer directly is that the
64582   ** vdbe program will take advantage of the various transaction,
64583   ** locking and error handling infrastructure built into the vdbe.
64584   **
64585   ** After seeking the cursor, the vdbe executes an OP_ResultRow.
64586   ** Code external to the Vdbe then "borrows" the b-tree cursor and
64587   ** uses it to implement the blob_read(), blob_write() and 
64588   ** blob_bytes() functions.
64589   **
64590   ** The sqlite3_blob_close() function finalizes the vdbe program,
64591   ** which closes the b-tree cursor and (possibly) commits the 
64592   ** transaction.
64593   */
64594   static const VdbeOpList openBlob[] = {
64595     {OP_Transaction, 0, 0, 0},     /* 0: Start a transaction */
64596     {OP_VerifyCookie, 0, 0, 0},    /* 1: Check the schema cookie */
64597     {OP_TableLock, 0, 0, 0},       /* 2: Acquire a read or write lock */
64598
64599     /* One of the following two instructions is replaced by an OP_Noop. */
64600     {OP_OpenRead, 0, 0, 0},        /* 3: Open cursor 0 for reading */
64601     {OP_OpenWrite, 0, 0, 0},       /* 4: Open cursor 0 for read/write */
64602
64603     {OP_Variable, 1, 1, 1},        /* 5: Push the rowid to the stack */
64604     {OP_NotExists, 0, 9, 1},       /* 6: Seek the cursor */
64605     {OP_Column, 0, 0, 1},          /* 7  */
64606     {OP_ResultRow, 1, 0, 0},       /* 8  */
64607     {OP_Close, 0, 0, 0},           /* 9  */
64608     {OP_Halt, 0, 0, 0},            /* 10 */
64609   };
64610
64611   Vdbe *v = 0;
64612   int rc = SQLITE_OK;
64613   char *zErr = 0;
64614   Table *pTab;
64615   Parse *pParse;
64616
64617   *ppBlob = 0;
64618   sqlite3_mutex_enter(db->mutex);
64619   pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
64620   if( pParse==0 ){
64621     rc = SQLITE_NOMEM;
64622     goto blob_open_out;
64623   }
64624   do {
64625     memset(pParse, 0, sizeof(Parse));
64626     pParse->db = db;
64627
64628     sqlite3BtreeEnterAll(db);
64629     pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
64630     if( pTab && IsVirtual(pTab) ){
64631       pTab = 0;
64632       sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
64633     }
64634 #ifndef SQLITE_OMIT_VIEW
64635     if( pTab && pTab->pSelect ){
64636       pTab = 0;
64637       sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
64638     }
64639 #endif
64640     if( !pTab ){
64641       if( pParse->zErrMsg ){
64642         sqlite3DbFree(db, zErr);
64643         zErr = pParse->zErrMsg;
64644         pParse->zErrMsg = 0;
64645       }
64646       rc = SQLITE_ERROR;
64647       sqlite3BtreeLeaveAll(db);
64648       goto blob_open_out;
64649     }
64650
64651     /* Now search pTab for the exact column. */
64652     for(iCol=0; iCol < pTab->nCol; iCol++) {
64653       if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
64654         break;
64655       }
64656     }
64657     if( iCol==pTab->nCol ){
64658       sqlite3DbFree(db, zErr);
64659       zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
64660       rc = SQLITE_ERROR;
64661       sqlite3BtreeLeaveAll(db);
64662       goto blob_open_out;
64663     }
64664
64665     /* If the value is being opened for writing, check that the
64666     ** column is not indexed, and that it is not part of a foreign key. 
64667     ** It is against the rules to open a column to which either of these
64668     ** descriptions applies for writing.  */
64669     if( flags ){
64670       const char *zFault = 0;
64671       Index *pIdx;
64672 #ifndef SQLITE_OMIT_FOREIGN_KEY
64673       if( db->flags&SQLITE_ForeignKeys ){
64674         /* Check that the column is not part of an FK child key definition. It
64675         ** is not necessary to check if it is part of a parent key, as parent
64676         ** key columns must be indexed. The check below will pick up this 
64677         ** case.  */
64678         FKey *pFKey;
64679         for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
64680           int j;
64681           for(j=0; j<pFKey->nCol; j++){
64682             if( pFKey->aCol[j].iFrom==iCol ){
64683               zFault = "foreign key";
64684             }
64685           }
64686         }
64687       }
64688 #endif
64689       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
64690         int j;
64691         for(j=0; j<pIdx->nColumn; j++){
64692           if( pIdx->aiColumn[j]==iCol ){
64693             zFault = "indexed";
64694           }
64695         }
64696       }
64697       if( zFault ){
64698         sqlite3DbFree(db, zErr);
64699         zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
64700         rc = SQLITE_ERROR;
64701         sqlite3BtreeLeaveAll(db);
64702         goto blob_open_out;
64703       }
64704     }
64705
64706     v = sqlite3VdbeCreate(db);
64707     if( v ){
64708       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
64709       sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
64710       flags = !!flags;                 /* flags = (flags ? 1 : 0); */
64711
64712       /* Configure the OP_Transaction */
64713       sqlite3VdbeChangeP1(v, 0, iDb);
64714       sqlite3VdbeChangeP2(v, 0, flags);
64715
64716       /* Configure the OP_VerifyCookie */
64717       sqlite3VdbeChangeP1(v, 1, iDb);
64718       sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
64719
64720       /* Make sure a mutex is held on the table to be accessed */
64721       sqlite3VdbeUsesBtree(v, iDb); 
64722
64723       /* Configure the OP_TableLock instruction */
64724 #ifdef SQLITE_OMIT_SHARED_CACHE
64725       sqlite3VdbeChangeToNoop(v, 2, 1);
64726 #else
64727       sqlite3VdbeChangeP1(v, 2, iDb);
64728       sqlite3VdbeChangeP2(v, 2, pTab->tnum);
64729       sqlite3VdbeChangeP3(v, 2, flags);
64730       sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
64731 #endif
64732
64733       /* Remove either the OP_OpenWrite or OpenRead. Set the P2 
64734       ** parameter of the other to pTab->tnum.  */
64735       sqlite3VdbeChangeToNoop(v, 4 - flags, 1);
64736       sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum);
64737       sqlite3VdbeChangeP3(v, 3 + flags, iDb);
64738
64739       /* Configure the number of columns. Configure the cursor to
64740       ** think that the table has one more column than it really
64741       ** does. An OP_Column to retrieve this imaginary column will
64742       ** always return an SQL NULL. This is useful because it means
64743       ** we can invoke OP_Column to fill in the vdbe cursors type 
64744       ** and offset cache without causing any IO.
64745       */
64746       sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
64747       sqlite3VdbeChangeP2(v, 7, pTab->nCol);
64748       if( !db->mallocFailed ){
64749         sqlite3VdbeMakeReady(v, 1, 1, 1, 0, 0, 0);
64750       }
64751     }
64752    
64753     sqlite3BtreeLeaveAll(db);
64754     if( db->mallocFailed ){
64755       goto blob_open_out;
64756     }
64757
64758     sqlite3_bind_int64((sqlite3_stmt *)v, 1, iRow);
64759     rc = sqlite3_step((sqlite3_stmt *)v);
64760     if( rc!=SQLITE_ROW ){
64761       nAttempt++;
64762       rc = sqlite3_finalize((sqlite3_stmt *)v);
64763       sqlite3DbFree(db, zErr);
64764       zErr = sqlite3MPrintf(db, sqlite3_errmsg(db));
64765       v = 0;
64766     }
64767   } while( nAttempt<5 && rc==SQLITE_SCHEMA );
64768
64769   if( rc==SQLITE_ROW ){
64770     /* The row-record has been opened successfully. Check that the
64771     ** column in question contains text or a blob. If it contains
64772     ** text, it is up to the caller to get the encoding right.
64773     */
64774     Incrblob *pBlob;
64775     u32 type = v->apCsr[0]->aType[iCol];
64776
64777     if( type<12 ){
64778       sqlite3DbFree(db, zErr);
64779       zErr = sqlite3MPrintf(db, "cannot open value of type %s",
64780           type==0?"null": type==7?"real": "integer"
64781       );
64782       rc = SQLITE_ERROR;
64783       goto blob_open_out;
64784     }
64785     pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
64786     if( db->mallocFailed ){
64787       sqlite3DbFree(db, pBlob);
64788       goto blob_open_out;
64789     }
64790     pBlob->flags = flags;
64791     pBlob->pCsr =  v->apCsr[0]->pCursor;
64792     sqlite3BtreeEnterCursor(pBlob->pCsr);
64793     sqlite3BtreeCacheOverflow(pBlob->pCsr);
64794     sqlite3BtreeLeaveCursor(pBlob->pCsr);
64795     pBlob->pStmt = (sqlite3_stmt *)v;
64796     pBlob->iOffset = v->apCsr[0]->aOffset[iCol];
64797     pBlob->nByte = sqlite3VdbeSerialTypeLen(type);
64798     pBlob->db = db;
64799     *ppBlob = (sqlite3_blob *)pBlob;
64800     rc = SQLITE_OK;
64801   }else if( rc==SQLITE_OK ){
64802     sqlite3DbFree(db, zErr);
64803     zErr = sqlite3MPrintf(db, "no such rowid: %lld", iRow);
64804     rc = SQLITE_ERROR;
64805   }
64806
64807 blob_open_out:
64808   if( v && (rc!=SQLITE_OK || db->mallocFailed) ){
64809     sqlite3VdbeFinalize(v);
64810   }
64811   sqlite3Error(db, rc, zErr);
64812   sqlite3DbFree(db, zErr);
64813   sqlite3StackFree(db, pParse);
64814   rc = sqlite3ApiExit(db, rc);
64815   sqlite3_mutex_leave(db->mutex);
64816   return rc;
64817 }
64818
64819 /*
64820 ** Close a blob handle that was previously created using
64821 ** sqlite3_blob_open().
64822 */
64823 SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
64824   Incrblob *p = (Incrblob *)pBlob;
64825   int rc;
64826   sqlite3 *db;
64827
64828   if( p ){
64829     db = p->db;
64830     sqlite3_mutex_enter(db->mutex);
64831     rc = sqlite3_finalize(p->pStmt);
64832     sqlite3DbFree(db, p);
64833     sqlite3_mutex_leave(db->mutex);
64834   }else{
64835     rc = SQLITE_OK;
64836   }
64837   return rc;
64838 }
64839
64840 /*
64841 ** Perform a read or write operation on a blob
64842 */
64843 static int blobReadWrite(
64844   sqlite3_blob *pBlob, 
64845   void *z, 
64846   int n, 
64847   int iOffset, 
64848   int (*xCall)(BtCursor*, u32, u32, void*)
64849 ){
64850   int rc;
64851   Incrblob *p = (Incrblob *)pBlob;
64852   Vdbe *v;
64853   sqlite3 *db;
64854
64855   if( p==0 ) return SQLITE_MISUSE_BKPT;
64856   db = p->db;
64857   sqlite3_mutex_enter(db->mutex);
64858   v = (Vdbe*)p->pStmt;
64859
64860   if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
64861     /* Request is out of range. Return a transient error. */
64862     rc = SQLITE_ERROR;
64863     sqlite3Error(db, SQLITE_ERROR, 0);
64864   } else if( v==0 ){
64865     /* If there is no statement handle, then the blob-handle has
64866     ** already been invalidated. Return SQLITE_ABORT in this case.
64867     */
64868     rc = SQLITE_ABORT;
64869   }else{
64870     /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
64871     ** returned, clean-up the statement handle.
64872     */
64873     assert( db == v->db );
64874     sqlite3BtreeEnterCursor(p->pCsr);
64875     rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
64876     sqlite3BtreeLeaveCursor(p->pCsr);
64877     if( rc==SQLITE_ABORT ){
64878       sqlite3VdbeFinalize(v);
64879       p->pStmt = 0;
64880     }else{
64881       db->errCode = rc;
64882       v->rc = rc;
64883     }
64884   }
64885   rc = sqlite3ApiExit(db, rc);
64886   sqlite3_mutex_leave(db->mutex);
64887   return rc;
64888 }
64889
64890 /*
64891 ** Read data from a blob handle.
64892 */
64893 SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
64894   return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
64895 }
64896
64897 /*
64898 ** Write data to a blob handle.
64899 */
64900 SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
64901   return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
64902 }
64903
64904 /*
64905 ** Query a blob handle for the size of the data.
64906 **
64907 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
64908 ** so no mutex is required for access.
64909 */
64910 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
64911   Incrblob *p = (Incrblob *)pBlob;
64912   return p ? p->nByte : 0;
64913 }
64914
64915 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
64916
64917 /************** End of vdbeblob.c ********************************************/
64918 /************** Begin file journal.c *****************************************/
64919 /*
64920 ** 2007 August 22
64921 **
64922 ** The author disclaims copyright to this source code.  In place of
64923 ** a legal notice, here is a blessing:
64924 **
64925 **    May you do good and not evil.
64926 **    May you find forgiveness for yourself and forgive others.
64927 **    May you share freely, never taking more than you give.
64928 **
64929 *************************************************************************
64930 **
64931 ** This file implements a special kind of sqlite3_file object used
64932 ** by SQLite to create journal files if the atomic-write optimization
64933 ** is enabled.
64934 **
64935 ** The distinctive characteristic of this sqlite3_file is that the
64936 ** actual on disk file is created lazily. When the file is created,
64937 ** the caller specifies a buffer size for an in-memory buffer to
64938 ** be used to service read() and write() requests. The actual file
64939 ** on disk is not created or populated until either:
64940 **
64941 **   1) The in-memory representation grows too large for the allocated 
64942 **      buffer, or
64943 **   2) The sqlite3JournalCreate() function is called.
64944 */
64945 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
64946
64947
64948 /*
64949 ** A JournalFile object is a subclass of sqlite3_file used by
64950 ** as an open file handle for journal files.
64951 */
64952 struct JournalFile {
64953   sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
64954   int nBuf;                       /* Size of zBuf[] in bytes */
64955   char *zBuf;                     /* Space to buffer journal writes */
64956   int iSize;                      /* Amount of zBuf[] currently used */
64957   int flags;                      /* xOpen flags */
64958   sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
64959   sqlite3_file *pReal;            /* The "real" underlying file descriptor */
64960   const char *zJournal;           /* Name of the journal file */
64961 };
64962 typedef struct JournalFile JournalFile;
64963
64964 /*
64965 ** If it does not already exists, create and populate the on-disk file 
64966 ** for JournalFile p.
64967 */
64968 static int createFile(JournalFile *p){
64969   int rc = SQLITE_OK;
64970   if( !p->pReal ){
64971     sqlite3_file *pReal = (sqlite3_file *)&p[1];
64972     rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
64973     if( rc==SQLITE_OK ){
64974       p->pReal = pReal;
64975       if( p->iSize>0 ){
64976         assert(p->iSize<=p->nBuf);
64977         rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
64978       }
64979     }
64980   }
64981   return rc;
64982 }
64983
64984 /*
64985 ** Close the file.
64986 */
64987 static int jrnlClose(sqlite3_file *pJfd){
64988   JournalFile *p = (JournalFile *)pJfd;
64989   if( p->pReal ){
64990     sqlite3OsClose(p->pReal);
64991   }
64992   sqlite3_free(p->zBuf);
64993   return SQLITE_OK;
64994 }
64995
64996 /*
64997 ** Read data from the file.
64998 */
64999 static int jrnlRead(
65000   sqlite3_file *pJfd,    /* The journal file from which to read */
65001   void *zBuf,            /* Put the results here */
65002   int iAmt,              /* Number of bytes to read */
65003   sqlite_int64 iOfst     /* Begin reading at this offset */
65004 ){
65005   int rc = SQLITE_OK;
65006   JournalFile *p = (JournalFile *)pJfd;
65007   if( p->pReal ){
65008     rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
65009   }else if( (iAmt+iOfst)>p->iSize ){
65010     rc = SQLITE_IOERR_SHORT_READ;
65011   }else{
65012     memcpy(zBuf, &p->zBuf[iOfst], iAmt);
65013   }
65014   return rc;
65015 }
65016
65017 /*
65018 ** Write data to the file.
65019 */
65020 static int jrnlWrite(
65021   sqlite3_file *pJfd,    /* The journal file into which to write */
65022   const void *zBuf,      /* Take data to be written from here */
65023   int iAmt,              /* Number of bytes to write */
65024   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
65025 ){
65026   int rc = SQLITE_OK;
65027   JournalFile *p = (JournalFile *)pJfd;
65028   if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
65029     rc = createFile(p);
65030   }
65031   if( rc==SQLITE_OK ){
65032     if( p->pReal ){
65033       rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
65034     }else{
65035       memcpy(&p->zBuf[iOfst], zBuf, iAmt);
65036       if( p->iSize<(iOfst+iAmt) ){
65037         p->iSize = (iOfst+iAmt);
65038       }
65039     }
65040   }
65041   return rc;
65042 }
65043
65044 /*
65045 ** Truncate the file.
65046 */
65047 static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
65048   int rc = SQLITE_OK;
65049   JournalFile *p = (JournalFile *)pJfd;
65050   if( p->pReal ){
65051     rc = sqlite3OsTruncate(p->pReal, size);
65052   }else if( size<p->iSize ){
65053     p->iSize = size;
65054   }
65055   return rc;
65056 }
65057
65058 /*
65059 ** Sync the file.
65060 */
65061 static int jrnlSync(sqlite3_file *pJfd, int flags){
65062   int rc;
65063   JournalFile *p = (JournalFile *)pJfd;
65064   if( p->pReal ){
65065     rc = sqlite3OsSync(p->pReal, flags);
65066   }else{
65067     rc = SQLITE_OK;
65068   }
65069   return rc;
65070 }
65071
65072 /*
65073 ** Query the size of the file in bytes.
65074 */
65075 static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
65076   int rc = SQLITE_OK;
65077   JournalFile *p = (JournalFile *)pJfd;
65078   if( p->pReal ){
65079     rc = sqlite3OsFileSize(p->pReal, pSize);
65080   }else{
65081     *pSize = (sqlite_int64) p->iSize;
65082   }
65083   return rc;
65084 }
65085
65086 /*
65087 ** Table of methods for JournalFile sqlite3_file object.
65088 */
65089 static struct sqlite3_io_methods JournalFileMethods = {
65090   1,             /* iVersion */
65091   jrnlClose,     /* xClose */
65092   jrnlRead,      /* xRead */
65093   jrnlWrite,     /* xWrite */
65094   jrnlTruncate,  /* xTruncate */
65095   jrnlSync,      /* xSync */
65096   jrnlFileSize,  /* xFileSize */
65097   0,             /* xLock */
65098   0,             /* xUnlock */
65099   0,             /* xCheckReservedLock */
65100   0,             /* xFileControl */
65101   0,             /* xSectorSize */
65102   0,             /* xDeviceCharacteristics */
65103   0,             /* xShmMap */
65104   0,             /* xShmLock */
65105   0,             /* xShmBarrier */
65106   0              /* xShmUnmap */
65107 };
65108
65109 /* 
65110 ** Open a journal file.
65111 */
65112 SQLITE_PRIVATE int sqlite3JournalOpen(
65113   sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
65114   const char *zName,         /* Name of the journal file */
65115   sqlite3_file *pJfd,        /* Preallocated, blank file handle */
65116   int flags,                 /* Opening flags */
65117   int nBuf                   /* Bytes buffered before opening the file */
65118 ){
65119   JournalFile *p = (JournalFile *)pJfd;
65120   memset(p, 0, sqlite3JournalSize(pVfs));
65121   if( nBuf>0 ){
65122     p->zBuf = sqlite3MallocZero(nBuf);
65123     if( !p->zBuf ){
65124       return SQLITE_NOMEM;
65125     }
65126   }else{
65127     return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
65128   }
65129   p->pMethod = &JournalFileMethods;
65130   p->nBuf = nBuf;
65131   p->flags = flags;
65132   p->zJournal = zName;
65133   p->pVfs = pVfs;
65134   return SQLITE_OK;
65135 }
65136
65137 /*
65138 ** If the argument p points to a JournalFile structure, and the underlying
65139 ** file has not yet been created, create it now.
65140 */
65141 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
65142   if( p->pMethods!=&JournalFileMethods ){
65143     return SQLITE_OK;
65144   }
65145   return createFile((JournalFile *)p);
65146 }
65147
65148 /* 
65149 ** Return the number of bytes required to store a JournalFile that uses vfs
65150 ** pVfs to create the underlying on-disk files.
65151 */
65152 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
65153   return (pVfs->szOsFile+sizeof(JournalFile));
65154 }
65155 #endif
65156
65157 /************** End of journal.c *********************************************/
65158 /************** Begin file memjournal.c **************************************/
65159 /*
65160 ** 2008 October 7
65161 **
65162 ** The author disclaims copyright to this source code.  In place of
65163 ** a legal notice, here is a blessing:
65164 **
65165 **    May you do good and not evil.
65166 **    May you find forgiveness for yourself and forgive others.
65167 **    May you share freely, never taking more than you give.
65168 **
65169 *************************************************************************
65170 **
65171 ** This file contains code use to implement an in-memory rollback journal.
65172 ** The in-memory rollback journal is used to journal transactions for
65173 ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
65174 */
65175
65176 /* Forward references to internal structures */
65177 typedef struct MemJournal MemJournal;
65178 typedef struct FilePoint FilePoint;
65179 typedef struct FileChunk FileChunk;
65180
65181 /* Space to hold the rollback journal is allocated in increments of
65182 ** this many bytes.
65183 **
65184 ** The size chosen is a little less than a power of two.  That way,
65185 ** the FileChunk object will have a size that almost exactly fills
65186 ** a power-of-two allocation.  This mimimizes wasted space in power-of-two
65187 ** memory allocators.
65188 */
65189 #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
65190
65191 /* Macro to find the minimum of two numeric values.
65192 */
65193 #ifndef MIN
65194 # define MIN(x,y) ((x)<(y)?(x):(y))
65195 #endif
65196
65197 /*
65198 ** The rollback journal is composed of a linked list of these structures.
65199 */
65200 struct FileChunk {
65201   FileChunk *pNext;               /* Next chunk in the journal */
65202   u8 zChunk[JOURNAL_CHUNKSIZE];   /* Content of this chunk */
65203 };
65204
65205 /*
65206 ** An instance of this object serves as a cursor into the rollback journal.
65207 ** The cursor can be either for reading or writing.
65208 */
65209 struct FilePoint {
65210   sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
65211   FileChunk *pChunk;              /* Specific chunk into which cursor points */
65212 };
65213
65214 /*
65215 ** This subclass is a subclass of sqlite3_file.  Each open memory-journal
65216 ** is an instance of this class.
65217 */
65218 struct MemJournal {
65219   sqlite3_io_methods *pMethod;    /* Parent class. MUST BE FIRST */
65220   FileChunk *pFirst;              /* Head of in-memory chunk-list */
65221   FilePoint endpoint;             /* Pointer to the end of the file */
65222   FilePoint readpoint;            /* Pointer to the end of the last xRead() */
65223 };
65224
65225 /*
65226 ** Read data from the in-memory journal file.  This is the implementation
65227 ** of the sqlite3_vfs.xRead method.
65228 */
65229 static int memjrnlRead(
65230   sqlite3_file *pJfd,    /* The journal file from which to read */
65231   void *zBuf,            /* Put the results here */
65232   int iAmt,              /* Number of bytes to read */
65233   sqlite_int64 iOfst     /* Begin reading at this offset */
65234 ){
65235   MemJournal *p = (MemJournal *)pJfd;
65236   u8 *zOut = zBuf;
65237   int nRead = iAmt;
65238   int iChunkOffset;
65239   FileChunk *pChunk;
65240
65241   /* SQLite never tries to read past the end of a rollback journal file */
65242   assert( iOfst+iAmt<=p->endpoint.iOffset );
65243
65244   if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
65245     sqlite3_int64 iOff = 0;
65246     for(pChunk=p->pFirst; 
65247         ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
65248         pChunk=pChunk->pNext
65249     ){
65250       iOff += JOURNAL_CHUNKSIZE;
65251     }
65252   }else{
65253     pChunk = p->readpoint.pChunk;
65254   }
65255
65256   iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
65257   do {
65258     int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
65259     int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
65260     memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
65261     zOut += nCopy;
65262     nRead -= iSpace;
65263     iChunkOffset = 0;
65264   } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
65265   p->readpoint.iOffset = iOfst+iAmt;
65266   p->readpoint.pChunk = pChunk;
65267
65268   return SQLITE_OK;
65269 }
65270
65271 /*
65272 ** Write data to the file.
65273 */
65274 static int memjrnlWrite(
65275   sqlite3_file *pJfd,    /* The journal file into which to write */
65276   const void *zBuf,      /* Take data to be written from here */
65277   int iAmt,              /* Number of bytes to write */
65278   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
65279 ){
65280   MemJournal *p = (MemJournal *)pJfd;
65281   int nWrite = iAmt;
65282   u8 *zWrite = (u8 *)zBuf;
65283
65284   /* An in-memory journal file should only ever be appended to. Random
65285   ** access writes are not required by sqlite.
65286   */
65287   assert( iOfst==p->endpoint.iOffset );
65288   UNUSED_PARAMETER(iOfst);
65289
65290   while( nWrite>0 ){
65291     FileChunk *pChunk = p->endpoint.pChunk;
65292     int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
65293     int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
65294
65295     if( iChunkOffset==0 ){
65296       /* New chunk is required to extend the file. */
65297       FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
65298       if( !pNew ){
65299         return SQLITE_IOERR_NOMEM;
65300       }
65301       pNew->pNext = 0;
65302       if( pChunk ){
65303         assert( p->pFirst );
65304         pChunk->pNext = pNew;
65305       }else{
65306         assert( !p->pFirst );
65307         p->pFirst = pNew;
65308       }
65309       p->endpoint.pChunk = pNew;
65310     }
65311
65312     memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
65313     zWrite += iSpace;
65314     nWrite -= iSpace;
65315     p->endpoint.iOffset += iSpace;
65316   }
65317
65318   return SQLITE_OK;
65319 }
65320
65321 /*
65322 ** Truncate the file.
65323 */
65324 static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
65325   MemJournal *p = (MemJournal *)pJfd;
65326   FileChunk *pChunk;
65327   assert(size==0);
65328   UNUSED_PARAMETER(size);
65329   pChunk = p->pFirst;
65330   while( pChunk ){
65331     FileChunk *pTmp = pChunk;
65332     pChunk = pChunk->pNext;
65333     sqlite3_free(pTmp);
65334   }
65335   sqlite3MemJournalOpen(pJfd);
65336   return SQLITE_OK;
65337 }
65338
65339 /*
65340 ** Close the file.
65341 */
65342 static int memjrnlClose(sqlite3_file *pJfd){
65343   memjrnlTruncate(pJfd, 0);
65344   return SQLITE_OK;
65345 }
65346
65347
65348 /*
65349 ** Sync the file.
65350 **
65351 ** Syncing an in-memory journal is a no-op.  And, in fact, this routine
65352 ** is never called in a working implementation.  This implementation
65353 ** exists purely as a contingency, in case some malfunction in some other
65354 ** part of SQLite causes Sync to be called by mistake.
65355 */
65356 static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
65357   UNUSED_PARAMETER2(NotUsed, NotUsed2);
65358   return SQLITE_OK;
65359 }
65360
65361 /*
65362 ** Query the size of the file in bytes.
65363 */
65364 static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
65365   MemJournal *p = (MemJournal *)pJfd;
65366   *pSize = (sqlite_int64) p->endpoint.iOffset;
65367   return SQLITE_OK;
65368 }
65369
65370 /*
65371 ** Table of methods for MemJournal sqlite3_file object.
65372 */
65373 static const struct sqlite3_io_methods MemJournalMethods = {
65374   1,                /* iVersion */
65375   memjrnlClose,     /* xClose */
65376   memjrnlRead,      /* xRead */
65377   memjrnlWrite,     /* xWrite */
65378   memjrnlTruncate,  /* xTruncate */
65379   memjrnlSync,      /* xSync */
65380   memjrnlFileSize,  /* xFileSize */
65381   0,                /* xLock */
65382   0,                /* xUnlock */
65383   0,                /* xCheckReservedLock */
65384   0,                /* xFileControl */
65385   0,                /* xSectorSize */
65386   0,                /* xDeviceCharacteristics */
65387   0,                /* xShmMap */
65388   0,                /* xShmLock */
65389   0,                /* xShmBarrier */
65390   0                 /* xShmUnlock */
65391 };
65392
65393 /* 
65394 ** Open a journal file.
65395 */
65396 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
65397   MemJournal *p = (MemJournal *)pJfd;
65398   assert( EIGHT_BYTE_ALIGNMENT(p) );
65399   memset(p, 0, sqlite3MemJournalSize());
65400   p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
65401 }
65402
65403 /*
65404 ** Return true if the file-handle passed as an argument is 
65405 ** an in-memory journal 
65406 */
65407 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
65408   return pJfd->pMethods==&MemJournalMethods;
65409 }
65410
65411 /* 
65412 ** Return the number of bytes required to store a MemJournal that uses vfs
65413 ** pVfs to create the underlying on-disk files.
65414 */
65415 SQLITE_PRIVATE int sqlite3MemJournalSize(void){
65416   return sizeof(MemJournal);
65417 }
65418
65419 /************** End of memjournal.c ******************************************/
65420 /************** Begin file walker.c ******************************************/
65421 /*
65422 ** 2008 August 16
65423 **
65424 ** The author disclaims copyright to this source code.  In place of
65425 ** a legal notice, here is a blessing:
65426 **
65427 **    May you do good and not evil.
65428 **    May you find forgiveness for yourself and forgive others.
65429 **    May you share freely, never taking more than you give.
65430 **
65431 *************************************************************************
65432 ** This file contains routines used for walking the parser tree for
65433 ** an SQL statement.
65434 */
65435
65436
65437 /*
65438 ** Walk an expression tree.  Invoke the callback once for each node
65439 ** of the expression, while decending.  (In other words, the callback
65440 ** is invoked before visiting children.)
65441 **
65442 ** The return value from the callback should be one of the WRC_*
65443 ** constants to specify how to proceed with the walk.
65444 **
65445 **    WRC_Continue      Continue descending down the tree.
65446 **
65447 **    WRC_Prune         Do not descend into child nodes.  But allow
65448 **                      the walk to continue with sibling nodes.
65449 **
65450 **    WRC_Abort         Do no more callbacks.  Unwind the stack and
65451 **                      return the top-level walk call.
65452 **
65453 ** The return value from this routine is WRC_Abort to abandon the tree walk
65454 ** and WRC_Continue to continue.
65455 */
65456 SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
65457   int rc;
65458   if( pExpr==0 ) return WRC_Continue;
65459   testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
65460   testcase( ExprHasProperty(pExpr, EP_Reduced) );
65461   rc = pWalker->xExprCallback(pWalker, pExpr);
65462   if( rc==WRC_Continue
65463               && !ExprHasAnyProperty(pExpr,EP_TokenOnly) ){
65464     if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
65465     if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
65466     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
65467       if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
65468     }else{
65469       if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
65470     }
65471   }
65472   return rc & WRC_Abort;
65473 }
65474
65475 /*
65476 ** Call sqlite3WalkExpr() for every expression in list p or until
65477 ** an abort request is seen.
65478 */
65479 SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
65480   int i;
65481   struct ExprList_item *pItem;
65482   if( p ){
65483     for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
65484       if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
65485     }
65486   }
65487   return WRC_Continue;
65488 }
65489
65490 /*
65491 ** Walk all expressions associated with SELECT statement p.  Do
65492 ** not invoke the SELECT callback on p, but do (of course) invoke
65493 ** any expr callbacks and SELECT callbacks that come from subqueries.
65494 ** Return WRC_Abort or WRC_Continue.
65495 */
65496 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
65497   if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
65498   if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
65499   if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
65500   if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
65501   if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
65502   if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
65503   if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
65504   return WRC_Continue;
65505 }
65506
65507 /*
65508 ** Walk the parse trees associated with all subqueries in the
65509 ** FROM clause of SELECT statement p.  Do not invoke the select
65510 ** callback on p, but do invoke it on each FROM clause subquery
65511 ** and on any subqueries further down in the tree.  Return 
65512 ** WRC_Abort or WRC_Continue;
65513 */
65514 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
65515   SrcList *pSrc;
65516   int i;
65517   struct SrcList_item *pItem;
65518
65519   pSrc = p->pSrc;
65520   if( ALWAYS(pSrc) ){
65521     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
65522       if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
65523         return WRC_Abort;
65524       }
65525     }
65526   }
65527   return WRC_Continue;
65528
65529
65530 /*
65531 ** Call sqlite3WalkExpr() for every expression in Select statement p.
65532 ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
65533 ** on the compound select chain, p->pPrior.
65534 **
65535 ** Return WRC_Continue under normal conditions.  Return WRC_Abort if
65536 ** there is an abort request.
65537 **
65538 ** If the Walker does not have an xSelectCallback() then this routine
65539 ** is a no-op returning WRC_Continue.
65540 */
65541 SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
65542   int rc;
65543   if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
65544   rc = WRC_Continue;
65545   while( p  ){
65546     rc = pWalker->xSelectCallback(pWalker, p);
65547     if( rc ) break;
65548     if( sqlite3WalkSelectExpr(pWalker, p) ) return WRC_Abort;
65549     if( sqlite3WalkSelectFrom(pWalker, p) ) return WRC_Abort;
65550     p = p->pPrior;
65551   }
65552   return rc & WRC_Abort;
65553 }
65554
65555 /************** End of walker.c **********************************************/
65556 /************** Begin file resolve.c *****************************************/
65557 /*
65558 ** 2008 August 18
65559 **
65560 ** The author disclaims copyright to this source code.  In place of
65561 ** a legal notice, here is a blessing:
65562 **
65563 **    May you do good and not evil.
65564 **    May you find forgiveness for yourself and forgive others.
65565 **    May you share freely, never taking more than you give.
65566 **
65567 *************************************************************************
65568 **
65569 ** This file contains routines used for walking the parser tree and
65570 ** resolve all identifiers by associating them with a particular
65571 ** table and column.
65572 */
65573
65574 /*
65575 ** Turn the pExpr expression into an alias for the iCol-th column of the
65576 ** result set in pEList.
65577 **
65578 ** If the result set column is a simple column reference, then this routine
65579 ** makes an exact copy.  But for any other kind of expression, this
65580 ** routine make a copy of the result set column as the argument to the
65581 ** TK_AS operator.  The TK_AS operator causes the expression to be
65582 ** evaluated just once and then reused for each alias.
65583 **
65584 ** The reason for suppressing the TK_AS term when the expression is a simple
65585 ** column reference is so that the column reference will be recognized as
65586 ** usable by indices within the WHERE clause processing logic. 
65587 **
65588 ** Hack:  The TK_AS operator is inhibited if zType[0]=='G'.  This means
65589 ** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
65590 **
65591 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
65592 **
65593 ** Is equivalent to:
65594 **
65595 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
65596 **
65597 ** The result of random()%5 in the GROUP BY clause is probably different
65598 ** from the result in the result-set.  We might fix this someday.  Or
65599 ** then again, we might not...
65600 */
65601 static void resolveAlias(
65602   Parse *pParse,         /* Parsing context */
65603   ExprList *pEList,      /* A result set */
65604   int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
65605   Expr *pExpr,           /* Transform this into an alias to the result set */
65606   const char *zType      /* "GROUP" or "ORDER" or "" */
65607 ){
65608   Expr *pOrig;           /* The iCol-th column of the result set */
65609   Expr *pDup;            /* Copy of pOrig */
65610   sqlite3 *db;           /* The database connection */
65611
65612   assert( iCol>=0 && iCol<pEList->nExpr );
65613   pOrig = pEList->a[iCol].pExpr;
65614   assert( pOrig!=0 );
65615   assert( pOrig->flags & EP_Resolved );
65616   db = pParse->db;
65617   if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
65618     pDup = sqlite3ExprDup(db, pOrig, 0);
65619     pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
65620     if( pDup==0 ) return;
65621     if( pEList->a[iCol].iAlias==0 ){
65622       pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
65623     }
65624     pDup->iTable = pEList->a[iCol].iAlias;
65625   }else if( ExprHasProperty(pOrig, EP_IntValue) || pOrig->u.zToken==0 ){
65626     pDup = sqlite3ExprDup(db, pOrig, 0);
65627     if( pDup==0 ) return;
65628   }else{
65629     char *zToken = pOrig->u.zToken;
65630     assert( zToken!=0 );
65631     pOrig->u.zToken = 0;
65632     pDup = sqlite3ExprDup(db, pOrig, 0);
65633     pOrig->u.zToken = zToken;
65634     if( pDup==0 ) return;
65635     assert( (pDup->flags & (EP_Reduced|EP_TokenOnly))==0 );
65636     pDup->flags2 |= EP2_MallocedToken;
65637     pDup->u.zToken = sqlite3DbStrDup(db, zToken);
65638   }
65639   if( pExpr->flags & EP_ExpCollate ){
65640     pDup->pColl = pExpr->pColl;
65641     pDup->flags |= EP_ExpCollate;
65642   }
65643
65644   /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This 
65645   ** prevents ExprDelete() from deleting the Expr structure itself,
65646   ** allowing it to be repopulated by the memcpy() on the following line.
65647   */
65648   ExprSetProperty(pExpr, EP_Static);
65649   sqlite3ExprDelete(db, pExpr);
65650   memcpy(pExpr, pDup, sizeof(*pExpr));
65651   sqlite3DbFree(db, pDup);
65652 }
65653
65654 /*
65655 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
65656 ** that name in the set of source tables in pSrcList and make the pExpr 
65657 ** expression node refer back to that source column.  The following changes
65658 ** are made to pExpr:
65659 **
65660 **    pExpr->iDb           Set the index in db->aDb[] of the database X
65661 **                         (even if X is implied).
65662 **    pExpr->iTable        Set to the cursor number for the table obtained
65663 **                         from pSrcList.
65664 **    pExpr->pTab          Points to the Table structure of X.Y (even if
65665 **                         X and/or Y are implied.)
65666 **    pExpr->iColumn       Set to the column number within the table.
65667 **    pExpr->op            Set to TK_COLUMN.
65668 **    pExpr->pLeft         Any expression this points to is deleted
65669 **    pExpr->pRight        Any expression this points to is deleted.
65670 **
65671 ** The zDb variable is the name of the database (the "X").  This value may be
65672 ** NULL meaning that name is of the form Y.Z or Z.  Any available database
65673 ** can be used.  The zTable variable is the name of the table (the "Y").  This
65674 ** value can be NULL if zDb is also NULL.  If zTable is NULL it
65675 ** means that the form of the name is Z and that columns from any table
65676 ** can be used.
65677 **
65678 ** If the name cannot be resolved unambiguously, leave an error message
65679 ** in pParse and return WRC_Abort.  Return WRC_Prune on success.
65680 */
65681 static int lookupName(
65682   Parse *pParse,       /* The parsing context */
65683   const char *zDb,     /* Name of the database containing table, or NULL */
65684   const char *zTab,    /* Name of table containing column, or NULL */
65685   const char *zCol,    /* Name of the column. */
65686   NameContext *pNC,    /* The name context used to resolve the name */
65687   Expr *pExpr          /* Make this EXPR node point to the selected column */
65688 ){
65689   int i, j;            /* Loop counters */
65690   int cnt = 0;                      /* Number of matching column names */
65691   int cntTab = 0;                   /* Number of matching table names */
65692   sqlite3 *db = pParse->db;         /* The database connection */
65693   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
65694   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
65695   NameContext *pTopNC = pNC;        /* First namecontext in the list */
65696   Schema *pSchema = 0;              /* Schema of the expression */
65697   int isTrigger = 0;
65698
65699   assert( pNC );     /* the name context cannot be NULL. */
65700   assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
65701   assert( ~ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
65702
65703   /* Initialize the node to no-match */
65704   pExpr->iTable = -1;
65705   pExpr->pTab = 0;
65706   ExprSetIrreducible(pExpr);
65707
65708   /* Start at the inner-most context and move outward until a match is found */
65709   while( pNC && cnt==0 ){
65710     ExprList *pEList;
65711     SrcList *pSrcList = pNC->pSrcList;
65712
65713     if( pSrcList ){
65714       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
65715         Table *pTab;
65716         int iDb;
65717         Column *pCol;
65718   
65719         pTab = pItem->pTab;
65720         assert( pTab!=0 && pTab->zName!=0 );
65721         iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
65722         assert( pTab->nCol>0 );
65723         if( zTab ){
65724           if( pItem->zAlias ){
65725             char *zTabName = pItem->zAlias;
65726             if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
65727           }else{
65728             char *zTabName = pTab->zName;
65729             if( NEVER(zTabName==0) || sqlite3StrICmp(zTabName, zTab)!=0 ){
65730               continue;
65731             }
65732             if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
65733               continue;
65734             }
65735           }
65736         }
65737         if( 0==(cntTab++) ){
65738           pExpr->iTable = pItem->iCursor;
65739           pExpr->pTab = pTab;
65740           pSchema = pTab->pSchema;
65741           pMatch = pItem;
65742         }
65743         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
65744           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
65745             IdList *pUsing;
65746             cnt++;
65747             pExpr->iTable = pItem->iCursor;
65748             pExpr->pTab = pTab;
65749             pMatch = pItem;
65750             pSchema = pTab->pSchema;
65751             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
65752             pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
65753             if( i<pSrcList->nSrc-1 ){
65754               if( pItem[1].jointype & JT_NATURAL ){
65755                 /* If this match occurred in the left table of a natural join,
65756                 ** then skip the right table to avoid a duplicate match */
65757                 pItem++;
65758                 i++;
65759               }else if( (pUsing = pItem[1].pUsing)!=0 ){
65760                 /* If this match occurs on a column that is in the USING clause
65761                 ** of a join, skip the search of the right table of the join
65762                 ** to avoid a duplicate match there. */
65763                 int k;
65764                 for(k=0; k<pUsing->nId; k++){
65765                   if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
65766                     pItem++;
65767                     i++;
65768                     break;
65769                   }
65770                 }
65771               }
65772             }
65773             break;
65774           }
65775         }
65776       }
65777     }
65778
65779 #ifndef SQLITE_OMIT_TRIGGER
65780     /* If we have not already resolved the name, then maybe 
65781     ** it is a new.* or old.* trigger argument reference
65782     */
65783     if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
65784       int op = pParse->eTriggerOp;
65785       Table *pTab = 0;
65786       assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
65787       if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
65788         pExpr->iTable = 1;
65789         pTab = pParse->pTriggerTab;
65790       }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
65791         pExpr->iTable = 0;
65792         pTab = pParse->pTriggerTab;
65793       }
65794
65795       if( pTab ){ 
65796         int iCol;
65797         pSchema = pTab->pSchema;
65798         cntTab++;
65799         for(iCol=0; iCol<pTab->nCol; iCol++){
65800           Column *pCol = &pTab->aCol[iCol];
65801           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
65802             if( iCol==pTab->iPKey ){
65803               iCol = -1;
65804             }
65805             break;
65806           }
65807         }
65808         if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
65809           iCol = -1;        /* IMP: R-44911-55124 */
65810         }
65811         if( iCol<pTab->nCol ){
65812           cnt++;
65813           if( iCol<0 ){
65814             pExpr->affinity = SQLITE_AFF_INTEGER;
65815           }else if( pExpr->iTable==0 ){
65816             testcase( iCol==31 );
65817             testcase( iCol==32 );
65818             pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
65819           }else{
65820             testcase( iCol==31 );
65821             testcase( iCol==32 );
65822             pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
65823           }
65824           pExpr->iColumn = (i16)iCol;
65825           pExpr->pTab = pTab;
65826           isTrigger = 1;
65827         }
65828       }
65829     }
65830 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
65831
65832     /*
65833     ** Perhaps the name is a reference to the ROWID
65834     */
65835     if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
65836       cnt = 1;
65837       pExpr->iColumn = -1;     /* IMP: R-44911-55124 */
65838       pExpr->affinity = SQLITE_AFF_INTEGER;
65839     }
65840
65841     /*
65842     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
65843     ** might refer to an result-set alias.  This happens, for example, when
65844     ** we are resolving names in the WHERE clause of the following command:
65845     **
65846     **     SELECT a+b AS x FROM table WHERE x<10;
65847     **
65848     ** In cases like this, replace pExpr with a copy of the expression that
65849     ** forms the result set entry ("a+b" in the example) and return immediately.
65850     ** Note that the expression in the result set should have already been
65851     ** resolved by the time the WHERE clause is resolved.
65852     */
65853     if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
65854       for(j=0; j<pEList->nExpr; j++){
65855         char *zAs = pEList->a[j].zName;
65856         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
65857           Expr *pOrig;
65858           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
65859           assert( pExpr->x.pList==0 );
65860           assert( pExpr->x.pSelect==0 );
65861           pOrig = pEList->a[j].pExpr;
65862           if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
65863             sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
65864             return WRC_Abort;
65865           }
65866           resolveAlias(pParse, pEList, j, pExpr, "");
65867           cnt = 1;
65868           pMatch = 0;
65869           assert( zTab==0 && zDb==0 );
65870           goto lookupname_end;
65871         }
65872       } 
65873     }
65874
65875     /* Advance to the next name context.  The loop will exit when either
65876     ** we have a match (cnt>0) or when we run out of name contexts.
65877     */
65878     if( cnt==0 ){
65879       pNC = pNC->pNext;
65880     }
65881   }
65882
65883   /*
65884   ** If X and Y are NULL (in other words if only the column name Z is
65885   ** supplied) and the value of Z is enclosed in double-quotes, then
65886   ** Z is a string literal if it doesn't match any column names.  In that
65887   ** case, we need to return right away and not make any changes to
65888   ** pExpr.
65889   **
65890   ** Because no reference was made to outer contexts, the pNC->nRef
65891   ** fields are not changed in any context.
65892   */
65893   if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
65894     pExpr->op = TK_STRING;
65895     pExpr->pTab = 0;
65896     return WRC_Prune;
65897   }
65898
65899   /*
65900   ** cnt==0 means there was not match.  cnt>1 means there were two or
65901   ** more matches.  Either way, we have an error.
65902   */
65903   if( cnt!=1 ){
65904     const char *zErr;
65905     zErr = cnt==0 ? "no such column" : "ambiguous column name";
65906     if( zDb ){
65907       sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
65908     }else if( zTab ){
65909       sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
65910     }else{
65911       sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
65912     }
65913     pParse->checkSchema = 1;
65914     pTopNC->nErr++;
65915   }
65916
65917   /* If a column from a table in pSrcList is referenced, then record
65918   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
65919   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
65920   ** column number is greater than the number of bits in the bitmask
65921   ** then set the high-order bit of the bitmask.
65922   */
65923   if( pExpr->iColumn>=0 && pMatch!=0 ){
65924     int n = pExpr->iColumn;
65925     testcase( n==BMS-1 );
65926     if( n>=BMS ){
65927       n = BMS-1;
65928     }
65929     assert( pMatch->iCursor==pExpr->iTable );
65930     pMatch->colUsed |= ((Bitmask)1)<<n;
65931   }
65932
65933   /* Clean up and return
65934   */
65935   sqlite3ExprDelete(db, pExpr->pLeft);
65936   pExpr->pLeft = 0;
65937   sqlite3ExprDelete(db, pExpr->pRight);
65938   pExpr->pRight = 0;
65939   pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
65940 lookupname_end:
65941   if( cnt==1 ){
65942     assert( pNC!=0 );
65943     sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
65944     /* Increment the nRef value on all name contexts from TopNC up to
65945     ** the point where the name matched. */
65946     for(;;){
65947       assert( pTopNC!=0 );
65948       pTopNC->nRef++;
65949       if( pTopNC==pNC ) break;
65950       pTopNC = pTopNC->pNext;
65951     }
65952     return WRC_Prune;
65953   } else {
65954     return WRC_Abort;
65955   }
65956 }
65957
65958 /*
65959 ** Allocate and return a pointer to an expression to load the column iCol
65960 ** from datasource iSrc in SrcList pSrc.
65961 */
65962 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
65963   Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
65964   if( p ){
65965     struct SrcList_item *pItem = &pSrc->a[iSrc];
65966     p->pTab = pItem->pTab;
65967     p->iTable = pItem->iCursor;
65968     if( p->pTab->iPKey==iCol ){
65969       p->iColumn = -1;
65970     }else{
65971       p->iColumn = (ynVar)iCol;
65972       testcase( iCol==BMS );
65973       testcase( iCol==BMS-1 );
65974       pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
65975     }
65976     ExprSetProperty(p, EP_Resolved);
65977   }
65978   return p;
65979 }
65980
65981 /*
65982 ** This routine is callback for sqlite3WalkExpr().
65983 **
65984 ** Resolve symbolic names into TK_COLUMN operators for the current
65985 ** node in the expression tree.  Return 0 to continue the search down
65986 ** the tree or 2 to abort the tree walk.
65987 **
65988 ** This routine also does error checking and name resolution for
65989 ** function names.  The operator for aggregate functions is changed
65990 ** to TK_AGG_FUNCTION.
65991 */
65992 static int resolveExprStep(Walker *pWalker, Expr *pExpr){
65993   NameContext *pNC;
65994   Parse *pParse;
65995
65996   pNC = pWalker->u.pNC;
65997   assert( pNC!=0 );
65998   pParse = pNC->pParse;
65999   assert( pParse==pWalker->pParse );
66000
66001   if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
66002   ExprSetProperty(pExpr, EP_Resolved);
66003 #ifndef NDEBUG
66004   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
66005     SrcList *pSrcList = pNC->pSrcList;
66006     int i;
66007     for(i=0; i<pNC->pSrcList->nSrc; i++){
66008       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
66009     }
66010   }
66011 #endif
66012   switch( pExpr->op ){
66013
66014 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
66015     /* The special operator TK_ROW means use the rowid for the first
66016     ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
66017     ** clause processing on UPDATE and DELETE statements.
66018     */
66019     case TK_ROW: {
66020       SrcList *pSrcList = pNC->pSrcList;
66021       struct SrcList_item *pItem;
66022       assert( pSrcList && pSrcList->nSrc==1 );
66023       pItem = pSrcList->a; 
66024       pExpr->op = TK_COLUMN;
66025       pExpr->pTab = pItem->pTab;
66026       pExpr->iTable = pItem->iCursor;
66027       pExpr->iColumn = -1;
66028       pExpr->affinity = SQLITE_AFF_INTEGER;
66029       break;
66030     }
66031 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
66032
66033     /* A lone identifier is the name of a column.
66034     */
66035     case TK_ID: {
66036       return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
66037     }
66038   
66039     /* A table name and column name:     ID.ID
66040     ** Or a database, table and column:  ID.ID.ID
66041     */
66042     case TK_DOT: {
66043       const char *zColumn;
66044       const char *zTable;
66045       const char *zDb;
66046       Expr *pRight;
66047
66048       /* if( pSrcList==0 ) break; */
66049       pRight = pExpr->pRight;
66050       if( pRight->op==TK_ID ){
66051         zDb = 0;
66052         zTable = pExpr->pLeft->u.zToken;
66053         zColumn = pRight->u.zToken;
66054       }else{
66055         assert( pRight->op==TK_DOT );
66056         zDb = pExpr->pLeft->u.zToken;
66057         zTable = pRight->pLeft->u.zToken;
66058         zColumn = pRight->pRight->u.zToken;
66059       }
66060       return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
66061     }
66062
66063     /* Resolve function names
66064     */
66065     case TK_CONST_FUNC:
66066     case TK_FUNCTION: {
66067       ExprList *pList = pExpr->x.pList;    /* The argument list */
66068       int n = pList ? pList->nExpr : 0;    /* Number of arguments */
66069       int no_such_func = 0;       /* True if no such function exists */
66070       int wrong_num_args = 0;     /* True if wrong number of arguments */
66071       int is_agg = 0;             /* True if is an aggregate function */
66072       int auth;                   /* Authorization to use the function */
66073       int nId;                    /* Number of characters in function name */
66074       const char *zId;            /* The function name. */
66075       FuncDef *pDef;              /* Information about the function */
66076       u8 enc = ENC(pParse->db);   /* The database encoding */
66077
66078       testcase( pExpr->op==TK_CONST_FUNC );
66079       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
66080       zId = pExpr->u.zToken;
66081       nId = sqlite3Strlen30(zId);
66082       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
66083       if( pDef==0 ){
66084         pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
66085         if( pDef==0 ){
66086           no_such_func = 1;
66087         }else{
66088           wrong_num_args = 1;
66089         }
66090       }else{
66091         is_agg = pDef->xFunc==0;
66092       }
66093 #ifndef SQLITE_OMIT_AUTHORIZATION
66094       if( pDef ){
66095         auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
66096         if( auth!=SQLITE_OK ){
66097           if( auth==SQLITE_DENY ){
66098             sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
66099                                     pDef->zName);
66100             pNC->nErr++;
66101           }
66102           pExpr->op = TK_NULL;
66103           return WRC_Prune;
66104         }
66105       }
66106 #endif
66107       if( is_agg && !pNC->allowAgg ){
66108         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
66109         pNC->nErr++;
66110         is_agg = 0;
66111       }else if( no_such_func ){
66112         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
66113         pNC->nErr++;
66114       }else if( wrong_num_args ){
66115         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
66116              nId, zId);
66117         pNC->nErr++;
66118       }
66119       if( is_agg ){
66120         pExpr->op = TK_AGG_FUNCTION;
66121         pNC->hasAgg = 1;
66122       }
66123       if( is_agg ) pNC->allowAgg = 0;
66124       sqlite3WalkExprList(pWalker, pList);
66125       if( is_agg ) pNC->allowAgg = 1;
66126       /* FIX ME:  Compute pExpr->affinity based on the expected return
66127       ** type of the function 
66128       */
66129       return WRC_Prune;
66130     }
66131 #ifndef SQLITE_OMIT_SUBQUERY
66132     case TK_SELECT:
66133     case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
66134 #endif
66135     case TK_IN: {
66136       testcase( pExpr->op==TK_IN );
66137       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
66138         int nRef = pNC->nRef;
66139 #ifndef SQLITE_OMIT_CHECK
66140         if( pNC->isCheck ){
66141           sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
66142         }
66143 #endif
66144         sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
66145         assert( pNC->nRef>=nRef );
66146         if( nRef!=pNC->nRef ){
66147           ExprSetProperty(pExpr, EP_VarSelect);
66148         }
66149       }
66150       break;
66151     }
66152 #ifndef SQLITE_OMIT_CHECK
66153     case TK_VARIABLE: {
66154       if( pNC->isCheck ){
66155         sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
66156       }
66157       break;
66158     }
66159 #endif
66160   }
66161   return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
66162 }
66163
66164 /*
66165 ** pEList is a list of expressions which are really the result set of the
66166 ** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
66167 ** This routine checks to see if pE is a simple identifier which corresponds
66168 ** to the AS-name of one of the terms of the expression list.  If it is,
66169 ** this routine return an integer between 1 and N where N is the number of
66170 ** elements in pEList, corresponding to the matching entry.  If there is
66171 ** no match, or if pE is not a simple identifier, then this routine
66172 ** return 0.
66173 **
66174 ** pEList has been resolved.  pE has not.
66175 */
66176 static int resolveAsName(
66177   Parse *pParse,     /* Parsing context for error messages */
66178   ExprList *pEList,  /* List of expressions to scan */
66179   Expr *pE           /* Expression we are trying to match */
66180 ){
66181   int i;             /* Loop counter */
66182
66183   UNUSED_PARAMETER(pParse);
66184
66185   if( pE->op==TK_ID ){
66186     char *zCol = pE->u.zToken;
66187     for(i=0; i<pEList->nExpr; i++){
66188       char *zAs = pEList->a[i].zName;
66189       if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
66190         return i+1;
66191       }
66192     }
66193   }
66194   return 0;
66195 }
66196
66197 /*
66198 ** pE is a pointer to an expression which is a single term in the
66199 ** ORDER BY of a compound SELECT.  The expression has not been
66200 ** name resolved.
66201 **
66202 ** At the point this routine is called, we already know that the
66203 ** ORDER BY term is not an integer index into the result set.  That
66204 ** case is handled by the calling routine.
66205 **
66206 ** Attempt to match pE against result set columns in the left-most
66207 ** SELECT statement.  Return the index i of the matching column,
66208 ** as an indication to the caller that it should sort by the i-th column.
66209 ** The left-most column is 1.  In other words, the value returned is the
66210 ** same integer value that would be used in the SQL statement to indicate
66211 ** the column.
66212 **
66213 ** If there is no match, return 0.  Return -1 if an error occurs.
66214 */
66215 static int resolveOrderByTermToExprList(
66216   Parse *pParse,     /* Parsing context for error messages */
66217   Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
66218   Expr *pE           /* The specific ORDER BY term */
66219 ){
66220   int i;             /* Loop counter */
66221   ExprList *pEList;  /* The columns of the result set */
66222   NameContext nc;    /* Name context for resolving pE */
66223   sqlite3 *db;       /* Database connection */
66224   int rc;            /* Return code from subprocedures */
66225   u8 savedSuppErr;   /* Saved value of db->suppressErr */
66226
66227   assert( sqlite3ExprIsInteger(pE, &i)==0 );
66228   pEList = pSelect->pEList;
66229
66230   /* Resolve all names in the ORDER BY term expression
66231   */
66232   memset(&nc, 0, sizeof(nc));
66233   nc.pParse = pParse;
66234   nc.pSrcList = pSelect->pSrc;
66235   nc.pEList = pEList;
66236   nc.allowAgg = 1;
66237   nc.nErr = 0;
66238   db = pParse->db;
66239   savedSuppErr = db->suppressErr;
66240   db->suppressErr = 1;
66241   rc = sqlite3ResolveExprNames(&nc, pE);
66242   db->suppressErr = savedSuppErr;
66243   if( rc ) return 0;
66244
66245   /* Try to match the ORDER BY expression against an expression
66246   ** in the result set.  Return an 1-based index of the matching
66247   ** result-set entry.
66248   */
66249   for(i=0; i<pEList->nExpr; i++){
66250     if( sqlite3ExprCompare(pEList->a[i].pExpr, pE)<2 ){
66251       return i+1;
66252     }
66253   }
66254
66255   /* If no match, return 0. */
66256   return 0;
66257 }
66258
66259 /*
66260 ** Generate an ORDER BY or GROUP BY term out-of-range error.
66261 */
66262 static void resolveOutOfRangeError(
66263   Parse *pParse,         /* The error context into which to write the error */
66264   const char *zType,     /* "ORDER" or "GROUP" */
66265   int i,                 /* The index (1-based) of the term out of range */
66266   int mx                 /* Largest permissible value of i */
66267 ){
66268   sqlite3ErrorMsg(pParse, 
66269     "%r %s BY term out of range - should be "
66270     "between 1 and %d", i, zType, mx);
66271 }
66272
66273 /*
66274 ** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
66275 ** each term of the ORDER BY clause is a constant integer between 1
66276 ** and N where N is the number of columns in the compound SELECT.
66277 **
66278 ** ORDER BY terms that are already an integer between 1 and N are
66279 ** unmodified.  ORDER BY terms that are integers outside the range of
66280 ** 1 through N generate an error.  ORDER BY terms that are expressions
66281 ** are matched against result set expressions of compound SELECT
66282 ** beginning with the left-most SELECT and working toward the right.
66283 ** At the first match, the ORDER BY expression is transformed into
66284 ** the integer column number.
66285 **
66286 ** Return the number of errors seen.
66287 */
66288 static int resolveCompoundOrderBy(
66289   Parse *pParse,        /* Parsing context.  Leave error messages here */
66290   Select *pSelect       /* The SELECT statement containing the ORDER BY */
66291 ){
66292   int i;
66293   ExprList *pOrderBy;
66294   ExprList *pEList;
66295   sqlite3 *db;
66296   int moreToDo = 1;
66297
66298   pOrderBy = pSelect->pOrderBy;
66299   if( pOrderBy==0 ) return 0;
66300   db = pParse->db;
66301 #if SQLITE_MAX_COLUMN
66302   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
66303     sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
66304     return 1;
66305   }
66306 #endif
66307   for(i=0; i<pOrderBy->nExpr; i++){
66308     pOrderBy->a[i].done = 0;
66309   }
66310   pSelect->pNext = 0;
66311   while( pSelect->pPrior ){
66312     pSelect->pPrior->pNext = pSelect;
66313     pSelect = pSelect->pPrior;
66314   }
66315   while( pSelect && moreToDo ){
66316     struct ExprList_item *pItem;
66317     moreToDo = 0;
66318     pEList = pSelect->pEList;
66319     assert( pEList!=0 );
66320     for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
66321       int iCol = -1;
66322       Expr *pE, *pDup;
66323       if( pItem->done ) continue;
66324       pE = pItem->pExpr;
66325       if( sqlite3ExprIsInteger(pE, &iCol) ){
66326         if( iCol<=0 || iCol>pEList->nExpr ){
66327           resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
66328           return 1;
66329         }
66330       }else{
66331         iCol = resolveAsName(pParse, pEList, pE);
66332         if( iCol==0 ){
66333           pDup = sqlite3ExprDup(db, pE, 0);
66334           if( !db->mallocFailed ){
66335             assert(pDup);
66336             iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
66337           }
66338           sqlite3ExprDelete(db, pDup);
66339         }
66340       }
66341       if( iCol>0 ){
66342         CollSeq *pColl = pE->pColl;
66343         int flags = pE->flags & EP_ExpCollate;
66344         sqlite3ExprDelete(db, pE);
66345         pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0);
66346         if( pE==0 ) return 1;
66347         pE->pColl = pColl;
66348         pE->flags |= EP_IntValue | flags;
66349         pE->u.iValue = iCol;
66350         pItem->iCol = (u16)iCol;
66351         pItem->done = 1;
66352       }else{
66353         moreToDo = 1;
66354       }
66355     }
66356     pSelect = pSelect->pNext;
66357   }
66358   for(i=0; i<pOrderBy->nExpr; i++){
66359     if( pOrderBy->a[i].done==0 ){
66360       sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
66361             "column in the result set", i+1);
66362       return 1;
66363     }
66364   }
66365   return 0;
66366 }
66367
66368 /*
66369 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
66370 ** the SELECT statement pSelect.  If any term is reference to a
66371 ** result set expression (as determined by the ExprList.a.iCol field)
66372 ** then convert that term into a copy of the corresponding result set
66373 ** column.
66374 **
66375 ** If any errors are detected, add an error message to pParse and
66376 ** return non-zero.  Return zero if no errors are seen.
66377 */
66378 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
66379   Parse *pParse,        /* Parsing context.  Leave error messages here */
66380   Select *pSelect,      /* The SELECT statement containing the clause */
66381   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
66382   const char *zType     /* "ORDER" or "GROUP" */
66383 ){
66384   int i;
66385   sqlite3 *db = pParse->db;
66386   ExprList *pEList;
66387   struct ExprList_item *pItem;
66388
66389   if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
66390 #if SQLITE_MAX_COLUMN
66391   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
66392     sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
66393     return 1;
66394   }
66395 #endif
66396   pEList = pSelect->pEList;
66397   assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
66398   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
66399     if( pItem->iCol ){
66400       if( pItem->iCol>pEList->nExpr ){
66401         resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
66402         return 1;
66403       }
66404       resolveAlias(pParse, pEList, pItem->iCol-1, pItem->pExpr, zType);
66405     }
66406   }
66407   return 0;
66408 }
66409
66410 /*
66411 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
66412 ** The Name context of the SELECT statement is pNC.  zType is either
66413 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
66414 **
66415 ** This routine resolves each term of the clause into an expression.
66416 ** If the order-by term is an integer I between 1 and N (where N is the
66417 ** number of columns in the result set of the SELECT) then the expression
66418 ** in the resolution is a copy of the I-th result-set expression.  If
66419 ** the order-by term is an identify that corresponds to the AS-name of
66420 ** a result-set expression, then the term resolves to a copy of the
66421 ** result-set expression.  Otherwise, the expression is resolved in
66422 ** the usual way - using sqlite3ResolveExprNames().
66423 **
66424 ** This routine returns the number of errors.  If errors occur, then
66425 ** an appropriate error message might be left in pParse.  (OOM errors
66426 ** excepted.)
66427 */
66428 static int resolveOrderGroupBy(
66429   NameContext *pNC,     /* The name context of the SELECT statement */
66430   Select *pSelect,      /* The SELECT statement holding pOrderBy */
66431   ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
66432   const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
66433 ){
66434   int i;                         /* Loop counter */
66435   int iCol;                      /* Column number */
66436   struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
66437   Parse *pParse;                 /* Parsing context */
66438   int nResult;                   /* Number of terms in the result set */
66439
66440   if( pOrderBy==0 ) return 0;
66441   nResult = pSelect->pEList->nExpr;
66442   pParse = pNC->pParse;
66443   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
66444     Expr *pE = pItem->pExpr;
66445     iCol = resolveAsName(pParse, pSelect->pEList, pE);
66446     if( iCol>0 ){
66447       /* If an AS-name match is found, mark this ORDER BY column as being
66448       ** a copy of the iCol-th result-set column.  The subsequent call to
66449       ** sqlite3ResolveOrderGroupBy() will convert the expression to a
66450       ** copy of the iCol-th result-set expression. */
66451       pItem->iCol = (u16)iCol;
66452       continue;
66453     }
66454     if( sqlite3ExprIsInteger(pE, &iCol) ){
66455       /* The ORDER BY term is an integer constant.  Again, set the column
66456       ** number so that sqlite3ResolveOrderGroupBy() will convert the
66457       ** order-by term to a copy of the result-set expression */
66458       if( iCol<1 ){
66459         resolveOutOfRangeError(pParse, zType, i+1, nResult);
66460         return 1;
66461       }
66462       pItem->iCol = (u16)iCol;
66463       continue;
66464     }
66465
66466     /* Otherwise, treat the ORDER BY term as an ordinary expression */
66467     pItem->iCol = 0;
66468     if( sqlite3ResolveExprNames(pNC, pE) ){
66469       return 1;
66470     }
66471   }
66472   return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
66473 }
66474
66475 /*
66476 ** Resolve names in the SELECT statement p and all of its descendents.
66477 */
66478 static int resolveSelectStep(Walker *pWalker, Select *p){
66479   NameContext *pOuterNC;  /* Context that contains this SELECT */
66480   NameContext sNC;        /* Name context of this SELECT */
66481   int isCompound;         /* True if p is a compound select */
66482   int nCompound;          /* Number of compound terms processed so far */
66483   Parse *pParse;          /* Parsing context */
66484   ExprList *pEList;       /* Result set expression list */
66485   int i;                  /* Loop counter */
66486   ExprList *pGroupBy;     /* The GROUP BY clause */
66487   Select *pLeftmost;      /* Left-most of SELECT of a compound */
66488   sqlite3 *db;            /* Database connection */
66489   
66490
66491   assert( p!=0 );
66492   if( p->selFlags & SF_Resolved ){
66493     return WRC_Prune;
66494   }
66495   pOuterNC = pWalker->u.pNC;
66496   pParse = pWalker->pParse;
66497   db = pParse->db;
66498
66499   /* Normally sqlite3SelectExpand() will be called first and will have
66500   ** already expanded this SELECT.  However, if this is a subquery within
66501   ** an expression, sqlite3ResolveExprNames() will be called without a
66502   ** prior call to sqlite3SelectExpand().  When that happens, let
66503   ** sqlite3SelectPrep() do all of the processing for this SELECT.
66504   ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
66505   ** this routine in the correct order.
66506   */
66507   if( (p->selFlags & SF_Expanded)==0 ){
66508     sqlite3SelectPrep(pParse, p, pOuterNC);
66509     return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
66510   }
66511
66512   isCompound = p->pPrior!=0;
66513   nCompound = 0;
66514   pLeftmost = p;
66515   while( p ){
66516     assert( (p->selFlags & SF_Expanded)!=0 );
66517     assert( (p->selFlags & SF_Resolved)==0 );
66518     p->selFlags |= SF_Resolved;
66519
66520     /* Resolve the expressions in the LIMIT and OFFSET clauses. These
66521     ** are not allowed to refer to any names, so pass an empty NameContext.
66522     */
66523     memset(&sNC, 0, sizeof(sNC));
66524     sNC.pParse = pParse;
66525     if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
66526         sqlite3ResolveExprNames(&sNC, p->pOffset) ){
66527       return WRC_Abort;
66528     }
66529   
66530     /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
66531     ** resolve the result-set expression list.
66532     */
66533     sNC.allowAgg = 1;
66534     sNC.pSrcList = p->pSrc;
66535     sNC.pNext = pOuterNC;
66536   
66537     /* Resolve names in the result set. */
66538     pEList = p->pEList;
66539     assert( pEList!=0 );
66540     for(i=0; i<pEList->nExpr; i++){
66541       Expr *pX = pEList->a[i].pExpr;
66542       if( sqlite3ResolveExprNames(&sNC, pX) ){
66543         return WRC_Abort;
66544       }
66545     }
66546   
66547     /* Recursively resolve names in all subqueries
66548     */
66549     for(i=0; i<p->pSrc->nSrc; i++){
66550       struct SrcList_item *pItem = &p->pSrc->a[i];
66551       if( pItem->pSelect ){
66552         const char *zSavedContext = pParse->zAuthContext;
66553         if( pItem->zName ) pParse->zAuthContext = pItem->zName;
66554         sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
66555         pParse->zAuthContext = zSavedContext;
66556         if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
66557       }
66558     }
66559   
66560     /* If there are no aggregate functions in the result-set, and no GROUP BY 
66561     ** expression, do not allow aggregates in any of the other expressions.
66562     */
66563     assert( (p->selFlags & SF_Aggregate)==0 );
66564     pGroupBy = p->pGroupBy;
66565     if( pGroupBy || sNC.hasAgg ){
66566       p->selFlags |= SF_Aggregate;
66567     }else{
66568       sNC.allowAgg = 0;
66569     }
66570   
66571     /* If a HAVING clause is present, then there must be a GROUP BY clause.
66572     */
66573     if( p->pHaving && !pGroupBy ){
66574       sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
66575       return WRC_Abort;
66576     }
66577   
66578     /* Add the expression list to the name-context before parsing the
66579     ** other expressions in the SELECT statement. This is so that
66580     ** expressions in the WHERE clause (etc.) can refer to expressions by
66581     ** aliases in the result set.
66582     **
66583     ** Minor point: If this is the case, then the expression will be
66584     ** re-evaluated for each reference to it.
66585     */
66586     sNC.pEList = p->pEList;
66587     if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
66588        sqlite3ResolveExprNames(&sNC, p->pHaving)
66589     ){
66590       return WRC_Abort;
66591     }
66592
66593     /* The ORDER BY and GROUP BY clauses may not refer to terms in
66594     ** outer queries 
66595     */
66596     sNC.pNext = 0;
66597     sNC.allowAgg = 1;
66598
66599     /* Process the ORDER BY clause for singleton SELECT statements.
66600     ** The ORDER BY clause for compounds SELECT statements is handled
66601     ** below, after all of the result-sets for all of the elements of
66602     ** the compound have been resolved.
66603     */
66604     if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
66605       return WRC_Abort;
66606     }
66607     if( db->mallocFailed ){
66608       return WRC_Abort;
66609     }
66610   
66611     /* Resolve the GROUP BY clause.  At the same time, make sure 
66612     ** the GROUP BY clause does not contain aggregate functions.
66613     */
66614     if( pGroupBy ){
66615       struct ExprList_item *pItem;
66616     
66617       if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
66618         return WRC_Abort;
66619       }
66620       for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
66621         if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
66622           sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
66623               "the GROUP BY clause");
66624           return WRC_Abort;
66625         }
66626       }
66627     }
66628
66629     /* Advance to the next term of the compound
66630     */
66631     p = p->pPrior;
66632     nCompound++;
66633   }
66634
66635   /* Resolve the ORDER BY on a compound SELECT after all terms of
66636   ** the compound have been resolved.
66637   */
66638   if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
66639     return WRC_Abort;
66640   }
66641
66642   return WRC_Prune;
66643 }
66644
66645 /*
66646 ** This routine walks an expression tree and resolves references to
66647 ** table columns and result-set columns.  At the same time, do error
66648 ** checking on function usage and set a flag if any aggregate functions
66649 ** are seen.
66650 **
66651 ** To resolve table columns references we look for nodes (or subtrees) of the 
66652 ** form X.Y.Z or Y.Z or just Z where
66653 **
66654 **      X:   The name of a database.  Ex:  "main" or "temp" or
66655 **           the symbolic name assigned to an ATTACH-ed database.
66656 **
66657 **      Y:   The name of a table in a FROM clause.  Or in a trigger
66658 **           one of the special names "old" or "new".
66659 **
66660 **      Z:   The name of a column in table Y.
66661 **
66662 ** The node at the root of the subtree is modified as follows:
66663 **
66664 **    Expr.op        Changed to TK_COLUMN
66665 **    Expr.pTab      Points to the Table object for X.Y
66666 **    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
66667 **    Expr.iTable    The VDBE cursor number for X.Y
66668 **
66669 **
66670 ** To resolve result-set references, look for expression nodes of the
66671 ** form Z (with no X and Y prefix) where the Z matches the right-hand
66672 ** size of an AS clause in the result-set of a SELECT.  The Z expression
66673 ** is replaced by a copy of the left-hand side of the result-set expression.
66674 ** Table-name and function resolution occurs on the substituted expression
66675 ** tree.  For example, in:
66676 **
66677 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
66678 **
66679 ** The "x" term of the order by is replaced by "a+b" to render:
66680 **
66681 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
66682 **
66683 ** Function calls are checked to make sure that the function is 
66684 ** defined and that the correct number of arguments are specified.
66685 ** If the function is an aggregate function, then the pNC->hasAgg is
66686 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
66687 ** If an expression contains aggregate functions then the EP_Agg
66688 ** property on the expression is set.
66689 **
66690 ** An error message is left in pParse if anything is amiss.  The number
66691 ** if errors is returned.
66692 */
66693 SQLITE_PRIVATE int sqlite3ResolveExprNames( 
66694   NameContext *pNC,       /* Namespace to resolve expressions in. */
66695   Expr *pExpr             /* The expression to be analyzed. */
66696 ){
66697   int savedHasAgg;
66698   Walker w;
66699
66700   if( pExpr==0 ) return 0;
66701 #if SQLITE_MAX_EXPR_DEPTH>0
66702   {
66703     Parse *pParse = pNC->pParse;
66704     if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
66705       return 1;
66706     }
66707     pParse->nHeight += pExpr->nHeight;
66708   }
66709 #endif
66710   savedHasAgg = pNC->hasAgg;
66711   pNC->hasAgg = 0;
66712   w.xExprCallback = resolveExprStep;
66713   w.xSelectCallback = resolveSelectStep;
66714   w.pParse = pNC->pParse;
66715   w.u.pNC = pNC;
66716   sqlite3WalkExpr(&w, pExpr);
66717 #if SQLITE_MAX_EXPR_DEPTH>0
66718   pNC->pParse->nHeight -= pExpr->nHeight;
66719 #endif
66720   if( pNC->nErr>0 || w.pParse->nErr>0 ){
66721     ExprSetProperty(pExpr, EP_Error);
66722   }
66723   if( pNC->hasAgg ){
66724     ExprSetProperty(pExpr, EP_Agg);
66725   }else if( savedHasAgg ){
66726     pNC->hasAgg = 1;
66727   }
66728   return ExprHasProperty(pExpr, EP_Error);
66729 }
66730
66731
66732 /*
66733 ** Resolve all names in all expressions of a SELECT and in all
66734 ** decendents of the SELECT, including compounds off of p->pPrior,
66735 ** subqueries in expressions, and subqueries used as FROM clause
66736 ** terms.
66737 **
66738 ** See sqlite3ResolveExprNames() for a description of the kinds of
66739 ** transformations that occur.
66740 **
66741 ** All SELECT statements should have been expanded using
66742 ** sqlite3SelectExpand() prior to invoking this routine.
66743 */
66744 SQLITE_PRIVATE void sqlite3ResolveSelectNames(
66745   Parse *pParse,         /* The parser context */
66746   Select *p,             /* The SELECT statement being coded. */
66747   NameContext *pOuterNC  /* Name context for parent SELECT statement */
66748 ){
66749   Walker w;
66750
66751   assert( p!=0 );
66752   w.xExprCallback = resolveExprStep;
66753   w.xSelectCallback = resolveSelectStep;
66754   w.pParse = pParse;
66755   w.u.pNC = pOuterNC;
66756   sqlite3WalkSelect(&w, p);
66757 }
66758
66759 /************** End of resolve.c *********************************************/
66760 /************** Begin file expr.c ********************************************/
66761 /*
66762 ** 2001 September 15
66763 **
66764 ** The author disclaims copyright to this source code.  In place of
66765 ** a legal notice, here is a blessing:
66766 **
66767 **    May you do good and not evil.
66768 **    May you find forgiveness for yourself and forgive others.
66769 **    May you share freely, never taking more than you give.
66770 **
66771 *************************************************************************
66772 ** This file contains routines used for analyzing expressions and
66773 ** for generating VDBE code that evaluates expressions in SQLite.
66774 */
66775
66776 /*
66777 ** Return the 'affinity' of the expression pExpr if any.
66778 **
66779 ** If pExpr is a column, a reference to a column via an 'AS' alias,
66780 ** or a sub-select with a column as the return value, then the 
66781 ** affinity of that column is returned. Otherwise, 0x00 is returned,
66782 ** indicating no affinity for the expression.
66783 **
66784 ** i.e. the WHERE clause expresssions in the following statements all
66785 ** have an affinity:
66786 **
66787 ** CREATE TABLE t1(a);
66788 ** SELECT * FROM t1 WHERE a;
66789 ** SELECT a AS b FROM t1 WHERE b;
66790 ** SELECT * FROM t1 WHERE (select a from t1);
66791 */
66792 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
66793   int op = pExpr->op;
66794   if( op==TK_SELECT ){
66795     assert( pExpr->flags&EP_xIsSelect );
66796     return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
66797   }
66798 #ifndef SQLITE_OMIT_CAST
66799   if( op==TK_CAST ){
66800     assert( !ExprHasProperty(pExpr, EP_IntValue) );
66801     return sqlite3AffinityType(pExpr->u.zToken);
66802   }
66803 #endif
66804   if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER) 
66805    && pExpr->pTab!=0
66806   ){
66807     /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
66808     ** a TK_COLUMN but was previously evaluated and cached in a register */
66809     int j = pExpr->iColumn;
66810     if( j<0 ) return SQLITE_AFF_INTEGER;
66811     assert( pExpr->pTab && j<pExpr->pTab->nCol );
66812     return pExpr->pTab->aCol[j].affinity;
66813   }
66814   return pExpr->affinity;
66815 }
66816
66817 /*
66818 ** Set the collating sequence for expression pExpr to be the collating
66819 ** sequence named by pToken.   Return a pointer to the revised expression.
66820 ** The collating sequence is marked as "explicit" using the EP_ExpCollate
66821 ** flag.  An explicit collating sequence will override implicit
66822 ** collating sequences.
66823 */
66824 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Parse *pParse, Expr *pExpr, Token *pCollName){
66825   char *zColl = 0;            /* Dequoted name of collation sequence */
66826   CollSeq *pColl;
66827   sqlite3 *db = pParse->db;
66828   zColl = sqlite3NameFromToken(db, pCollName);
66829   if( pExpr && zColl ){
66830     pColl = sqlite3LocateCollSeq(pParse, zColl);
66831     if( pColl ){
66832       pExpr->pColl = pColl;
66833       pExpr->flags |= EP_ExpCollate;
66834     }
66835   }
66836   sqlite3DbFree(db, zColl);
66837   return pExpr;
66838 }
66839
66840 /*
66841 ** Return the default collation sequence for the expression pExpr. If
66842 ** there is no default collation type, return 0.
66843 */
66844 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
66845   CollSeq *pColl = 0;
66846   Expr *p = pExpr;
66847   while( ALWAYS(p) ){
66848     int op;
66849     pColl = p->pColl;
66850     if( pColl ) break;
66851     op = p->op;
66852     if( p->pTab!=0 && (
66853         op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER || op==TK_TRIGGER
66854     )){
66855       /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
66856       ** a TK_COLUMN but was previously evaluated and cached in a register */
66857       const char *zColl;
66858       int j = p->iColumn;
66859       if( j>=0 ){
66860         sqlite3 *db = pParse->db;
66861         zColl = p->pTab->aCol[j].zColl;
66862         pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
66863         pExpr->pColl = pColl;
66864       }
66865       break;
66866     }
66867     if( op!=TK_CAST && op!=TK_UPLUS ){
66868       break;
66869     }
66870     p = p->pLeft;
66871   }
66872   if( sqlite3CheckCollSeq(pParse, pColl) ){ 
66873     pColl = 0;
66874   }
66875   return pColl;
66876 }
66877
66878 /*
66879 ** pExpr is an operand of a comparison operator.  aff2 is the
66880 ** type affinity of the other operand.  This routine returns the
66881 ** type affinity that should be used for the comparison operator.
66882 */
66883 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
66884   char aff1 = sqlite3ExprAffinity(pExpr);
66885   if( aff1 && aff2 ){
66886     /* Both sides of the comparison are columns. If one has numeric
66887     ** affinity, use that. Otherwise use no affinity.
66888     */
66889     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
66890       return SQLITE_AFF_NUMERIC;
66891     }else{
66892       return SQLITE_AFF_NONE;
66893     }
66894   }else if( !aff1 && !aff2 ){
66895     /* Neither side of the comparison is a column.  Compare the
66896     ** results directly.
66897     */
66898     return SQLITE_AFF_NONE;
66899   }else{
66900     /* One side is a column, the other is not. Use the columns affinity. */
66901     assert( aff1==0 || aff2==0 );
66902     return (aff1 + aff2);
66903   }
66904 }
66905
66906 /*
66907 ** pExpr is a comparison operator.  Return the type affinity that should
66908 ** be applied to both operands prior to doing the comparison.
66909 */
66910 static char comparisonAffinity(Expr *pExpr){
66911   char aff;
66912   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
66913           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
66914           pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
66915   assert( pExpr->pLeft );
66916   aff = sqlite3ExprAffinity(pExpr->pLeft);
66917   if( pExpr->pRight ){
66918     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
66919   }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
66920     aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
66921   }else if( !aff ){
66922     aff = SQLITE_AFF_NONE;
66923   }
66924   return aff;
66925 }
66926
66927 /*
66928 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
66929 ** idx_affinity is the affinity of an indexed column. Return true
66930 ** if the index with affinity idx_affinity may be used to implement
66931 ** the comparison in pExpr.
66932 */
66933 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
66934   char aff = comparisonAffinity(pExpr);
66935   switch( aff ){
66936     case SQLITE_AFF_NONE:
66937       return 1;
66938     case SQLITE_AFF_TEXT:
66939       return idx_affinity==SQLITE_AFF_TEXT;
66940     default:
66941       return sqlite3IsNumericAffinity(idx_affinity);
66942   }
66943 }
66944
66945 /*
66946 ** Return the P5 value that should be used for a binary comparison
66947 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
66948 */
66949 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
66950   u8 aff = (char)sqlite3ExprAffinity(pExpr2);
66951   aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
66952   return aff;
66953 }
66954
66955 /*
66956 ** Return a pointer to the collation sequence that should be used by
66957 ** a binary comparison operator comparing pLeft and pRight.
66958 **
66959 ** If the left hand expression has a collating sequence type, then it is
66960 ** used. Otherwise the collation sequence for the right hand expression
66961 ** is used, or the default (BINARY) if neither expression has a collating
66962 ** type.
66963 **
66964 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
66965 ** it is not considered.
66966 */
66967 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
66968   Parse *pParse, 
66969   Expr *pLeft, 
66970   Expr *pRight
66971 ){
66972   CollSeq *pColl;
66973   assert( pLeft );
66974   if( pLeft->flags & EP_ExpCollate ){
66975     assert( pLeft->pColl );
66976     pColl = pLeft->pColl;
66977   }else if( pRight && pRight->flags & EP_ExpCollate ){
66978     assert( pRight->pColl );
66979     pColl = pRight->pColl;
66980   }else{
66981     pColl = sqlite3ExprCollSeq(pParse, pLeft);
66982     if( !pColl ){
66983       pColl = sqlite3ExprCollSeq(pParse, pRight);
66984     }
66985   }
66986   return pColl;
66987 }
66988
66989 /*
66990 ** Generate code for a comparison operator.
66991 */
66992 static int codeCompare(
66993   Parse *pParse,    /* The parsing (and code generating) context */
66994   Expr *pLeft,      /* The left operand */
66995   Expr *pRight,     /* The right operand */
66996   int opcode,       /* The comparison opcode */
66997   int in1, int in2, /* Register holding operands */
66998   int dest,         /* Jump here if true.  */
66999   int jumpIfNull    /* If true, jump if either operand is NULL */
67000 ){
67001   int p5;
67002   int addr;
67003   CollSeq *p4;
67004
67005   p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
67006   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
67007   addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
67008                            (void*)p4, P4_COLLSEQ);
67009   sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
67010   return addr;
67011 }
67012
67013 #if SQLITE_MAX_EXPR_DEPTH>0
67014 /*
67015 ** Check that argument nHeight is less than or equal to the maximum
67016 ** expression depth allowed. If it is not, leave an error message in
67017 ** pParse.
67018 */
67019 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
67020   int rc = SQLITE_OK;
67021   int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
67022   if( nHeight>mxHeight ){
67023     sqlite3ErrorMsg(pParse, 
67024        "Expression tree is too large (maximum depth %d)", mxHeight
67025     );
67026     rc = SQLITE_ERROR;
67027   }
67028   return rc;
67029 }
67030
67031 /* The following three functions, heightOfExpr(), heightOfExprList()
67032 ** and heightOfSelect(), are used to determine the maximum height
67033 ** of any expression tree referenced by the structure passed as the
67034 ** first argument.
67035 **
67036 ** If this maximum height is greater than the current value pointed
67037 ** to by pnHeight, the second parameter, then set *pnHeight to that
67038 ** value.
67039 */
67040 static void heightOfExpr(Expr *p, int *pnHeight){
67041   if( p ){
67042     if( p->nHeight>*pnHeight ){
67043       *pnHeight = p->nHeight;
67044     }
67045   }
67046 }
67047 static void heightOfExprList(ExprList *p, int *pnHeight){
67048   if( p ){
67049     int i;
67050     for(i=0; i<p->nExpr; i++){
67051       heightOfExpr(p->a[i].pExpr, pnHeight);
67052     }
67053   }
67054 }
67055 static void heightOfSelect(Select *p, int *pnHeight){
67056   if( p ){
67057     heightOfExpr(p->pWhere, pnHeight);
67058     heightOfExpr(p->pHaving, pnHeight);
67059     heightOfExpr(p->pLimit, pnHeight);
67060     heightOfExpr(p->pOffset, pnHeight);
67061     heightOfExprList(p->pEList, pnHeight);
67062     heightOfExprList(p->pGroupBy, pnHeight);
67063     heightOfExprList(p->pOrderBy, pnHeight);
67064     heightOfSelect(p->pPrior, pnHeight);
67065   }
67066 }
67067
67068 /*
67069 ** Set the Expr.nHeight variable in the structure passed as an 
67070 ** argument. An expression with no children, Expr.pList or 
67071 ** Expr.pSelect member has a height of 1. Any other expression
67072 ** has a height equal to the maximum height of any other 
67073 ** referenced Expr plus one.
67074 */
67075 static void exprSetHeight(Expr *p){
67076   int nHeight = 0;
67077   heightOfExpr(p->pLeft, &nHeight);
67078   heightOfExpr(p->pRight, &nHeight);
67079   if( ExprHasProperty(p, EP_xIsSelect) ){
67080     heightOfSelect(p->x.pSelect, &nHeight);
67081   }else{
67082     heightOfExprList(p->x.pList, &nHeight);
67083   }
67084   p->nHeight = nHeight + 1;
67085 }
67086
67087 /*
67088 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
67089 ** the height is greater than the maximum allowed expression depth,
67090 ** leave an error in pParse.
67091 */
67092 SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
67093   exprSetHeight(p);
67094   sqlite3ExprCheckHeight(pParse, p->nHeight);
67095 }
67096
67097 /*
67098 ** Return the maximum height of any expression tree referenced
67099 ** by the select statement passed as an argument.
67100 */
67101 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
67102   int nHeight = 0;
67103   heightOfSelect(p, &nHeight);
67104   return nHeight;
67105 }
67106 #else
67107   #define exprSetHeight(y)
67108 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
67109
67110 /*
67111 ** This routine is the core allocator for Expr nodes.
67112 **
67113 ** Construct a new expression node and return a pointer to it.  Memory
67114 ** for this node and for the pToken argument is a single allocation
67115 ** obtained from sqlite3DbMalloc().  The calling function
67116 ** is responsible for making sure the node eventually gets freed.
67117 **
67118 ** If dequote is true, then the token (if it exists) is dequoted.
67119 ** If dequote is false, no dequoting is performance.  The deQuote
67120 ** parameter is ignored if pToken is NULL or if the token does not
67121 ** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
67122 ** then the EP_DblQuoted flag is set on the expression node.
67123 **
67124 ** Special case:  If op==TK_INTEGER and pToken points to a string that
67125 ** can be translated into a 32-bit integer, then the token is not
67126 ** stored in u.zToken.  Instead, the integer values is written
67127 ** into u.iValue and the EP_IntValue flag is set.  No extra storage
67128 ** is allocated to hold the integer text and the dequote flag is ignored.
67129 */
67130 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
67131   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
67132   int op,                 /* Expression opcode */
67133   const Token *pToken,    /* Token argument.  Might be NULL */
67134   int dequote             /* True to dequote */
67135 ){
67136   Expr *pNew;
67137   int nExtra = 0;
67138   int iValue = 0;
67139
67140   if( pToken ){
67141     if( op!=TK_INTEGER || pToken->z==0
67142           || sqlite3GetInt32(pToken->z, &iValue)==0 ){
67143       nExtra = pToken->n+1;
67144     }
67145   }
67146   pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
67147   if( pNew ){
67148     pNew->op = (u8)op;
67149     pNew->iAgg = -1;
67150     if( pToken ){
67151       if( nExtra==0 ){
67152         pNew->flags |= EP_IntValue;
67153         pNew->u.iValue = iValue;
67154       }else{
67155         int c;
67156         pNew->u.zToken = (char*)&pNew[1];
67157         memcpy(pNew->u.zToken, pToken->z, pToken->n);
67158         pNew->u.zToken[pToken->n] = 0;
67159         if( dequote && nExtra>=3 
67160              && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
67161           sqlite3Dequote(pNew->u.zToken);
67162           if( c=='"' ) pNew->flags |= EP_DblQuoted;
67163         }
67164       }
67165     }
67166 #if SQLITE_MAX_EXPR_DEPTH>0
67167     pNew->nHeight = 1;
67168 #endif  
67169   }
67170   return pNew;
67171 }
67172
67173 /*
67174 ** Allocate a new expression node from a zero-terminated token that has
67175 ** already been dequoted.
67176 */
67177 SQLITE_PRIVATE Expr *sqlite3Expr(
67178   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
67179   int op,                 /* Expression opcode */
67180   const char *zToken      /* Token argument.  Might be NULL */
67181 ){
67182   Token x;
67183   x.z = zToken;
67184   x.n = zToken ? sqlite3Strlen30(zToken) : 0;
67185   return sqlite3ExprAlloc(db, op, &x, 0);
67186 }
67187
67188 /*
67189 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
67190 **
67191 ** If pRoot==NULL that means that a memory allocation error has occurred.
67192 ** In that case, delete the subtrees pLeft and pRight.
67193 */
67194 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
67195   sqlite3 *db,
67196   Expr *pRoot,
67197   Expr *pLeft,
67198   Expr *pRight
67199 ){
67200   if( pRoot==0 ){
67201     assert( db->mallocFailed );
67202     sqlite3ExprDelete(db, pLeft);
67203     sqlite3ExprDelete(db, pRight);
67204   }else{
67205     if( pRight ){
67206       pRoot->pRight = pRight;
67207       if( pRight->flags & EP_ExpCollate ){
67208         pRoot->flags |= EP_ExpCollate;
67209         pRoot->pColl = pRight->pColl;
67210       }
67211     }
67212     if( pLeft ){
67213       pRoot->pLeft = pLeft;
67214       if( pLeft->flags & EP_ExpCollate ){
67215         pRoot->flags |= EP_ExpCollate;
67216         pRoot->pColl = pLeft->pColl;
67217       }
67218     }
67219     exprSetHeight(pRoot);
67220   }
67221 }
67222
67223 /*
67224 ** Allocate a Expr node which joins as many as two subtrees.
67225 **
67226 ** One or both of the subtrees can be NULL.  Return a pointer to the new
67227 ** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
67228 ** free the subtrees and return NULL.
67229 */
67230 SQLITE_PRIVATE Expr *sqlite3PExpr(
67231   Parse *pParse,          /* Parsing context */
67232   int op,                 /* Expression opcode */
67233   Expr *pLeft,            /* Left operand */
67234   Expr *pRight,           /* Right operand */
67235   const Token *pToken     /* Argument token */
67236 ){
67237   Expr *p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
67238   sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
67239   return p;
67240 }
67241
67242 /*
67243 ** Join two expressions using an AND operator.  If either expression is
67244 ** NULL, then just return the other expression.
67245 */
67246 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
67247   if( pLeft==0 ){
67248     return pRight;
67249   }else if( pRight==0 ){
67250     return pLeft;
67251   }else{
67252     Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
67253     sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
67254     return pNew;
67255   }
67256 }
67257
67258 /*
67259 ** Construct a new expression node for a function with multiple
67260 ** arguments.
67261 */
67262 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
67263   Expr *pNew;
67264   sqlite3 *db = pParse->db;
67265   assert( pToken );
67266   pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
67267   if( pNew==0 ){
67268     sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
67269     return 0;
67270   }
67271   pNew->x.pList = pList;
67272   assert( !ExprHasProperty(pNew, EP_xIsSelect) );
67273   sqlite3ExprSetHeight(pParse, pNew);
67274   return pNew;
67275 }
67276
67277 /*
67278 ** Assign a variable number to an expression that encodes a wildcard
67279 ** in the original SQL statement.  
67280 **
67281 ** Wildcards consisting of a single "?" are assigned the next sequential
67282 ** variable number.
67283 **
67284 ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
67285 ** sure "nnn" is not too be to avoid a denial of service attack when
67286 ** the SQL statement comes from an external source.
67287 **
67288 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
67289 ** as the previous instance of the same wildcard.  Or if this is the first
67290 ** instance of the wildcard, the next sequenial variable number is
67291 ** assigned.
67292 */
67293 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
67294   sqlite3 *db = pParse->db;
67295   const char *z;
67296
67297   if( pExpr==0 ) return;
67298   assert( !ExprHasAnyProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
67299   z = pExpr->u.zToken;
67300   assert( z!=0 );
67301   assert( z[0]!=0 );
67302   if( z[1]==0 ){
67303     /* Wildcard of the form "?".  Assign the next variable number */
67304     assert( z[0]=='?' );
67305     pExpr->iColumn = (ynVar)(++pParse->nVar);
67306   }else if( z[0]=='?' ){
67307     /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
67308     ** use it as the variable number */
67309     int i = atoi((char*)&z[1]);
67310     pExpr->iColumn = (ynVar)i;
67311     testcase( i==0 );
67312     testcase( i==1 );
67313     testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
67314     testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
67315     if( i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
67316       sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
67317           db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
67318     }
67319     if( i>pParse->nVar ){
67320       pParse->nVar = i;
67321     }
67322   }else{
67323     /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
67324     ** number as the prior appearance of the same name, or if the name
67325     ** has never appeared before, reuse the same variable number
67326     */
67327     int i;
67328     u32 n;
67329     n = sqlite3Strlen30(z);
67330     for(i=0; i<pParse->nVarExpr; i++){
67331       Expr *pE = pParse->apVarExpr[i];
67332       assert( pE!=0 );
67333       if( memcmp(pE->u.zToken, z, n)==0 && pE->u.zToken[n]==0 ){
67334         pExpr->iColumn = pE->iColumn;
67335         break;
67336       }
67337     }
67338     if( i>=pParse->nVarExpr ){
67339       pExpr->iColumn = (ynVar)(++pParse->nVar);
67340       if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
67341         pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
67342         pParse->apVarExpr =
67343             sqlite3DbReallocOrFree(
67344               db,
67345               pParse->apVarExpr,
67346               pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0])
67347             );
67348       }
67349       if( !db->mallocFailed ){
67350         assert( pParse->apVarExpr!=0 );
67351         pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
67352       }
67353     }
67354   } 
67355   if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
67356     sqlite3ErrorMsg(pParse, "too many SQL variables");
67357   }
67358 }
67359
67360 /*
67361 ** Recursively delete an expression tree.
67362 */
67363 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
67364   if( p==0 ) return;
67365   if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
67366     sqlite3ExprDelete(db, p->pLeft);
67367     sqlite3ExprDelete(db, p->pRight);
67368     if( !ExprHasProperty(p, EP_Reduced) && (p->flags2 & EP2_MallocedToken)!=0 ){
67369       sqlite3DbFree(db, p->u.zToken);
67370     }
67371     if( ExprHasProperty(p, EP_xIsSelect) ){
67372       sqlite3SelectDelete(db, p->x.pSelect);
67373     }else{
67374       sqlite3ExprListDelete(db, p->x.pList);
67375     }
67376   }
67377   if( !ExprHasProperty(p, EP_Static) ){
67378     sqlite3DbFree(db, p);
67379   }
67380 }
67381
67382 /*
67383 ** Return the number of bytes allocated for the expression structure 
67384 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
67385 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
67386 */
67387 static int exprStructSize(Expr *p){
67388   if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
67389   if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
67390   return EXPR_FULLSIZE;
67391 }
67392
67393 /*
67394 ** The dupedExpr*Size() routines each return the number of bytes required
67395 ** to store a copy of an expression or expression tree.  They differ in
67396 ** how much of the tree is measured.
67397 **
67398 **     dupedExprStructSize()     Size of only the Expr structure 
67399 **     dupedExprNodeSize()       Size of Expr + space for token
67400 **     dupedExprSize()           Expr + token + subtree components
67401 **
67402 ***************************************************************************
67403 **
67404 ** The dupedExprStructSize() function returns two values OR-ed together:  
67405 ** (1) the space required for a copy of the Expr structure only and 
67406 ** (2) the EP_xxx flags that indicate what the structure size should be.
67407 ** The return values is always one of:
67408 **
67409 **      EXPR_FULLSIZE
67410 **      EXPR_REDUCEDSIZE   | EP_Reduced
67411 **      EXPR_TOKENONLYSIZE | EP_TokenOnly
67412 **
67413 ** The size of the structure can be found by masking the return value
67414 ** of this routine with 0xfff.  The flags can be found by masking the
67415 ** return value with EP_Reduced|EP_TokenOnly.
67416 **
67417 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
67418 ** (unreduced) Expr objects as they or originally constructed by the parser.
67419 ** During expression analysis, extra information is computed and moved into
67420 ** later parts of teh Expr object and that extra information might get chopped
67421 ** off if the expression is reduced.  Note also that it does not work to
67422 ** make a EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
67423 ** to reduce a pristine expression tree from the parser.  The implementation
67424 ** of dupedExprStructSize() contain multiple assert() statements that attempt
67425 ** to enforce this constraint.
67426 */
67427 static int dupedExprStructSize(Expr *p, int flags){
67428   int nSize;
67429   assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
67430   if( 0==(flags&EXPRDUP_REDUCE) ){
67431     nSize = EXPR_FULLSIZE;
67432   }else{
67433     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
67434     assert( !ExprHasProperty(p, EP_FromJoin) ); 
67435     assert( (p->flags2 & EP2_MallocedToken)==0 );
67436     assert( (p->flags2 & EP2_Irreducible)==0 );
67437     if( p->pLeft || p->pRight || p->pColl || p->x.pList ){
67438       nSize = EXPR_REDUCEDSIZE | EP_Reduced;
67439     }else{
67440       nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
67441     }
67442   }
67443   return nSize;
67444 }
67445
67446 /*
67447 ** This function returns the space in bytes required to store the copy 
67448 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
67449 ** string is defined.)
67450 */
67451 static int dupedExprNodeSize(Expr *p, int flags){
67452   int nByte = dupedExprStructSize(p, flags) & 0xfff;
67453   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
67454     nByte += sqlite3Strlen30(p->u.zToken)+1;
67455   }
67456   return ROUND8(nByte);
67457 }
67458
67459 /*
67460 ** Return the number of bytes required to create a duplicate of the 
67461 ** expression passed as the first argument. The second argument is a
67462 ** mask containing EXPRDUP_XXX flags.
67463 **
67464 ** The value returned includes space to create a copy of the Expr struct
67465 ** itself and the buffer referred to by Expr.u.zToken, if any.
67466 **
67467 ** If the EXPRDUP_REDUCE flag is set, then the return value includes 
67468 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft 
67469 ** and Expr.pRight variables (but not for any structures pointed to or 
67470 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
67471 */
67472 static int dupedExprSize(Expr *p, int flags){
67473   int nByte = 0;
67474   if( p ){
67475     nByte = dupedExprNodeSize(p, flags);
67476     if( flags&EXPRDUP_REDUCE ){
67477       nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
67478     }
67479   }
67480   return nByte;
67481 }
67482
67483 /*
67484 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer 
67485 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough 
67486 ** to store the copy of expression p, the copies of p->u.zToken
67487 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
67488 ** if any. Before returning, *pzBuffer is set to the first byte passed the
67489 ** portion of the buffer copied into by this function.
67490 */
67491 static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
67492   Expr *pNew = 0;                      /* Value to return */
67493   if( p ){
67494     const int isReduced = (flags&EXPRDUP_REDUCE);
67495     u8 *zAlloc;
67496     u32 staticFlag = 0;
67497
67498     assert( pzBuffer==0 || isReduced );
67499
67500     /* Figure out where to write the new Expr structure. */
67501     if( pzBuffer ){
67502       zAlloc = *pzBuffer;
67503       staticFlag = EP_Static;
67504     }else{
67505       zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
67506     }
67507     pNew = (Expr *)zAlloc;
67508
67509     if( pNew ){
67510       /* Set nNewSize to the size allocated for the structure pointed to
67511       ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
67512       ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
67513       ** by the copy of the p->u.zToken string (if any).
67514       */
67515       const unsigned nStructSize = dupedExprStructSize(p, flags);
67516       const int nNewSize = nStructSize & 0xfff;
67517       int nToken;
67518       if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
67519         nToken = sqlite3Strlen30(p->u.zToken) + 1;
67520       }else{
67521         nToken = 0;
67522       }
67523       if( isReduced ){
67524         assert( ExprHasProperty(p, EP_Reduced)==0 );
67525         memcpy(zAlloc, p, nNewSize);
67526       }else{
67527         int nSize = exprStructSize(p);
67528         memcpy(zAlloc, p, nSize);
67529         memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
67530       }
67531
67532       /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
67533       pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
67534       pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
67535       pNew->flags |= staticFlag;
67536
67537       /* Copy the p->u.zToken string, if any. */
67538       if( nToken ){
67539         char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
67540         memcpy(zToken, p->u.zToken, nToken);
67541       }
67542
67543       if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
67544         /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
67545         if( ExprHasProperty(p, EP_xIsSelect) ){
67546           pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
67547         }else{
67548           pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
67549         }
67550       }
67551
67552       /* Fill in pNew->pLeft and pNew->pRight. */
67553       if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly) ){
67554         zAlloc += dupedExprNodeSize(p, flags);
67555         if( ExprHasProperty(pNew, EP_Reduced) ){
67556           pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
67557           pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
67558         }
67559         if( pzBuffer ){
67560           *pzBuffer = zAlloc;
67561         }
67562       }else{
67563         pNew->flags2 = 0;
67564         if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
67565           pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
67566           pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
67567         }
67568       }
67569
67570     }
67571   }
67572   return pNew;
67573 }
67574
67575 /*
67576 ** The following group of routines make deep copies of expressions,
67577 ** expression lists, ID lists, and select statements.  The copies can
67578 ** be deleted (by being passed to their respective ...Delete() routines)
67579 ** without effecting the originals.
67580 **
67581 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
67582 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded 
67583 ** by subsequent calls to sqlite*ListAppend() routines.
67584 **
67585 ** Any tables that the SrcList might point to are not duplicated.
67586 **
67587 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
67588 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
67589 ** truncated version of the usual Expr structure that will be stored as
67590 ** part of the in-memory representation of the database schema.
67591 */
67592 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
67593   return exprDup(db, p, flags, 0);
67594 }
67595 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
67596   ExprList *pNew;
67597   struct ExprList_item *pItem, *pOldItem;
67598   int i;
67599   if( p==0 ) return 0;
67600   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
67601   if( pNew==0 ) return 0;
67602   pNew->iECursor = 0;
67603   pNew->nExpr = pNew->nAlloc = p->nExpr;
67604   pNew->a = pItem = sqlite3DbMallocRaw(db,  p->nExpr*sizeof(p->a[0]) );
67605   if( pItem==0 ){
67606     sqlite3DbFree(db, pNew);
67607     return 0;
67608   } 
67609   pOldItem = p->a;
67610   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
67611     Expr *pOldExpr = pOldItem->pExpr;
67612     pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
67613     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
67614     pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
67615     pItem->sortOrder = pOldItem->sortOrder;
67616     pItem->done = 0;
67617     pItem->iCol = pOldItem->iCol;
67618     pItem->iAlias = pOldItem->iAlias;
67619   }
67620   return pNew;
67621 }
67622
67623 /*
67624 ** If cursors, triggers, views and subqueries are all omitted from
67625 ** the build, then none of the following routines, except for 
67626 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
67627 ** called with a NULL argument.
67628 */
67629 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
67630  || !defined(SQLITE_OMIT_SUBQUERY)
67631 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
67632   SrcList *pNew;
67633   int i;
67634   int nByte;
67635   if( p==0 ) return 0;
67636   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
67637   pNew = sqlite3DbMallocRaw(db, nByte );
67638   if( pNew==0 ) return 0;
67639   pNew->nSrc = pNew->nAlloc = p->nSrc;
67640   for(i=0; i<p->nSrc; i++){
67641     struct SrcList_item *pNewItem = &pNew->a[i];
67642     struct SrcList_item *pOldItem = &p->a[i];
67643     Table *pTab;
67644     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
67645     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
67646     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
67647     pNewItem->jointype = pOldItem->jointype;
67648     pNewItem->iCursor = pOldItem->iCursor;
67649     pNewItem->isPopulated = pOldItem->isPopulated;
67650     pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
67651     pNewItem->notIndexed = pOldItem->notIndexed;
67652     pNewItem->pIndex = pOldItem->pIndex;
67653     pTab = pNewItem->pTab = pOldItem->pTab;
67654     if( pTab ){
67655       pTab->nRef++;
67656     }
67657     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
67658     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
67659     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
67660     pNewItem->colUsed = pOldItem->colUsed;
67661   }
67662   return pNew;
67663 }
67664 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
67665   IdList *pNew;
67666   int i;
67667   if( p==0 ) return 0;
67668   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
67669   if( pNew==0 ) return 0;
67670   pNew->nId = pNew->nAlloc = p->nId;
67671   pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
67672   if( pNew->a==0 ){
67673     sqlite3DbFree(db, pNew);
67674     return 0;
67675   }
67676   for(i=0; i<p->nId; i++){
67677     struct IdList_item *pNewItem = &pNew->a[i];
67678     struct IdList_item *pOldItem = &p->a[i];
67679     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
67680     pNewItem->idx = pOldItem->idx;
67681   }
67682   return pNew;
67683 }
67684 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
67685   Select *pNew;
67686   if( p==0 ) return 0;
67687   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
67688   if( pNew==0 ) return 0;
67689   pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
67690   pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
67691   pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
67692   pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
67693   pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
67694   pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
67695   pNew->op = p->op;
67696   pNew->pPrior = sqlite3SelectDup(db, p->pPrior, flags);
67697   pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
67698   pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
67699   pNew->iLimit = 0;
67700   pNew->iOffset = 0;
67701   pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
67702   pNew->pRightmost = 0;
67703   pNew->addrOpenEphm[0] = -1;
67704   pNew->addrOpenEphm[1] = -1;
67705   pNew->addrOpenEphm[2] = -1;
67706   return pNew;
67707 }
67708 #else
67709 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
67710   assert( p==0 );
67711   return 0;
67712 }
67713 #endif
67714
67715
67716 /*
67717 ** Add a new element to the end of an expression list.  If pList is
67718 ** initially NULL, then create a new expression list.
67719 **
67720 ** If a memory allocation error occurs, the entire list is freed and
67721 ** NULL is returned.  If non-NULL is returned, then it is guaranteed
67722 ** that the new entry was successfully appended.
67723 */
67724 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
67725   Parse *pParse,          /* Parsing context */
67726   ExprList *pList,        /* List to which to append. Might be NULL */
67727   Expr *pExpr             /* Expression to be appended. Might be NULL */
67728 ){
67729   sqlite3 *db = pParse->db;
67730   if( pList==0 ){
67731     pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
67732     if( pList==0 ){
67733       goto no_mem;
67734     }
67735     assert( pList->nAlloc==0 );
67736   }
67737   if( pList->nAlloc<=pList->nExpr ){
67738     struct ExprList_item *a;
67739     int n = pList->nAlloc*2 + 4;
67740     a = sqlite3DbRealloc(db, pList->a, n*sizeof(pList->a[0]));
67741     if( a==0 ){
67742       goto no_mem;
67743     }
67744     pList->a = a;
67745     pList->nAlloc = sqlite3DbMallocSize(db, a)/sizeof(a[0]);
67746   }
67747   assert( pList->a!=0 );
67748   if( 1 ){
67749     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
67750     memset(pItem, 0, sizeof(*pItem));
67751     pItem->pExpr = pExpr;
67752   }
67753   return pList;
67754
67755 no_mem:     
67756   /* Avoid leaking memory if malloc has failed. */
67757   sqlite3ExprDelete(db, pExpr);
67758   sqlite3ExprListDelete(db, pList);
67759   return 0;
67760 }
67761
67762 /*
67763 ** Set the ExprList.a[].zName element of the most recently added item
67764 ** on the expression list.
67765 **
67766 ** pList might be NULL following an OOM error.  But pName should never be
67767 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
67768 ** is set.
67769 */
67770 SQLITE_PRIVATE void sqlite3ExprListSetName(
67771   Parse *pParse,          /* Parsing context */
67772   ExprList *pList,        /* List to which to add the span. */
67773   Token *pName,           /* Name to be added */
67774   int dequote             /* True to cause the name to be dequoted */
67775 ){
67776   assert( pList!=0 || pParse->db->mallocFailed!=0 );
67777   if( pList ){
67778     struct ExprList_item *pItem;
67779     assert( pList->nExpr>0 );
67780     pItem = &pList->a[pList->nExpr-1];
67781     assert( pItem->zName==0 );
67782     pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
67783     if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
67784   }
67785 }
67786
67787 /*
67788 ** Set the ExprList.a[].zSpan element of the most recently added item
67789 ** on the expression list.
67790 **
67791 ** pList might be NULL following an OOM error.  But pSpan should never be
67792 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
67793 ** is set.
67794 */
67795 SQLITE_PRIVATE void sqlite3ExprListSetSpan(
67796   Parse *pParse,          /* Parsing context */
67797   ExprList *pList,        /* List to which to add the span. */
67798   ExprSpan *pSpan         /* The span to be added */
67799 ){
67800   sqlite3 *db = pParse->db;
67801   assert( pList!=0 || db->mallocFailed!=0 );
67802   if( pList ){
67803     struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
67804     assert( pList->nExpr>0 );
67805     assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
67806     sqlite3DbFree(db, pItem->zSpan);
67807     pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
67808                                     (int)(pSpan->zEnd - pSpan->zStart));
67809   }
67810 }
67811
67812 /*
67813 ** If the expression list pEList contains more than iLimit elements,
67814 ** leave an error message in pParse.
67815 */
67816 SQLITE_PRIVATE void sqlite3ExprListCheckLength(
67817   Parse *pParse,
67818   ExprList *pEList,
67819   const char *zObject
67820 ){
67821   int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
67822   testcase( pEList && pEList->nExpr==mx );
67823   testcase( pEList && pEList->nExpr==mx+1 );
67824   if( pEList && pEList->nExpr>mx ){
67825     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
67826   }
67827 }
67828
67829 /*
67830 ** Delete an entire expression list.
67831 */
67832 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
67833   int i;
67834   struct ExprList_item *pItem;
67835   if( pList==0 ) return;
67836   assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
67837   assert( pList->nExpr<=pList->nAlloc );
67838   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
67839     sqlite3ExprDelete(db, pItem->pExpr);
67840     sqlite3DbFree(db, pItem->zName);
67841     sqlite3DbFree(db, pItem->zSpan);
67842   }
67843   sqlite3DbFree(db, pList->a);
67844   sqlite3DbFree(db, pList);
67845 }
67846
67847 /*
67848 ** These routines are Walker callbacks.  Walker.u.pi is a pointer
67849 ** to an integer.  These routines are checking an expression to see
67850 ** if it is a constant.  Set *Walker.u.pi to 0 if the expression is
67851 ** not constant.
67852 **
67853 ** These callback routines are used to implement the following:
67854 **
67855 **     sqlite3ExprIsConstant()
67856 **     sqlite3ExprIsConstantNotJoin()
67857 **     sqlite3ExprIsConstantOrFunction()
67858 **
67859 */
67860 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
67861
67862   /* If pWalker->u.i is 3 then any term of the expression that comes from
67863   ** the ON or USING clauses of a join disqualifies the expression
67864   ** from being considered constant. */
67865   if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
67866     pWalker->u.i = 0;
67867     return WRC_Abort;
67868   }
67869
67870   switch( pExpr->op ){
67871     /* Consider functions to be constant if all their arguments are constant
67872     ** and pWalker->u.i==2 */
67873     case TK_FUNCTION:
67874       if( pWalker->u.i==2 ) return 0;
67875       /* Fall through */
67876     case TK_ID:
67877     case TK_COLUMN:
67878     case TK_AGG_FUNCTION:
67879     case TK_AGG_COLUMN:
67880       testcase( pExpr->op==TK_ID );
67881       testcase( pExpr->op==TK_COLUMN );
67882       testcase( pExpr->op==TK_AGG_FUNCTION );
67883       testcase( pExpr->op==TK_AGG_COLUMN );
67884       pWalker->u.i = 0;
67885       return WRC_Abort;
67886     default:
67887       testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
67888       testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
67889       return WRC_Continue;
67890   }
67891 }
67892 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
67893   UNUSED_PARAMETER(NotUsed);
67894   pWalker->u.i = 0;
67895   return WRC_Abort;
67896 }
67897 static int exprIsConst(Expr *p, int initFlag){
67898   Walker w;
67899   w.u.i = initFlag;
67900   w.xExprCallback = exprNodeIsConstant;
67901   w.xSelectCallback = selectNodeIsConstant;
67902   sqlite3WalkExpr(&w, p);
67903   return w.u.i;
67904 }
67905
67906 /*
67907 ** Walk an expression tree.  Return 1 if the expression is constant
67908 ** and 0 if it involves variables or function calls.
67909 **
67910 ** For the purposes of this function, a double-quoted string (ex: "abc")
67911 ** is considered a variable but a single-quoted string (ex: 'abc') is
67912 ** a constant.
67913 */
67914 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
67915   return exprIsConst(p, 1);
67916 }
67917
67918 /*
67919 ** Walk an expression tree.  Return 1 if the expression is constant
67920 ** that does no originate from the ON or USING clauses of a join.
67921 ** Return 0 if it involves variables or function calls or terms from
67922 ** an ON or USING clause.
67923 */
67924 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
67925   return exprIsConst(p, 3);
67926 }
67927
67928 /*
67929 ** Walk an expression tree.  Return 1 if the expression is constant
67930 ** or a function call with constant arguments.  Return and 0 if there
67931 ** are any variables.
67932 **
67933 ** For the purposes of this function, a double-quoted string (ex: "abc")
67934 ** is considered a variable but a single-quoted string (ex: 'abc') is
67935 ** a constant.
67936 */
67937 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
67938   return exprIsConst(p, 2);
67939 }
67940
67941 /*
67942 ** If the expression p codes a constant integer that is small enough
67943 ** to fit in a 32-bit integer, return 1 and put the value of the integer
67944 ** in *pValue.  If the expression is not an integer or if it is too big
67945 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
67946 */
67947 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
67948   int rc = 0;
67949   if( p->flags & EP_IntValue ){
67950     *pValue = p->u.iValue;
67951     return 1;
67952   }
67953   switch( p->op ){
67954     case TK_INTEGER: {
67955       rc = sqlite3GetInt32(p->u.zToken, pValue);
67956       assert( rc==0 );
67957       break;
67958     }
67959     case TK_UPLUS: {
67960       rc = sqlite3ExprIsInteger(p->pLeft, pValue);
67961       break;
67962     }
67963     case TK_UMINUS: {
67964       int v;
67965       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
67966         *pValue = -v;
67967         rc = 1;
67968       }
67969       break;
67970     }
67971     default: break;
67972   }
67973   if( rc ){
67974     assert( ExprHasAnyProperty(p, EP_Reduced|EP_TokenOnly)
67975                || (p->flags2 & EP2_MallocedToken)==0 );
67976     p->op = TK_INTEGER;
67977     p->flags |= EP_IntValue;
67978     p->u.iValue = *pValue;
67979   }
67980   return rc;
67981 }
67982
67983 /*
67984 ** Return FALSE if there is no chance that the expression can be NULL.
67985 **
67986 ** If the expression might be NULL or if the expression is too complex
67987 ** to tell return TRUE.  
67988 **
67989 ** This routine is used as an optimization, to skip OP_IsNull opcodes
67990 ** when we know that a value cannot be NULL.  Hence, a false positive
67991 ** (returning TRUE when in fact the expression can never be NULL) might
67992 ** be a small performance hit but is otherwise harmless.  On the other
67993 ** hand, a false negative (returning FALSE when the result could be NULL)
67994 ** will likely result in an incorrect answer.  So when in doubt, return
67995 ** TRUE.
67996 */
67997 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
67998   u8 op;
67999   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
68000   op = p->op;
68001   if( op==TK_REGISTER ) op = p->op2;
68002   switch( op ){
68003     case TK_INTEGER:
68004     case TK_STRING:
68005     case TK_FLOAT:
68006     case TK_BLOB:
68007       return 0;
68008     default:
68009       return 1;
68010   }
68011 }
68012
68013 /*
68014 ** Generate an OP_IsNull instruction that tests register iReg and jumps
68015 ** to location iDest if the value in iReg is NULL.  The value in iReg 
68016 ** was computed by pExpr.  If we can look at pExpr at compile-time and
68017 ** determine that it can never generate a NULL, then the OP_IsNull operation
68018 ** can be omitted.
68019 */
68020 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(
68021   Vdbe *v,            /* The VDBE under construction */
68022   const Expr *pExpr,  /* Only generate OP_IsNull if this expr can be NULL */
68023   int iReg,           /* Test the value in this register for NULL */
68024   int iDest           /* Jump here if the value is null */
68025 ){
68026   if( sqlite3ExprCanBeNull(pExpr) ){
68027     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
68028   }
68029 }
68030
68031 /*
68032 ** Return TRUE if the given expression is a constant which would be
68033 ** unchanged by OP_Affinity with the affinity given in the second
68034 ** argument.
68035 **
68036 ** This routine is used to determine if the OP_Affinity operation
68037 ** can be omitted.  When in doubt return FALSE.  A false negative
68038 ** is harmless.  A false positive, however, can result in the wrong
68039 ** answer.
68040 */
68041 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
68042   u8 op;
68043   if( aff==SQLITE_AFF_NONE ) return 1;
68044   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
68045   op = p->op;
68046   if( op==TK_REGISTER ) op = p->op2;
68047   switch( op ){
68048     case TK_INTEGER: {
68049       return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
68050     }
68051     case TK_FLOAT: {
68052       return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
68053     }
68054     case TK_STRING: {
68055       return aff==SQLITE_AFF_TEXT;
68056     }
68057     case TK_BLOB: {
68058       return 1;
68059     }
68060     case TK_COLUMN: {
68061       assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
68062       return p->iColumn<0
68063           && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
68064     }
68065     default: {
68066       return 0;
68067     }
68068   }
68069 }
68070
68071 /*
68072 ** Return TRUE if the given string is a row-id column name.
68073 */
68074 SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
68075   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
68076   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
68077   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
68078   return 0;
68079 }
68080
68081 /*
68082 ** Return true if we are able to the IN operator optimization on a
68083 ** query of the form
68084 **
68085 **       x IN (SELECT ...)
68086 **
68087 ** Where the SELECT... clause is as specified by the parameter to this
68088 ** routine.
68089 **
68090 ** The Select object passed in has already been preprocessed and no
68091 ** errors have been found.
68092 */
68093 #ifndef SQLITE_OMIT_SUBQUERY
68094 static int isCandidateForInOpt(Select *p){
68095   SrcList *pSrc;
68096   ExprList *pEList;
68097   Table *pTab;
68098   if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
68099   if( p->pPrior ) return 0;              /* Not a compound SELECT */
68100   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
68101     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
68102     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
68103     return 0; /* No DISTINCT keyword and no aggregate functions */
68104   }
68105   assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
68106   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
68107   assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
68108   if( p->pWhere ) return 0;              /* Has no WHERE clause */
68109   pSrc = p->pSrc;
68110   assert( pSrc!=0 );
68111   if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
68112   if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
68113   pTab = pSrc->a[0].pTab;
68114   if( NEVER(pTab==0) ) return 0;
68115   assert( pTab->pSelect==0 );            /* FROM clause is not a view */
68116   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
68117   pEList = p->pEList;
68118   if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
68119   if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
68120   return 1;
68121 }
68122 #endif /* SQLITE_OMIT_SUBQUERY */
68123
68124 /*
68125 ** This function is used by the implementation of the IN (...) operator.
68126 ** It's job is to find or create a b-tree structure that may be used
68127 ** either to test for membership of the (...) set or to iterate through
68128 ** its members, skipping duplicates.
68129 **
68130 ** The index of the cursor opened on the b-tree (database table, database index 
68131 ** or ephermal table) is stored in pX->iTable before this function returns.
68132 ** The returned value of this function indicates the b-tree type, as follows:
68133 **
68134 **   IN_INDEX_ROWID - The cursor was opened on a database table.
68135 **   IN_INDEX_INDEX - The cursor was opened on a database index.
68136 **   IN_INDEX_EPH -   The cursor was opened on a specially created and
68137 **                    populated epheremal table.
68138 **
68139 ** An existing b-tree may only be used if the SELECT is of the simple
68140 ** form:
68141 **
68142 **     SELECT <column> FROM <table>
68143 **
68144 ** If the prNotFound parameter is 0, then the b-tree will be used to iterate
68145 ** through the set members, skipping any duplicates. In this case an
68146 ** epheremal table must be used unless the selected <column> is guaranteed
68147 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
68148 ** has a UNIQUE constraint or UNIQUE index.
68149 **
68150 ** If the prNotFound parameter is not 0, then the b-tree will be used 
68151 ** for fast set membership tests. In this case an epheremal table must 
68152 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can 
68153 ** be found with <column> as its left-most column.
68154 **
68155 ** When the b-tree is being used for membership tests, the calling function
68156 ** needs to know whether or not the structure contains an SQL NULL 
68157 ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
68158 ** If there is any chance that the (...) might contain a NULL value at
68159 ** runtime, then a register is allocated and the register number written
68160 ** to *prNotFound. If there is no chance that the (...) contains a
68161 ** NULL value, then *prNotFound is left unchanged.
68162 **
68163 ** If a register is allocated and its location stored in *prNotFound, then
68164 ** its initial value is NULL.  If the (...) does not remain constant
68165 ** for the duration of the query (i.e. the SELECT within the (...)
68166 ** is a correlated subquery) then the value of the allocated register is
68167 ** reset to NULL each time the subquery is rerun. This allows the
68168 ** caller to use vdbe code equivalent to the following:
68169 **
68170 **   if( register==NULL ){
68171 **     has_null = <test if data structure contains null>
68172 **     register = 1
68173 **   }
68174 **
68175 ** in order to avoid running the <test if data structure contains null>
68176 ** test more often than is necessary.
68177 */
68178 #ifndef SQLITE_OMIT_SUBQUERY
68179 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
68180   Select *p;                            /* SELECT to the right of IN operator */
68181   int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
68182   int iTab = pParse->nTab++;            /* Cursor of the RHS table */
68183   int mustBeUnique = (prNotFound==0);   /* True if RHS must be unique */
68184
68185   assert( pX->op==TK_IN );
68186
68187   /* Check to see if an existing table or index can be used to
68188   ** satisfy the query.  This is preferable to generating a new 
68189   ** ephemeral table.
68190   */
68191   p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
68192   if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
68193     sqlite3 *db = pParse->db;              /* Database connection */
68194     Expr *pExpr = p->pEList->a[0].pExpr;   /* Expression <column> */
68195     int iCol = pExpr->iColumn;             /* Index of column <column> */
68196     Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
68197     Table *pTab = p->pSrc->a[0].pTab;      /* Table <table>. */
68198     int iDb;                               /* Database idx for pTab */
68199    
68200     /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
68201     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
68202     sqlite3CodeVerifySchema(pParse, iDb);
68203     sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
68204
68205     /* This function is only called from two places. In both cases the vdbe
68206     ** has already been allocated. So assume sqlite3GetVdbe() is always
68207     ** successful here.
68208     */
68209     assert(v);
68210     if( iCol<0 ){
68211       int iMem = ++pParse->nMem;
68212       int iAddr;
68213
68214       iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
68215       sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
68216
68217       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
68218       eType = IN_INDEX_ROWID;
68219
68220       sqlite3VdbeJumpHere(v, iAddr);
68221     }else{
68222       Index *pIdx;                         /* Iterator variable */
68223
68224       /* The collation sequence used by the comparison. If an index is to
68225       ** be used in place of a temp-table, it must be ordered according
68226       ** to this collation sequence.  */
68227       CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
68228
68229       /* Check that the affinity that will be used to perform the 
68230       ** comparison is the same as the affinity of the column. If
68231       ** it is not, it is not possible to use any index.
68232       */
68233       char aff = comparisonAffinity(pX);
68234       int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);
68235
68236       for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
68237         if( (pIdx->aiColumn[0]==iCol)
68238          && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
68239          && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
68240         ){
68241           int iMem = ++pParse->nMem;
68242           int iAddr;
68243           char *pKey;
68244   
68245           pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
68246           iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
68247           sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
68248   
68249           sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
68250                                pKey,P4_KEYINFO_HANDOFF);
68251           VdbeComment((v, "%s", pIdx->zName));
68252           eType = IN_INDEX_INDEX;
68253
68254           sqlite3VdbeJumpHere(v, iAddr);
68255           if( prNotFound && !pTab->aCol[iCol].notNull ){
68256             *prNotFound = ++pParse->nMem;
68257           }
68258         }
68259       }
68260     }
68261   }
68262
68263   if( eType==0 ){
68264     /* Could not found an existing table or index to use as the RHS b-tree.
68265     ** We will have to generate an ephemeral table to do the job.
68266     */
68267     int rMayHaveNull = 0;
68268     eType = IN_INDEX_EPH;
68269     if( prNotFound ){
68270       *prNotFound = rMayHaveNull = ++pParse->nMem;
68271     }else if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
68272       eType = IN_INDEX_ROWID;
68273     }
68274     sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
68275   }else{
68276     pX->iTable = iTab;
68277   }
68278   return eType;
68279 }
68280 #endif
68281
68282 /*
68283 ** Generate code for scalar subqueries used as an expression
68284 ** and IN operators.  Examples:
68285 **
68286 **     (SELECT a FROM b)          -- subquery
68287 **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
68288 **     x IN (4,5,11)              -- IN operator with list on right-hand side
68289 **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
68290 **
68291 ** The pExpr parameter describes the expression that contains the IN
68292 ** operator or subquery.
68293 **
68294 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
68295 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
68296 ** to some integer key column of a table B-Tree. In this case, use an
68297 ** intkey B-Tree to store the set of IN(...) values instead of the usual
68298 ** (slower) variable length keys B-Tree.
68299 **
68300 ** If rMayHaveNull is non-zero, that means that the operation is an IN
68301 ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
68302 ** Furthermore, the IN is in a WHERE clause and that we really want
68303 ** to iterate over the RHS of the IN operator in order to quickly locate
68304 ** all corresponding LHS elements.  All this routine does is initialize
68305 ** the register given by rMayHaveNull to NULL.  Calling routines will take
68306 ** care of changing this register value to non-NULL if the RHS is NULL-free.
68307 **
68308 ** If rMayHaveNull is zero, that means that the subquery is being used
68309 ** for membership testing only.  There is no need to initialize any
68310 ** registers to indicate the presense or absence of NULLs on the RHS.
68311 **
68312 ** For a SELECT or EXISTS operator, return the register that holds the
68313 ** result.  For IN operators or if an error occurs, the return value is 0.
68314 */
68315 #ifndef SQLITE_OMIT_SUBQUERY
68316 SQLITE_PRIVATE int sqlite3CodeSubselect(
68317   Parse *pParse,          /* Parsing context */
68318   Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
68319   int rMayHaveNull,       /* Register that records whether NULLs exist in RHS */
68320   int isRowid             /* If true, LHS of IN operator is a rowid */
68321 ){
68322   int testAddr = 0;                       /* One-time test address */
68323   int rReg = 0;                           /* Register storing resulting */
68324   Vdbe *v = sqlite3GetVdbe(pParse);
68325   if( NEVER(v==0) ) return 0;
68326   sqlite3ExprCachePush(pParse);
68327
68328   /* This code must be run in its entirety every time it is encountered
68329   ** if any of the following is true:
68330   **
68331   **    *  The right-hand side is a correlated subquery
68332   **    *  The right-hand side is an expression list containing variables
68333   **    *  We are inside a trigger
68334   **
68335   ** If all of the above are false, then we can run this code just once
68336   ** save the results, and reuse the same result on subsequent invocations.
68337   */
68338   if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->pTriggerTab ){
68339     int mem = ++pParse->nMem;
68340     sqlite3VdbeAddOp1(v, OP_If, mem);
68341     testAddr = sqlite3VdbeAddOp2(v, OP_Integer, 1, mem);
68342     assert( testAddr>0 || pParse->db->mallocFailed );
68343   }
68344
68345   switch( pExpr->op ){
68346     case TK_IN: {
68347       char affinity;
68348       KeyInfo keyInfo;
68349       int addr;        /* Address of OP_OpenEphemeral instruction */
68350       Expr *pLeft = pExpr->pLeft;
68351
68352       if( rMayHaveNull ){
68353         sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
68354       }
68355
68356       affinity = sqlite3ExprAffinity(pLeft);
68357
68358       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
68359       ** expression it is handled the same way.  An ephemeral table is 
68360       ** filled with single-field index keys representing the results
68361       ** from the SELECT or the <exprlist>.
68362       **
68363       ** If the 'x' expression is a column value, or the SELECT...
68364       ** statement returns a column value, then the affinity of that
68365       ** column is used to build the index keys. If both 'x' and the
68366       ** SELECT... statement are columns, then numeric affinity is used
68367       ** if either column has NUMERIC or INTEGER affinity. If neither
68368       ** 'x' nor the SELECT... statement are columns, then numeric affinity
68369       ** is used.
68370       */
68371       pExpr->iTable = pParse->nTab++;
68372       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
68373       memset(&keyInfo, 0, sizeof(keyInfo));
68374       keyInfo.nField = 1;
68375
68376       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
68377         /* Case 1:     expr IN (SELECT ...)
68378         **
68379         ** Generate code to write the results of the select into the temporary
68380         ** table allocated and opened above.
68381         */
68382         SelectDest dest;
68383         ExprList *pEList;
68384
68385         assert( !isRowid );
68386         sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
68387         dest.affinity = (u8)affinity;
68388         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
68389         if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
68390           return 0;
68391         }
68392         pEList = pExpr->x.pSelect->pEList;
68393         if( ALWAYS(pEList!=0 && pEList->nExpr>0) ){ 
68394           keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
68395               pEList->a[0].pExpr);
68396         }
68397       }else if( ALWAYS(pExpr->x.pList!=0) ){
68398         /* Case 2:     expr IN (exprlist)
68399         **
68400         ** For each expression, build an index key from the evaluation and
68401         ** store it in the temporary table. If <expr> is a column, then use
68402         ** that columns affinity when building index keys. If <expr> is not
68403         ** a column, use numeric affinity.
68404         */
68405         int i;
68406         ExprList *pList = pExpr->x.pList;
68407         struct ExprList_item *pItem;
68408         int r1, r2, r3;
68409
68410         if( !affinity ){
68411           affinity = SQLITE_AFF_NONE;
68412         }
68413         keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
68414
68415         /* Loop through each expression in <exprlist>. */
68416         r1 = sqlite3GetTempReg(pParse);
68417         r2 = sqlite3GetTempReg(pParse);
68418         sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
68419         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
68420           Expr *pE2 = pItem->pExpr;
68421           int iValToIns;
68422
68423           /* If the expression is not constant then we will need to
68424           ** disable the test that was generated above that makes sure
68425           ** this code only executes once.  Because for a non-constant
68426           ** expression we need to rerun this code each time.
68427           */
68428           if( testAddr && !sqlite3ExprIsConstant(pE2) ){
68429             sqlite3VdbeChangeToNoop(v, testAddr-1, 2);
68430             testAddr = 0;
68431           }
68432
68433           /* Evaluate the expression and insert it into the temp table */
68434           if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
68435             sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
68436           }else{
68437             r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
68438             if( isRowid ){
68439               sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
68440                                 sqlite3VdbeCurrentAddr(v)+2);
68441               sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
68442             }else{
68443               sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
68444               sqlite3ExprCacheAffinityChange(pParse, r3, 1);
68445               sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
68446             }
68447           }
68448         }
68449         sqlite3ReleaseTempReg(pParse, r1);
68450         sqlite3ReleaseTempReg(pParse, r2);
68451       }
68452       if( !isRowid ){
68453         sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
68454       }
68455       break;
68456     }
68457
68458     case TK_EXISTS:
68459     case TK_SELECT:
68460     default: {
68461       /* If this has to be a scalar SELECT.  Generate code to put the
68462       ** value of this select in a memory cell and record the number
68463       ** of the memory cell in iColumn.  If this is an EXISTS, write
68464       ** an integer 0 (not exists) or 1 (exists) into a memory cell
68465       ** and record that memory cell in iColumn.
68466       */
68467       Select *pSel;                         /* SELECT statement to encode */
68468       SelectDest dest;                      /* How to deal with SELECt result */
68469
68470       testcase( pExpr->op==TK_EXISTS );
68471       testcase( pExpr->op==TK_SELECT );
68472       assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
68473
68474       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
68475       pSel = pExpr->x.pSelect;
68476       sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
68477       if( pExpr->op==TK_SELECT ){
68478         dest.eDest = SRT_Mem;
68479         sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm);
68480         VdbeComment((v, "Init subquery result"));
68481       }else{
68482         dest.eDest = SRT_Exists;
68483         sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm);
68484         VdbeComment((v, "Init EXISTS result"));
68485       }
68486       sqlite3ExprDelete(pParse->db, pSel->pLimit);
68487       pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
68488                                   &sqlite3IntTokens[1]);
68489       if( sqlite3Select(pParse, pSel, &dest) ){
68490         return 0;
68491       }
68492       rReg = dest.iParm;
68493       ExprSetIrreducible(pExpr);
68494       break;
68495     }
68496   }
68497
68498   if( testAddr ){
68499     sqlite3VdbeJumpHere(v, testAddr-1);
68500   }
68501   sqlite3ExprCachePop(pParse, 1);
68502
68503   return rReg;
68504 }
68505 #endif /* SQLITE_OMIT_SUBQUERY */
68506
68507 #ifndef SQLITE_OMIT_SUBQUERY
68508 /*
68509 ** Generate code for an IN expression.
68510 **
68511 **      x IN (SELECT ...)
68512 **      x IN (value, value, ...)
68513 **
68514 ** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
68515 ** is an array of zero or more values.  The expression is true if the LHS is
68516 ** contained within the RHS.  The value of the expression is unknown (NULL)
68517 ** if the LHS is NULL or if the LHS is not contained within the RHS and the
68518 ** RHS contains one or more NULL values.
68519 **
68520 ** This routine generates code will jump to destIfFalse if the LHS is not 
68521 ** contained within the RHS.  If due to NULLs we cannot determine if the LHS
68522 ** is contained in the RHS then jump to destIfNull.  If the LHS is contained
68523 ** within the RHS then fall through.
68524 */
68525 static void sqlite3ExprCodeIN(
68526   Parse *pParse,        /* Parsing and code generating context */
68527   Expr *pExpr,          /* The IN expression */
68528   int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
68529   int destIfNull        /* Jump here if the results are unknown due to NULLs */
68530 ){
68531   int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
68532   char affinity;        /* Comparison affinity to use */
68533   int eType;            /* Type of the RHS */
68534   int r1;               /* Temporary use register */
68535   Vdbe *v;              /* Statement under construction */
68536
68537   /* Compute the RHS.   After this step, the table with cursor
68538   ** pExpr->iTable will contains the values that make up the RHS.
68539   */
68540   v = pParse->pVdbe;
68541   assert( v!=0 );       /* OOM detected prior to this routine */
68542   VdbeNoopComment((v, "begin IN expr"));
68543   eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
68544
68545   /* Figure out the affinity to use to create a key from the results
68546   ** of the expression. affinityStr stores a static string suitable for
68547   ** P4 of OP_MakeRecord.
68548   */
68549   affinity = comparisonAffinity(pExpr);
68550
68551   /* Code the LHS, the <expr> from "<expr> IN (...)".
68552   */
68553   sqlite3ExprCachePush(pParse);
68554   r1 = sqlite3GetTempReg(pParse);
68555   sqlite3ExprCode(pParse, pExpr->pLeft, r1);
68556
68557   /* If the LHS is NULL, then the result is either false or NULL depending
68558   ** on whether the RHS is empty or not, respectively.
68559   */
68560   if( destIfNull==destIfFalse ){
68561     /* Shortcut for the common case where the false and NULL outcomes are
68562     ** the same. */
68563     sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
68564   }else{
68565     int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1);
68566     sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
68567     sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
68568     sqlite3VdbeJumpHere(v, addr1);
68569   }
68570
68571   if( eType==IN_INDEX_ROWID ){
68572     /* In this case, the RHS is the ROWID of table b-tree
68573     */
68574     sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
68575     sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
68576   }else{
68577     /* In this case, the RHS is an index b-tree.
68578     */
68579     sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
68580
68581     /* If the set membership test fails, then the result of the 
68582     ** "x IN (...)" expression must be either 0 or NULL. If the set
68583     ** contains no NULL values, then the result is 0. If the set 
68584     ** contains one or more NULL values, then the result of the
68585     ** expression is also NULL.
68586     */
68587     if( rRhsHasNull==0 || destIfFalse==destIfNull ){
68588       /* This branch runs if it is known at compile time that the RHS
68589       ** cannot contain NULL values. This happens as the result
68590       ** of a "NOT NULL" constraint in the database schema.
68591       **
68592       ** Also run this branch if NULL is equivalent to FALSE
68593       ** for this particular IN operator.
68594       */
68595       sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
68596
68597     }else{
68598       /* In this branch, the RHS of the IN might contain a NULL and
68599       ** the presence of a NULL on the RHS makes a difference in the
68600       ** outcome.
68601       */
68602       int j1, j2, j3;
68603
68604       /* First check to see if the LHS is contained in the RHS.  If so,
68605       ** then the presence of NULLs in the RHS does not matter, so jump
68606       ** over all of the code that follows.
68607       */
68608       j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
68609
68610       /* Here we begin generating code that runs if the LHS is not
68611       ** contained within the RHS.  Generate additional code that
68612       ** tests the RHS for NULLs.  If the RHS contains a NULL then
68613       ** jump to destIfNull.  If there are no NULLs in the RHS then
68614       ** jump to destIfFalse.
68615       */
68616       j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
68617       j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
68618       sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
68619       sqlite3VdbeJumpHere(v, j3);
68620       sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
68621       sqlite3VdbeJumpHere(v, j2);
68622
68623       /* Jump to the appropriate target depending on whether or not
68624       ** the RHS contains a NULL
68625       */
68626       sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
68627       sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
68628
68629       /* The OP_Found at the top of this branch jumps here when true, 
68630       ** causing the overall IN expression evaluation to fall through.
68631       */
68632       sqlite3VdbeJumpHere(v, j1);
68633     }
68634   }
68635   sqlite3ReleaseTempReg(pParse, r1);
68636   sqlite3ExprCachePop(pParse, 1);
68637   VdbeComment((v, "end IN expr"));
68638 }
68639 #endif /* SQLITE_OMIT_SUBQUERY */
68640
68641 /*
68642 ** Duplicate an 8-byte value
68643 */
68644 static char *dup8bytes(Vdbe *v, const char *in){
68645   char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
68646   if( out ){
68647     memcpy(out, in, 8);
68648   }
68649   return out;
68650 }
68651
68652 #ifndef SQLITE_OMIT_FLOATING_POINT
68653 /*
68654 ** Generate an instruction that will put the floating point
68655 ** value described by z[0..n-1] into register iMem.
68656 **
68657 ** The z[] string will probably not be zero-terminated.  But the 
68658 ** z[n] character is guaranteed to be something that does not look
68659 ** like the continuation of the number.
68660 */
68661 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
68662   if( ALWAYS(z!=0) ){
68663     double value;
68664     char *zV;
68665     sqlite3AtoF(z, &value);
68666     assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
68667     if( negateFlag ) value = -value;
68668     zV = dup8bytes(v, (char*)&value);
68669     sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
68670   }
68671 }
68672 #endif
68673
68674
68675 /*
68676 ** Generate an instruction that will put the integer describe by
68677 ** text z[0..n-1] into register iMem.
68678 **
68679 ** The z[] string will probably not be zero-terminated.  But the 
68680 ** z[n] character is guaranteed to be something that does not look
68681 ** like the continuation of the number.
68682 */
68683 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
68684   Vdbe *v = pParse->pVdbe;
68685   if( pExpr->flags & EP_IntValue ){
68686     int i = pExpr->u.iValue;
68687     if( negFlag ) i = -i;
68688     sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
68689   }else{
68690     const char *z = pExpr->u.zToken;
68691     assert( z!=0 );
68692     if( sqlite3FitsIn64Bits(z, negFlag) ){
68693       i64 value;
68694       char *zV;
68695       sqlite3Atoi64(z, &value);
68696       if( negFlag ) value = -value;
68697       zV = dup8bytes(v, (char*)&value);
68698       sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
68699     }else{
68700 #ifdef SQLITE_OMIT_FLOATING_POINT
68701       sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
68702 #else
68703       codeReal(v, z, negFlag, iMem);
68704 #endif
68705     }
68706   }
68707 }
68708
68709 /*
68710 ** Clear a cache entry.
68711 */
68712 static void cacheEntryClear(Parse *pParse, struct yColCache *p){
68713   if( p->tempReg ){
68714     if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
68715       pParse->aTempReg[pParse->nTempReg++] = p->iReg;
68716     }
68717     p->tempReg = 0;
68718   }
68719 }
68720
68721
68722 /*
68723 ** Record in the column cache that a particular column from a
68724 ** particular table is stored in a particular register.
68725 */
68726 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
68727   int i;
68728   int minLru;
68729   int idxLru;
68730   struct yColCache *p;
68731
68732   assert( iReg>0 );  /* Register numbers are always positive */
68733   assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
68734
68735   /* The SQLITE_ColumnCache flag disables the column cache.  This is used
68736   ** for testing only - to verify that SQLite always gets the same answer
68737   ** with and without the column cache.
68738   */
68739   if( pParse->db->flags & SQLITE_ColumnCache ) return;
68740
68741   /* First replace any existing entry.
68742   **
68743   ** Actually, the way the column cache is currently used, we are guaranteed
68744   ** that the object will never already be in cache.  Verify this guarantee.
68745   */
68746 #ifndef NDEBUG
68747   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
68748 #if 0 /* This code wold remove the entry from the cache if it existed */
68749     if( p->iReg && p->iTable==iTab && p->iColumn==iCol ){
68750       cacheEntryClear(pParse, p);
68751       p->iLevel = pParse->iCacheLevel;
68752       p->iReg = iReg;
68753       p->lru = pParse->iCacheCnt++;
68754       return;
68755     }
68756 #endif
68757     assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
68758   }
68759 #endif
68760
68761   /* Find an empty slot and replace it */
68762   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
68763     if( p->iReg==0 ){
68764       p->iLevel = pParse->iCacheLevel;
68765       p->iTable = iTab;
68766       p->iColumn = iCol;
68767       p->iReg = iReg;
68768       p->tempReg = 0;
68769       p->lru = pParse->iCacheCnt++;
68770       return;
68771     }
68772   }
68773
68774   /* Replace the last recently used */
68775   minLru = 0x7fffffff;
68776   idxLru = -1;
68777   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
68778     if( p->lru<minLru ){
68779       idxLru = i;
68780       minLru = p->lru;
68781     }
68782   }
68783   if( ALWAYS(idxLru>=0) ){
68784     p = &pParse->aColCache[idxLru];
68785     p->iLevel = pParse->iCacheLevel;
68786     p->iTable = iTab;
68787     p->iColumn = iCol;
68788     p->iReg = iReg;
68789     p->tempReg = 0;
68790     p->lru = pParse->iCacheCnt++;
68791     return;
68792   }
68793 }
68794
68795 /*
68796 ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
68797 ** Purge the range of registers from the column cache.
68798 */
68799 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
68800   int i;
68801   int iLast = iReg + nReg - 1;
68802   struct yColCache *p;
68803   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
68804     int r = p->iReg;
68805     if( r>=iReg && r<=iLast ){
68806       cacheEntryClear(pParse, p);
68807       p->iReg = 0;
68808     }
68809   }
68810 }
68811
68812 /*
68813 ** Remember the current column cache context.  Any new entries added
68814 ** added to the column cache after this call are removed when the
68815 ** corresponding pop occurs.
68816 */
68817 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
68818   pParse->iCacheLevel++;
68819 }
68820
68821 /*
68822 ** Remove from the column cache any entries that were added since the
68823 ** the previous N Push operations.  In other words, restore the cache
68824 ** to the state it was in N Pushes ago.
68825 */
68826 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse, int N){
68827   int i;
68828   struct yColCache *p;
68829   assert( N>0 );
68830   assert( pParse->iCacheLevel>=N );
68831   pParse->iCacheLevel -= N;
68832   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
68833     if( p->iReg && p->iLevel>pParse->iCacheLevel ){
68834       cacheEntryClear(pParse, p);
68835       p->iReg = 0;
68836     }
68837   }
68838 }
68839
68840 /*
68841 ** When a cached column is reused, make sure that its register is
68842 ** no longer available as a temp register.  ticket #3879:  that same
68843 ** register might be in the cache in multiple places, so be sure to
68844 ** get them all.
68845 */
68846 static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
68847   int i;
68848   struct yColCache *p;
68849   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
68850     if( p->iReg==iReg ){
68851       p->tempReg = 0;
68852     }
68853   }
68854 }
68855
68856 /*
68857 ** Generate code to extract the value of the iCol-th column of a table.
68858 */
68859 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
68860   Vdbe *v,        /* The VDBE under construction */
68861   Table *pTab,    /* The table containing the value */
68862   int iTabCur,    /* The cursor for this table */
68863   int iCol,       /* Index of the column to extract */
68864   int regOut      /* Extract the valud into this register */
68865 ){
68866   if( iCol<0 || iCol==pTab->iPKey ){
68867     sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
68868   }else{
68869     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
68870     sqlite3VdbeAddOp3(v, op, iTabCur, iCol, regOut);
68871   }
68872   if( iCol>=0 ){
68873     sqlite3ColumnDefault(v, pTab, iCol, regOut);
68874   }
68875 }
68876
68877 /*
68878 ** Generate code that will extract the iColumn-th column from
68879 ** table pTab and store the column value in a register.  An effort
68880 ** is made to store the column value in register iReg, but this is
68881 ** not guaranteed.  The location of the column value is returned.
68882 **
68883 ** There must be an open cursor to pTab in iTable when this routine
68884 ** is called.  If iColumn<0 then code is generated that extracts the rowid.
68885 */
68886 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
68887   Parse *pParse,   /* Parsing and code generating context */
68888   Table *pTab,     /* Description of the table we are reading from */
68889   int iColumn,     /* Index of the table column */
68890   int iTable,      /* The cursor pointing to the table */
68891   int iReg         /* Store results here */
68892 ){
68893   Vdbe *v = pParse->pVdbe;
68894   int i;
68895   struct yColCache *p;
68896
68897   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
68898     if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
68899       p->lru = pParse->iCacheCnt++;
68900       sqlite3ExprCachePinRegister(pParse, p->iReg);
68901       return p->iReg;
68902     }
68903   }  
68904   assert( v!=0 );
68905   sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
68906   sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
68907   return iReg;
68908 }
68909
68910 /*
68911 ** Clear all column cache entries.
68912 */
68913 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
68914   int i;
68915   struct yColCache *p;
68916
68917   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
68918     if( p->iReg ){
68919       cacheEntryClear(pParse, p);
68920       p->iReg = 0;
68921     }
68922   }
68923 }
68924
68925 /*
68926 ** Record the fact that an affinity change has occurred on iCount
68927 ** registers starting with iStart.
68928 */
68929 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
68930   sqlite3ExprCacheRemove(pParse, iStart, iCount);
68931 }
68932
68933 /*
68934 ** Generate code to move content from registers iFrom...iFrom+nReg-1
68935 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
68936 */
68937 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
68938   int i;
68939   struct yColCache *p;
68940   if( NEVER(iFrom==iTo) ) return;
68941   sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
68942   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
68943     int x = p->iReg;
68944     if( x>=iFrom && x<iFrom+nReg ){
68945       p->iReg += iTo-iFrom;
68946     }
68947   }
68948 }
68949
68950 /*
68951 ** Generate code to copy content from registers iFrom...iFrom+nReg-1
68952 ** over to iTo..iTo+nReg-1.
68953 */
68954 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, int iFrom, int iTo, int nReg){
68955   int i;
68956   if( NEVER(iFrom==iTo) ) return;
68957   for(i=0; i<nReg; i++){
68958     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, iFrom+i, iTo+i);
68959   }
68960 }
68961
68962 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
68963 /*
68964 ** Return true if any register in the range iFrom..iTo (inclusive)
68965 ** is used as part of the column cache.
68966 **
68967 ** This routine is used within assert() and testcase() macros only
68968 ** and does not appear in a normal build.
68969 */
68970 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
68971   int i;
68972   struct yColCache *p;
68973   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
68974     int r = p->iReg;
68975     if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
68976   }
68977   return 0;
68978 }
68979 #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
68980
68981 /*
68982 ** If the last instruction coded is an ephemeral copy of any of
68983 ** the registers in the nReg registers beginning with iReg, then
68984 ** convert the last instruction from OP_SCopy to OP_Copy.
68985 */
68986 SQLITE_PRIVATE void sqlite3ExprHardCopy(Parse *pParse, int iReg, int nReg){
68987   VdbeOp *pOp;
68988   Vdbe *v;
68989
68990   assert( pParse->db->mallocFailed==0 );
68991   v = pParse->pVdbe;
68992   assert( v!=0 );
68993   pOp = sqlite3VdbeGetOp(v, -1);
68994   assert( pOp!=0 );
68995   if( pOp->opcode==OP_SCopy && pOp->p1>=iReg && pOp->p1<iReg+nReg ){
68996     pOp->opcode = OP_Copy;
68997   }
68998 }
68999
69000 /*
69001 ** Generate code to store the value of the iAlias-th alias in register
69002 ** target.  The first time this is called, pExpr is evaluated to compute
69003 ** the value of the alias.  The value is stored in an auxiliary register
69004 ** and the number of that register is returned.  On subsequent calls,
69005 ** the register number is returned without generating any code.
69006 **
69007 ** Note that in order for this to work, code must be generated in the
69008 ** same order that it is executed.
69009 **
69010 ** Aliases are numbered starting with 1.  So iAlias is in the range
69011 ** of 1 to pParse->nAlias inclusive.  
69012 **
69013 ** pParse->aAlias[iAlias-1] records the register number where the value
69014 ** of the iAlias-th alias is stored.  If zero, that means that the
69015 ** alias has not yet been computed.
69016 */
69017 static int codeAlias(Parse *pParse, int iAlias, Expr *pExpr, int target){
69018 #if 0
69019   sqlite3 *db = pParse->db;
69020   int iReg;
69021   if( pParse->nAliasAlloc<pParse->nAlias ){
69022     pParse->aAlias = sqlite3DbReallocOrFree(db, pParse->aAlias,
69023                                  sizeof(pParse->aAlias[0])*pParse->nAlias );
69024     testcase( db->mallocFailed && pParse->nAliasAlloc>0 );
69025     if( db->mallocFailed ) return 0;
69026     memset(&pParse->aAlias[pParse->nAliasAlloc], 0,
69027            (pParse->nAlias-pParse->nAliasAlloc)*sizeof(pParse->aAlias[0]));
69028     pParse->nAliasAlloc = pParse->nAlias;
69029   }
69030   assert( iAlias>0 && iAlias<=pParse->nAlias );
69031   iReg = pParse->aAlias[iAlias-1];
69032   if( iReg==0 ){
69033     if( pParse->iCacheLevel>0 ){
69034       iReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
69035     }else{
69036       iReg = ++pParse->nMem;
69037       sqlite3ExprCode(pParse, pExpr, iReg);
69038       pParse->aAlias[iAlias-1] = iReg;
69039     }
69040   }
69041   return iReg;
69042 #else
69043   UNUSED_PARAMETER(iAlias);
69044   return sqlite3ExprCodeTarget(pParse, pExpr, target);
69045 #endif
69046 }
69047
69048 /*
69049 ** Generate code into the current Vdbe to evaluate the given
69050 ** expression.  Attempt to store the results in register "target".
69051 ** Return the register where results are stored.
69052 **
69053 ** With this routine, there is no guarantee that results will
69054 ** be stored in target.  The result might be stored in some other
69055 ** register if it is convenient to do so.  The calling function
69056 ** must check the return code and move the results to the desired
69057 ** register.
69058 */
69059 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
69060   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
69061   int op;                   /* The opcode being coded */
69062   int inReg = target;       /* Results stored in register inReg */
69063   int regFree1 = 0;         /* If non-zero free this temporary register */
69064   int regFree2 = 0;         /* If non-zero free this temporary register */
69065   int r1, r2, r3, r4;       /* Various register numbers */
69066   sqlite3 *db = pParse->db; /* The database connection */
69067
69068   assert( target>0 && target<=pParse->nMem );
69069   if( v==0 ){
69070     assert( pParse->db->mallocFailed );
69071     return 0;
69072   }
69073
69074   if( pExpr==0 ){
69075     op = TK_NULL;
69076   }else{
69077     op = pExpr->op;
69078   }
69079   switch( op ){
69080     case TK_AGG_COLUMN: {
69081       AggInfo *pAggInfo = pExpr->pAggInfo;
69082       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
69083       if( !pAggInfo->directMode ){
69084         assert( pCol->iMem>0 );
69085         inReg = pCol->iMem;
69086         break;
69087       }else if( pAggInfo->useSortingIdx ){
69088         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdx,
69089                               pCol->iSorterColumn, target);
69090         break;
69091       }
69092       /* Otherwise, fall thru into the TK_COLUMN case */
69093     }
69094     case TK_COLUMN: {
69095       if( pExpr->iTable<0 ){
69096         /* This only happens when coding check constraints */
69097         assert( pParse->ckBase>0 );
69098         inReg = pExpr->iColumn + pParse->ckBase;
69099       }else{
69100         inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
69101                                  pExpr->iColumn, pExpr->iTable, target);
69102       }
69103       break;
69104     }
69105     case TK_INTEGER: {
69106       codeInteger(pParse, pExpr, 0, target);
69107       break;
69108     }
69109 #ifndef SQLITE_OMIT_FLOATING_POINT
69110     case TK_FLOAT: {
69111       assert( !ExprHasProperty(pExpr, EP_IntValue) );
69112       codeReal(v, pExpr->u.zToken, 0, target);
69113       break;
69114     }
69115 #endif
69116     case TK_STRING: {
69117       assert( !ExprHasProperty(pExpr, EP_IntValue) );
69118       sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
69119       break;
69120     }
69121     case TK_NULL: {
69122       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
69123       break;
69124     }
69125 #ifndef SQLITE_OMIT_BLOB_LITERAL
69126     case TK_BLOB: {
69127       int n;
69128       const char *z;
69129       char *zBlob;
69130       assert( !ExprHasProperty(pExpr, EP_IntValue) );
69131       assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
69132       assert( pExpr->u.zToken[1]=='\'' );
69133       z = &pExpr->u.zToken[2];
69134       n = sqlite3Strlen30(z) - 1;
69135       assert( z[n]=='\'' );
69136       zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
69137       sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
69138       break;
69139     }
69140 #endif
69141     case TK_VARIABLE: {
69142       assert( !ExprHasProperty(pExpr, EP_IntValue) );
69143       assert( pExpr->u.zToken!=0 );
69144       assert( pExpr->u.zToken[0]!=0 );
69145       sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
69146       if( pExpr->u.zToken[1]!=0 ){
69147         sqlite3VdbeChangeP4(v, -1, pExpr->u.zToken, 0);
69148       }
69149       break;
69150     }
69151     case TK_REGISTER: {
69152       inReg = pExpr->iTable;
69153       break;
69154     }
69155     case TK_AS: {
69156       inReg = codeAlias(pParse, pExpr->iTable, pExpr->pLeft, target);
69157       break;
69158     }
69159 #ifndef SQLITE_OMIT_CAST
69160     case TK_CAST: {
69161       /* Expressions of the form:   CAST(pLeft AS token) */
69162       int aff, to_op;
69163       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
69164       assert( !ExprHasProperty(pExpr, EP_IntValue) );
69165       aff = sqlite3AffinityType(pExpr->u.zToken);
69166       to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
69167       assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
69168       assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
69169       assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
69170       assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
69171       assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
69172       testcase( to_op==OP_ToText );
69173       testcase( to_op==OP_ToBlob );
69174       testcase( to_op==OP_ToNumeric );
69175       testcase( to_op==OP_ToInt );
69176       testcase( to_op==OP_ToReal );
69177       if( inReg!=target ){
69178         sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
69179         inReg = target;
69180       }
69181       sqlite3VdbeAddOp1(v, to_op, inReg);
69182       testcase( usedAsColumnCache(pParse, inReg, inReg) );
69183       sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
69184       break;
69185     }
69186 #endif /* SQLITE_OMIT_CAST */
69187     case TK_LT:
69188     case TK_LE:
69189     case TK_GT:
69190     case TK_GE:
69191     case TK_NE:
69192     case TK_EQ: {
69193       assert( TK_LT==OP_Lt );
69194       assert( TK_LE==OP_Le );
69195       assert( TK_GT==OP_Gt );
69196       assert( TK_GE==OP_Ge );
69197       assert( TK_EQ==OP_Eq );
69198       assert( TK_NE==OP_Ne );
69199       testcase( op==TK_LT );
69200       testcase( op==TK_LE );
69201       testcase( op==TK_GT );
69202       testcase( op==TK_GE );
69203       testcase( op==TK_EQ );
69204       testcase( op==TK_NE );
69205       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
69206       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
69207       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
69208                   r1, r2, inReg, SQLITE_STOREP2);
69209       testcase( regFree1==0 );
69210       testcase( regFree2==0 );
69211       break;
69212     }
69213     case TK_IS:
69214     case TK_ISNOT: {
69215       testcase( op==TK_IS );
69216       testcase( op==TK_ISNOT );
69217       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
69218       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
69219       op = (op==TK_IS) ? TK_EQ : TK_NE;
69220       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
69221                   r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
69222       testcase( regFree1==0 );
69223       testcase( regFree2==0 );
69224       break;
69225     }
69226     case TK_AND:
69227     case TK_OR:
69228     case TK_PLUS:
69229     case TK_STAR:
69230     case TK_MINUS:
69231     case TK_REM:
69232     case TK_BITAND:
69233     case TK_BITOR:
69234     case TK_SLASH:
69235     case TK_LSHIFT:
69236     case TK_RSHIFT: 
69237     case TK_CONCAT: {
69238       assert( TK_AND==OP_And );
69239       assert( TK_OR==OP_Or );
69240       assert( TK_PLUS==OP_Add );
69241       assert( TK_MINUS==OP_Subtract );
69242       assert( TK_REM==OP_Remainder );
69243       assert( TK_BITAND==OP_BitAnd );
69244       assert( TK_BITOR==OP_BitOr );
69245       assert( TK_SLASH==OP_Divide );
69246       assert( TK_LSHIFT==OP_ShiftLeft );
69247       assert( TK_RSHIFT==OP_ShiftRight );
69248       assert( TK_CONCAT==OP_Concat );
69249       testcase( op==TK_AND );
69250       testcase( op==TK_OR );
69251       testcase( op==TK_PLUS );
69252       testcase( op==TK_MINUS );
69253       testcase( op==TK_REM );
69254       testcase( op==TK_BITAND );
69255       testcase( op==TK_BITOR );
69256       testcase( op==TK_SLASH );
69257       testcase( op==TK_LSHIFT );
69258       testcase( op==TK_RSHIFT );
69259       testcase( op==TK_CONCAT );
69260       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
69261       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
69262       sqlite3VdbeAddOp3(v, op, r2, r1, target);
69263       testcase( regFree1==0 );
69264       testcase( regFree2==0 );
69265       break;
69266     }
69267     case TK_UMINUS: {
69268       Expr *pLeft = pExpr->pLeft;
69269       assert( pLeft );
69270       if( pLeft->op==TK_INTEGER ){
69271         codeInteger(pParse, pLeft, 1, target);
69272 #ifndef SQLITE_OMIT_FLOATING_POINT
69273       }else if( pLeft->op==TK_FLOAT ){
69274         assert( !ExprHasProperty(pExpr, EP_IntValue) );
69275         codeReal(v, pLeft->u.zToken, 1, target);
69276 #endif
69277       }else{
69278         regFree1 = r1 = sqlite3GetTempReg(pParse);
69279         sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
69280         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
69281         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
69282         testcase( regFree2==0 );
69283       }
69284       inReg = target;
69285       break;
69286     }
69287     case TK_BITNOT:
69288     case TK_NOT: {
69289       assert( TK_BITNOT==OP_BitNot );
69290       assert( TK_NOT==OP_Not );
69291       testcase( op==TK_BITNOT );
69292       testcase( op==TK_NOT );
69293       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
69294       testcase( regFree1==0 );
69295       inReg = target;
69296       sqlite3VdbeAddOp2(v, op, r1, inReg);
69297       break;
69298     }
69299     case TK_ISNULL:
69300     case TK_NOTNULL: {
69301       int addr;
69302       assert( TK_ISNULL==OP_IsNull );
69303       assert( TK_NOTNULL==OP_NotNull );
69304       testcase( op==TK_ISNULL );
69305       testcase( op==TK_NOTNULL );
69306       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
69307       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
69308       testcase( regFree1==0 );
69309       addr = sqlite3VdbeAddOp1(v, op, r1);
69310       sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
69311       sqlite3VdbeJumpHere(v, addr);
69312       break;
69313     }
69314     case TK_AGG_FUNCTION: {
69315       AggInfo *pInfo = pExpr->pAggInfo;
69316       if( pInfo==0 ){
69317         assert( !ExprHasProperty(pExpr, EP_IntValue) );
69318         sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
69319       }else{
69320         inReg = pInfo->aFunc[pExpr->iAgg].iMem;
69321       }
69322       break;
69323     }
69324     case TK_CONST_FUNC:
69325     case TK_FUNCTION: {
69326       ExprList *pFarg;       /* List of function arguments */
69327       int nFarg;             /* Number of function arguments */
69328       FuncDef *pDef;         /* The function definition object */
69329       int nId;               /* Length of the function name in bytes */
69330       const char *zId;       /* The function name */
69331       int constMask = 0;     /* Mask of function arguments that are constant */
69332       int i;                 /* Loop counter */
69333       u8 enc = ENC(db);      /* The text encoding used by this database */
69334       CollSeq *pColl = 0;    /* A collating sequence */
69335
69336       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
69337       testcase( op==TK_CONST_FUNC );
69338       testcase( op==TK_FUNCTION );
69339       if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
69340         pFarg = 0;
69341       }else{
69342         pFarg = pExpr->x.pList;
69343       }
69344       nFarg = pFarg ? pFarg->nExpr : 0;
69345       assert( !ExprHasProperty(pExpr, EP_IntValue) );
69346       zId = pExpr->u.zToken;
69347       nId = sqlite3Strlen30(zId);
69348       pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
69349       if( pDef==0 ){
69350         sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
69351         break;
69352       }
69353
69354       /* Attempt a direct implementation of the built-in COALESCE() and
69355       ** IFNULL() functions.  This avoids unnecessary evalation of
69356       ** arguments past the first non-NULL argument.
69357       */
69358       if( pDef->flags & SQLITE_FUNC_COALESCE ){
69359         int endCoalesce = sqlite3VdbeMakeLabel(v);
69360         assert( nFarg>=2 );
69361         sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
69362         for(i=1; i<nFarg; i++){
69363           sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
69364           sqlite3ExprCacheRemove(pParse, target, 1);
69365           sqlite3ExprCachePush(pParse);
69366           sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
69367           sqlite3ExprCachePop(pParse, 1);
69368         }
69369         sqlite3VdbeResolveLabel(v, endCoalesce);
69370         break;
69371       }
69372
69373
69374       if( pFarg ){
69375         r1 = sqlite3GetTempRange(pParse, nFarg);
69376         sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
69377         sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
69378         sqlite3ExprCachePop(pParse, 1);   /* Ticket 2ea2425d34be */
69379       }else{
69380         r1 = 0;
69381       }
69382 #ifndef SQLITE_OMIT_VIRTUALTABLE
69383       /* Possibly overload the function if the first argument is
69384       ** a virtual table column.
69385       **
69386       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
69387       ** second argument, not the first, as the argument to test to
69388       ** see if it is a column in a virtual table.  This is done because
69389       ** the left operand of infix functions (the operand we want to
69390       ** control overloading) ends up as the second argument to the
69391       ** function.  The expression "A glob B" is equivalent to 
69392       ** "glob(B,A).  We want to use the A in "A glob B" to test
69393       ** for function overloading.  But we use the B term in "glob(B,A)".
69394       */
69395       if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
69396         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
69397       }else if( nFarg>0 ){
69398         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
69399       }
69400 #endif
69401       for(i=0; i<nFarg; i++){
69402         if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
69403           constMask |= (1<<i);
69404         }
69405         if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
69406           pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
69407         }
69408       }
69409       if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
69410         if( !pColl ) pColl = db->pDfltColl; 
69411         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
69412       }
69413       sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
69414                         (char*)pDef, P4_FUNCDEF);
69415       sqlite3VdbeChangeP5(v, (u8)nFarg);
69416       if( nFarg ){
69417         sqlite3ReleaseTempRange(pParse, r1, nFarg);
69418       }
69419       break;
69420     }
69421 #ifndef SQLITE_OMIT_SUBQUERY
69422     case TK_EXISTS:
69423     case TK_SELECT: {
69424       testcase( op==TK_EXISTS );
69425       testcase( op==TK_SELECT );
69426       inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
69427       break;
69428     }
69429     case TK_IN: {
69430       int destIfFalse = sqlite3VdbeMakeLabel(v);
69431       int destIfNull = sqlite3VdbeMakeLabel(v);
69432       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
69433       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
69434       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
69435       sqlite3VdbeResolveLabel(v, destIfFalse);
69436       sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
69437       sqlite3VdbeResolveLabel(v, destIfNull);
69438       break;
69439     }
69440 #endif /* SQLITE_OMIT_SUBQUERY */
69441
69442
69443     /*
69444     **    x BETWEEN y AND z
69445     **
69446     ** This is equivalent to
69447     **
69448     **    x>=y AND x<=z
69449     **
69450     ** X is stored in pExpr->pLeft.
69451     ** Y is stored in pExpr->pList->a[0].pExpr.
69452     ** Z is stored in pExpr->pList->a[1].pExpr.
69453     */
69454     case TK_BETWEEN: {
69455       Expr *pLeft = pExpr->pLeft;
69456       struct ExprList_item *pLItem = pExpr->x.pList->a;
69457       Expr *pRight = pLItem->pExpr;
69458
69459       r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
69460       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
69461       testcase( regFree1==0 );
69462       testcase( regFree2==0 );
69463       r3 = sqlite3GetTempReg(pParse);
69464       r4 = sqlite3GetTempReg(pParse);
69465       codeCompare(pParse, pLeft, pRight, OP_Ge,
69466                   r1, r2, r3, SQLITE_STOREP2);
69467       pLItem++;
69468       pRight = pLItem->pExpr;
69469       sqlite3ReleaseTempReg(pParse, regFree2);
69470       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
69471       testcase( regFree2==0 );
69472       codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
69473       sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
69474       sqlite3ReleaseTempReg(pParse, r3);
69475       sqlite3ReleaseTempReg(pParse, r4);
69476       break;
69477     }
69478     case TK_UPLUS: {
69479       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
69480       break;
69481     }
69482
69483     case TK_TRIGGER: {
69484       /* If the opcode is TK_TRIGGER, then the expression is a reference
69485       ** to a column in the new.* or old.* pseudo-tables available to
69486       ** trigger programs. In this case Expr.iTable is set to 1 for the
69487       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
69488       ** is set to the column of the pseudo-table to read, or to -1 to
69489       ** read the rowid field.
69490       **
69491       ** The expression is implemented using an OP_Param opcode. The p1
69492       ** parameter is set to 0 for an old.rowid reference, or to (i+1)
69493       ** to reference another column of the old.* pseudo-table, where 
69494       ** i is the index of the column. For a new.rowid reference, p1 is
69495       ** set to (n+1), where n is the number of columns in each pseudo-table.
69496       ** For a reference to any other column in the new.* pseudo-table, p1
69497       ** is set to (n+2+i), where n and i are as defined previously. For
69498       ** example, if the table on which triggers are being fired is
69499       ** declared as:
69500       **
69501       **   CREATE TABLE t1(a, b);
69502       **
69503       ** Then p1 is interpreted as follows:
69504       **
69505       **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
69506       **   p1==1   ->    old.a         p1==4   ->    new.a
69507       **   p1==2   ->    old.b         p1==5   ->    new.b       
69508       */
69509       Table *pTab = pExpr->pTab;
69510       int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
69511
69512       assert( pExpr->iTable==0 || pExpr->iTable==1 );
69513       assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
69514       assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
69515       assert( p1>=0 && p1<(pTab->nCol*2+2) );
69516
69517       sqlite3VdbeAddOp2(v, OP_Param, p1, target);
69518       VdbeComment((v, "%s.%s -> $%d",
69519         (pExpr->iTable ? "new" : "old"),
69520         (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
69521         target
69522       ));
69523
69524 #ifndef SQLITE_OMIT_FLOATING_POINT
69525       /* If the column has REAL affinity, it may currently be stored as an
69526       ** integer. Use OP_RealAffinity to make sure it is really real.  */
69527       if( pExpr->iColumn>=0 
69528        && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
69529       ){
69530         sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
69531       }
69532 #endif
69533       break;
69534     }
69535
69536
69537     /*
69538     ** Form A:
69539     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
69540     **
69541     ** Form B:
69542     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
69543     **
69544     ** Form A is can be transformed into the equivalent form B as follows:
69545     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
69546     **        WHEN x=eN THEN rN ELSE y END
69547     **
69548     ** X (if it exists) is in pExpr->pLeft.
69549     ** Y is in pExpr->pRight.  The Y is also optional.  If there is no
69550     ** ELSE clause and no other term matches, then the result of the
69551     ** exprssion is NULL.
69552     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
69553     **
69554     ** The result of the expression is the Ri for the first matching Ei,
69555     ** or if there is no matching Ei, the ELSE term Y, or if there is
69556     ** no ELSE term, NULL.
69557     */
69558     default: assert( op==TK_CASE ); {
69559       int endLabel;                     /* GOTO label for end of CASE stmt */
69560       int nextCase;                     /* GOTO label for next WHEN clause */
69561       int nExpr;                        /* 2x number of WHEN terms */
69562       int i;                            /* Loop counter */
69563       ExprList *pEList;                 /* List of WHEN terms */
69564       struct ExprList_item *aListelem;  /* Array of WHEN terms */
69565       Expr opCompare;                   /* The X==Ei expression */
69566       Expr cacheX;                      /* Cached expression X */
69567       Expr *pX;                         /* The X expression */
69568       Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
69569       VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
69570
69571       assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
69572       assert((pExpr->x.pList->nExpr % 2) == 0);
69573       assert(pExpr->x.pList->nExpr > 0);
69574       pEList = pExpr->x.pList;
69575       aListelem = pEList->a;
69576       nExpr = pEList->nExpr;
69577       endLabel = sqlite3VdbeMakeLabel(v);
69578       if( (pX = pExpr->pLeft)!=0 ){
69579         cacheX = *pX;
69580         testcase( pX->op==TK_COLUMN );
69581         testcase( pX->op==TK_REGISTER );
69582         cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
69583         testcase( regFree1==0 );
69584         cacheX.op = TK_REGISTER;
69585         opCompare.op = TK_EQ;
69586         opCompare.pLeft = &cacheX;
69587         pTest = &opCompare;
69588       }
69589       for(i=0; i<nExpr; i=i+2){
69590         sqlite3ExprCachePush(pParse);
69591         if( pX ){
69592           assert( pTest!=0 );
69593           opCompare.pRight = aListelem[i].pExpr;
69594         }else{
69595           pTest = aListelem[i].pExpr;
69596         }
69597         nextCase = sqlite3VdbeMakeLabel(v);
69598         testcase( pTest->op==TK_COLUMN );
69599         sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
69600         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
69601         testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
69602         sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
69603         sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
69604         sqlite3ExprCachePop(pParse, 1);
69605         sqlite3VdbeResolveLabel(v, nextCase);
69606       }
69607       if( pExpr->pRight ){
69608         sqlite3ExprCachePush(pParse);
69609         sqlite3ExprCode(pParse, pExpr->pRight, target);
69610         sqlite3ExprCachePop(pParse, 1);
69611       }else{
69612         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
69613       }
69614       assert( db->mallocFailed || pParse->nErr>0 
69615            || pParse->iCacheLevel==iCacheLevel );
69616       sqlite3VdbeResolveLabel(v, endLabel);
69617       break;
69618     }
69619 #ifndef SQLITE_OMIT_TRIGGER
69620     case TK_RAISE: {
69621       assert( pExpr->affinity==OE_Rollback 
69622            || pExpr->affinity==OE_Abort
69623            || pExpr->affinity==OE_Fail
69624            || pExpr->affinity==OE_Ignore
69625       );
69626       if( !pParse->pTriggerTab ){
69627         sqlite3ErrorMsg(pParse,
69628                        "RAISE() may only be used within a trigger-program");
69629         return 0;
69630       }
69631       if( pExpr->affinity==OE_Abort ){
69632         sqlite3MayAbort(pParse);
69633       }
69634       assert( !ExprHasProperty(pExpr, EP_IntValue) );
69635       if( pExpr->affinity==OE_Ignore ){
69636         sqlite3VdbeAddOp4(
69637             v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
69638       }else{
69639         sqlite3HaltConstraint(pParse, pExpr->affinity, pExpr->u.zToken, 0);
69640       }
69641
69642       break;
69643     }
69644 #endif
69645   }
69646   sqlite3ReleaseTempReg(pParse, regFree1);
69647   sqlite3ReleaseTempReg(pParse, regFree2);
69648   return inReg;
69649 }
69650
69651 /*
69652 ** Generate code to evaluate an expression and store the results
69653 ** into a register.  Return the register number where the results
69654 ** are stored.
69655 **
69656 ** If the register is a temporary register that can be deallocated,
69657 ** then write its number into *pReg.  If the result register is not
69658 ** a temporary, then set *pReg to zero.
69659 */
69660 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
69661   int r1 = sqlite3GetTempReg(pParse);
69662   int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
69663   if( r2==r1 ){
69664     *pReg = r1;
69665   }else{
69666     sqlite3ReleaseTempReg(pParse, r1);
69667     *pReg = 0;
69668   }
69669   return r2;
69670 }
69671
69672 /*
69673 ** Generate code that will evaluate expression pExpr and store the
69674 ** results in register target.  The results are guaranteed to appear
69675 ** in register target.
69676 */
69677 SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
69678   int inReg;
69679
69680   assert( target>0 && target<=pParse->nMem );
69681   inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
69682   assert( pParse->pVdbe || pParse->db->mallocFailed );
69683   if( inReg!=target && pParse->pVdbe ){
69684     sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
69685   }
69686   return target;
69687 }
69688
69689 /*
69690 ** Generate code that evalutes the given expression and puts the result
69691 ** in register target.
69692 **
69693 ** Also make a copy of the expression results into another "cache" register
69694 ** and modify the expression so that the next time it is evaluated,
69695 ** the result is a copy of the cache register.
69696 **
69697 ** This routine is used for expressions that are used multiple 
69698 ** times.  They are evaluated once and the results of the expression
69699 ** are reused.
69700 */
69701 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
69702   Vdbe *v = pParse->pVdbe;
69703   int inReg;
69704   inReg = sqlite3ExprCode(pParse, pExpr, target);
69705   assert( target>0 );
69706   /* This routine is called for terms to INSERT or UPDATE.  And the only
69707   ** other place where expressions can be converted into TK_REGISTER is
69708   ** in WHERE clause processing.  So as currently implemented, there is
69709   ** no way for a TK_REGISTER to exist here.  But it seems prudent to
69710   ** keep the ALWAYS() in case the conditions above change with future
69711   ** modifications or enhancements. */
69712   if( ALWAYS(pExpr->op!=TK_REGISTER) ){  
69713     int iMem;
69714     iMem = ++pParse->nMem;
69715     sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
69716     pExpr->iTable = iMem;
69717     pExpr->op2 = pExpr->op;
69718     pExpr->op = TK_REGISTER;
69719   }
69720   return inReg;
69721 }
69722
69723 /*
69724 ** Return TRUE if pExpr is an constant expression that is appropriate
69725 ** for factoring out of a loop.  Appropriate expressions are:
69726 **
69727 **    *  Any expression that evaluates to two or more opcodes.
69728 **
69729 **    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null, 
69730 **       or OP_Variable that does not need to be placed in a 
69731 **       specific register.
69732 **
69733 ** There is no point in factoring out single-instruction constant
69734 ** expressions that need to be placed in a particular register.  
69735 ** We could factor them out, but then we would end up adding an
69736 ** OP_SCopy instruction to move the value into the correct register
69737 ** later.  We might as well just use the original instruction and
69738 ** avoid the OP_SCopy.
69739 */
69740 static int isAppropriateForFactoring(Expr *p){
69741   if( !sqlite3ExprIsConstantNotJoin(p) ){
69742     return 0;  /* Only constant expressions are appropriate for factoring */
69743   }
69744   if( (p->flags & EP_FixedDest)==0 ){
69745     return 1;  /* Any constant without a fixed destination is appropriate */
69746   }
69747   while( p->op==TK_UPLUS ) p = p->pLeft;
69748   switch( p->op ){
69749 #ifndef SQLITE_OMIT_BLOB_LITERAL
69750     case TK_BLOB:
69751 #endif
69752     case TK_VARIABLE:
69753     case TK_INTEGER:
69754     case TK_FLOAT:
69755     case TK_NULL:
69756     case TK_STRING: {
69757       testcase( p->op==TK_BLOB );
69758       testcase( p->op==TK_VARIABLE );
69759       testcase( p->op==TK_INTEGER );
69760       testcase( p->op==TK_FLOAT );
69761       testcase( p->op==TK_NULL );
69762       testcase( p->op==TK_STRING );
69763       /* Single-instruction constants with a fixed destination are
69764       ** better done in-line.  If we factor them, they will just end
69765       ** up generating an OP_SCopy to move the value to the destination
69766       ** register. */
69767       return 0;
69768     }
69769     case TK_UMINUS: {
69770       if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
69771         return 0;
69772       }
69773       break;
69774     }
69775     default: {
69776       break;
69777     }
69778   }
69779   return 1;
69780 }
69781
69782 /*
69783 ** If pExpr is a constant expression that is appropriate for
69784 ** factoring out of a loop, then evaluate the expression
69785 ** into a register and convert the expression into a TK_REGISTER
69786 ** expression.
69787 */
69788 static int evalConstExpr(Walker *pWalker, Expr *pExpr){
69789   Parse *pParse = pWalker->pParse;
69790   switch( pExpr->op ){
69791     case TK_IN:
69792     case TK_REGISTER: {
69793       return WRC_Prune;
69794     }
69795     case TK_FUNCTION:
69796     case TK_AGG_FUNCTION:
69797     case TK_CONST_FUNC: {
69798       /* The arguments to a function have a fixed destination.
69799       ** Mark them this way to avoid generated unneeded OP_SCopy
69800       ** instructions. 
69801       */
69802       ExprList *pList = pExpr->x.pList;
69803       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
69804       if( pList ){
69805         int i = pList->nExpr;
69806         struct ExprList_item *pItem = pList->a;
69807         for(; i>0; i--, pItem++){
69808           if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
69809         }
69810       }
69811       break;
69812     }
69813   }
69814   if( isAppropriateForFactoring(pExpr) ){
69815     int r1 = ++pParse->nMem;
69816     int r2;
69817     r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
69818     if( NEVER(r1!=r2) ) sqlite3ReleaseTempReg(pParse, r1);
69819     pExpr->op2 = pExpr->op;
69820     pExpr->op = TK_REGISTER;
69821     pExpr->iTable = r2;
69822     return WRC_Prune;
69823   }
69824   return WRC_Continue;
69825 }
69826
69827 /*
69828 ** Preevaluate constant subexpressions within pExpr and store the
69829 ** results in registers.  Modify pExpr so that the constant subexpresions
69830 ** are TK_REGISTER opcodes that refer to the precomputed values.
69831 */
69832 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
69833   Walker w;
69834   w.xExprCallback = evalConstExpr;
69835   w.xSelectCallback = 0;
69836   w.pParse = pParse;
69837   sqlite3WalkExpr(&w, pExpr);
69838 }
69839
69840
69841 /*
69842 ** Generate code that pushes the value of every element of the given
69843 ** expression list into a sequence of registers beginning at target.
69844 **
69845 ** Return the number of elements evaluated.
69846 */
69847 SQLITE_PRIVATE int sqlite3ExprCodeExprList(
69848   Parse *pParse,     /* Parsing context */
69849   ExprList *pList,   /* The expression list to be coded */
69850   int target,        /* Where to write results */
69851   int doHardCopy     /* Make a hard copy of every element */
69852 ){
69853   struct ExprList_item *pItem;
69854   int i, n;
69855   assert( pList!=0 );
69856   assert( target>0 );
69857   n = pList->nExpr;
69858   for(pItem=pList->a, i=0; i<n; i++, pItem++){
69859     if( pItem->iAlias ){
69860       int iReg = codeAlias(pParse, pItem->iAlias, pItem->pExpr, target+i);
69861       Vdbe *v = sqlite3GetVdbe(pParse);
69862       if( iReg!=target+i ){
69863         sqlite3VdbeAddOp2(v, OP_SCopy, iReg, target+i);
69864       }
69865     }else{
69866       sqlite3ExprCode(pParse, pItem->pExpr, target+i);
69867     }
69868     if( doHardCopy && !pParse->db->mallocFailed ){
69869       sqlite3ExprHardCopy(pParse, target, n);
69870     }
69871   }
69872   return n;
69873 }
69874
69875 /*
69876 ** Generate code for a BETWEEN operator.
69877 **
69878 **    x BETWEEN y AND z
69879 **
69880 ** The above is equivalent to 
69881 **
69882 **    x>=y AND x<=z
69883 **
69884 ** Code it as such, taking care to do the common subexpression
69885 ** elementation of x.
69886 */
69887 static void exprCodeBetween(
69888   Parse *pParse,    /* Parsing and code generating context */
69889   Expr *pExpr,      /* The BETWEEN expression */
69890   int dest,         /* Jump here if the jump is taken */
69891   int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
69892   int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
69893 ){
69894   Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
69895   Expr compLeft;    /* The  x>=y  term */
69896   Expr compRight;   /* The  x<=z  term */
69897   Expr exprX;       /* The  x  subexpression */
69898   int regFree1 = 0; /* Temporary use register */
69899
69900   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
69901   exprX = *pExpr->pLeft;
69902   exprAnd.op = TK_AND;
69903   exprAnd.pLeft = &compLeft;
69904   exprAnd.pRight = &compRight;
69905   compLeft.op = TK_GE;
69906   compLeft.pLeft = &exprX;
69907   compLeft.pRight = pExpr->x.pList->a[0].pExpr;
69908   compRight.op = TK_LE;
69909   compRight.pLeft = &exprX;
69910   compRight.pRight = pExpr->x.pList->a[1].pExpr;
69911   exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
69912   exprX.op = TK_REGISTER;
69913   if( jumpIfTrue ){
69914     sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
69915   }else{
69916     sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
69917   }
69918   sqlite3ReleaseTempReg(pParse, regFree1);
69919
69920   /* Ensure adequate test coverage */
69921   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
69922   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
69923   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
69924   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
69925   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
69926   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
69927   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
69928   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
69929 }
69930
69931 /*
69932 ** Generate code for a boolean expression such that a jump is made
69933 ** to the label "dest" if the expression is true but execution
69934 ** continues straight thru if the expression is false.
69935 **
69936 ** If the expression evaluates to NULL (neither true nor false), then
69937 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
69938 **
69939 ** This code depends on the fact that certain token values (ex: TK_EQ)
69940 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
69941 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
69942 ** the make process cause these values to align.  Assert()s in the code
69943 ** below verify that the numbers are aligned correctly.
69944 */
69945 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
69946   Vdbe *v = pParse->pVdbe;
69947   int op = 0;
69948   int regFree1 = 0;
69949   int regFree2 = 0;
69950   int r1, r2;
69951
69952   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
69953   if( NEVER(v==0) )     return;  /* Existance of VDBE checked by caller */
69954   if( NEVER(pExpr==0) ) return;  /* No way this can happen */
69955   op = pExpr->op;
69956   switch( op ){
69957     case TK_AND: {
69958       int d2 = sqlite3VdbeMakeLabel(v);
69959       testcase( jumpIfNull==0 );
69960       sqlite3ExprCachePush(pParse);
69961       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
69962       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
69963       sqlite3VdbeResolveLabel(v, d2);
69964       sqlite3ExprCachePop(pParse, 1);
69965       break;
69966     }
69967     case TK_OR: {
69968       testcase( jumpIfNull==0 );
69969       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
69970       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
69971       break;
69972     }
69973     case TK_NOT: {
69974       testcase( jumpIfNull==0 );
69975       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
69976       break;
69977     }
69978     case TK_LT:
69979     case TK_LE:
69980     case TK_GT:
69981     case TK_GE:
69982     case TK_NE:
69983     case TK_EQ: {
69984       assert( TK_LT==OP_Lt );
69985       assert( TK_LE==OP_Le );
69986       assert( TK_GT==OP_Gt );
69987       assert( TK_GE==OP_Ge );
69988       assert( TK_EQ==OP_Eq );
69989       assert( TK_NE==OP_Ne );
69990       testcase( op==TK_LT );
69991       testcase( op==TK_LE );
69992       testcase( op==TK_GT );
69993       testcase( op==TK_GE );
69994       testcase( op==TK_EQ );
69995       testcase( op==TK_NE );
69996       testcase( jumpIfNull==0 );
69997       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
69998       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
69999       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
70000                   r1, r2, dest, jumpIfNull);
70001       testcase( regFree1==0 );
70002       testcase( regFree2==0 );
70003       break;
70004     }
70005     case TK_IS:
70006     case TK_ISNOT: {
70007       testcase( op==TK_IS );
70008       testcase( op==TK_ISNOT );
70009       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
70010       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
70011       op = (op==TK_IS) ? TK_EQ : TK_NE;
70012       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
70013                   r1, r2, dest, SQLITE_NULLEQ);
70014       testcase( regFree1==0 );
70015       testcase( regFree2==0 );
70016       break;
70017     }
70018     case TK_ISNULL:
70019     case TK_NOTNULL: {
70020       assert( TK_ISNULL==OP_IsNull );
70021       assert( TK_NOTNULL==OP_NotNull );
70022       testcase( op==TK_ISNULL );
70023       testcase( op==TK_NOTNULL );
70024       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
70025       sqlite3VdbeAddOp2(v, op, r1, dest);
70026       testcase( regFree1==0 );
70027       break;
70028     }
70029     case TK_BETWEEN: {
70030       testcase( jumpIfNull==0 );
70031       exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
70032       break;
70033     }
70034     case TK_IN: {
70035       int destIfFalse = sqlite3VdbeMakeLabel(v);
70036       int destIfNull = jumpIfNull ? dest : destIfFalse;
70037       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
70038       sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
70039       sqlite3VdbeResolveLabel(v, destIfFalse);
70040       break;
70041     }
70042     default: {
70043       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
70044       sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
70045       testcase( regFree1==0 );
70046       testcase( jumpIfNull==0 );
70047       break;
70048     }
70049   }
70050   sqlite3ReleaseTempReg(pParse, regFree1);
70051   sqlite3ReleaseTempReg(pParse, regFree2);  
70052 }
70053
70054 /*
70055 ** Generate code for a boolean expression such that a jump is made
70056 ** to the label "dest" if the expression is false but execution
70057 ** continues straight thru if the expression is true.
70058 **
70059 ** If the expression evaluates to NULL (neither true nor false) then
70060 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
70061 ** is 0.
70062 */
70063 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
70064   Vdbe *v = pParse->pVdbe;
70065   int op = 0;
70066   int regFree1 = 0;
70067   int regFree2 = 0;
70068   int r1, r2;
70069
70070   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
70071   if( NEVER(v==0) ) return; /* Existance of VDBE checked by caller */
70072   if( pExpr==0 )    return;
70073
70074   /* The value of pExpr->op and op are related as follows:
70075   **
70076   **       pExpr->op            op
70077   **       ---------          ----------
70078   **       TK_ISNULL          OP_NotNull
70079   **       TK_NOTNULL         OP_IsNull
70080   **       TK_NE              OP_Eq
70081   **       TK_EQ              OP_Ne
70082   **       TK_GT              OP_Le
70083   **       TK_LE              OP_Gt
70084   **       TK_GE              OP_Lt
70085   **       TK_LT              OP_Ge
70086   **
70087   ** For other values of pExpr->op, op is undefined and unused.
70088   ** The value of TK_ and OP_ constants are arranged such that we
70089   ** can compute the mapping above using the following expression.
70090   ** Assert()s verify that the computation is correct.
70091   */
70092   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
70093
70094   /* Verify correct alignment of TK_ and OP_ constants
70095   */
70096   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
70097   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
70098   assert( pExpr->op!=TK_NE || op==OP_Eq );
70099   assert( pExpr->op!=TK_EQ || op==OP_Ne );
70100   assert( pExpr->op!=TK_LT || op==OP_Ge );
70101   assert( pExpr->op!=TK_LE || op==OP_Gt );
70102   assert( pExpr->op!=TK_GT || op==OP_Le );
70103   assert( pExpr->op!=TK_GE || op==OP_Lt );
70104
70105   switch( pExpr->op ){
70106     case TK_AND: {
70107       testcase( jumpIfNull==0 );
70108       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
70109       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
70110       break;
70111     }
70112     case TK_OR: {
70113       int d2 = sqlite3VdbeMakeLabel(v);
70114       testcase( jumpIfNull==0 );
70115       sqlite3ExprCachePush(pParse);
70116       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
70117       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
70118       sqlite3VdbeResolveLabel(v, d2);
70119       sqlite3ExprCachePop(pParse, 1);
70120       break;
70121     }
70122     case TK_NOT: {
70123       testcase( jumpIfNull==0 );
70124       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
70125       break;
70126     }
70127     case TK_LT:
70128     case TK_LE:
70129     case TK_GT:
70130     case TK_GE:
70131     case TK_NE:
70132     case TK_EQ: {
70133       testcase( op==TK_LT );
70134       testcase( op==TK_LE );
70135       testcase( op==TK_GT );
70136       testcase( op==TK_GE );
70137       testcase( op==TK_EQ );
70138       testcase( op==TK_NE );
70139       testcase( jumpIfNull==0 );
70140       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
70141       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
70142       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
70143                   r1, r2, dest, jumpIfNull);
70144       testcase( regFree1==0 );
70145       testcase( regFree2==0 );
70146       break;
70147     }
70148     case TK_IS:
70149     case TK_ISNOT: {
70150       testcase( pExpr->op==TK_IS );
70151       testcase( pExpr->op==TK_ISNOT );
70152       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
70153       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
70154       op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
70155       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
70156                   r1, r2, dest, SQLITE_NULLEQ);
70157       testcase( regFree1==0 );
70158       testcase( regFree2==0 );
70159       break;
70160     }
70161     case TK_ISNULL:
70162     case TK_NOTNULL: {
70163       testcase( op==TK_ISNULL );
70164       testcase( op==TK_NOTNULL );
70165       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
70166       sqlite3VdbeAddOp2(v, op, r1, dest);
70167       testcase( regFree1==0 );
70168       break;
70169     }
70170     case TK_BETWEEN: {
70171       testcase( jumpIfNull==0 );
70172       exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
70173       break;
70174     }
70175     case TK_IN: {
70176       if( jumpIfNull ){
70177         sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
70178       }else{
70179         int destIfNull = sqlite3VdbeMakeLabel(v);
70180         sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
70181         sqlite3VdbeResolveLabel(v, destIfNull);
70182       }
70183       break;
70184     }
70185     default: {
70186       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
70187       sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
70188       testcase( regFree1==0 );
70189       testcase( jumpIfNull==0 );
70190       break;
70191     }
70192   }
70193   sqlite3ReleaseTempReg(pParse, regFree1);
70194   sqlite3ReleaseTempReg(pParse, regFree2);
70195 }
70196
70197 /*
70198 ** Do a deep comparison of two expression trees.  Return 0 if the two
70199 ** expressions are completely identical.  Return 1 if they differ only
70200 ** by a COLLATE operator at the top level.  Return 2 if there are differences
70201 ** other than the top-level COLLATE operator.
70202 **
70203 ** Sometimes this routine will return 2 even if the two expressions
70204 ** really are equivalent.  If we cannot prove that the expressions are
70205 ** identical, we return 2 just to be safe.  So if this routine
70206 ** returns 2, then you do not really know for certain if the two
70207 ** expressions are the same.  But if you get a 0 or 1 return, then you
70208 ** can be sure the expressions are the same.  In the places where
70209 ** this routine is used, it does not hurt to get an extra 2 - that
70210 ** just might result in some slightly slower code.  But returning
70211 ** an incorrect 0 or 1 could lead to a malfunction.
70212 */
70213 SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
70214   if( pA==0||pB==0 ){
70215     return pB==pA ? 0 : 2;
70216   }
70217   assert( !ExprHasAnyProperty(pA, EP_TokenOnly|EP_Reduced) );
70218   assert( !ExprHasAnyProperty(pB, EP_TokenOnly|EP_Reduced) );
70219   if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
70220     return 2;
70221   }
70222   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
70223   if( pA->op!=pB->op ) return 2;
70224   if( sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 2;
70225   if( sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 2;
70226   if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList) ) return 2;
70227   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 2;
70228   if( ExprHasProperty(pA, EP_IntValue) ){
70229     if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
70230       return 2;
70231     }
70232   }else if( pA->op!=TK_COLUMN && pA->u.zToken ){
70233     if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2;
70234     if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ){
70235       return 2;
70236     }
70237   }
70238   if( (pA->flags & EP_ExpCollate)!=(pB->flags & EP_ExpCollate) ) return 1;
70239   if( (pA->flags & EP_ExpCollate)!=0 && pA->pColl!=pB->pColl ) return 2;
70240   return 0;
70241 }
70242
70243 /*
70244 ** Compare two ExprList objects.  Return 0 if they are identical and 
70245 ** non-zero if they differ in any way.
70246 **
70247 ** This routine might return non-zero for equivalent ExprLists.  The
70248 ** only consequence will be disabled optimizations.  But this routine
70249 ** must never return 0 if the two ExprList objects are different, or
70250 ** a malfunction will result.
70251 **
70252 ** Two NULL pointers are considered to be the same.  But a NULL pointer
70253 ** always differs from a non-NULL pointer.
70254 */
70255 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB){
70256   int i;
70257   if( pA==0 && pB==0 ) return 0;
70258   if( pA==0 || pB==0 ) return 1;
70259   if( pA->nExpr!=pB->nExpr ) return 1;
70260   for(i=0; i<pA->nExpr; i++){
70261     Expr *pExprA = pA->a[i].pExpr;
70262     Expr *pExprB = pB->a[i].pExpr;
70263     if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
70264     if( sqlite3ExprCompare(pExprA, pExprB) ) return 1;
70265   }
70266   return 0;
70267 }
70268
70269 /*
70270 ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
70271 ** the new element.  Return a negative number if malloc fails.
70272 */
70273 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
70274   int i;
70275   pInfo->aCol = sqlite3ArrayAllocate(
70276        db,
70277        pInfo->aCol,
70278        sizeof(pInfo->aCol[0]),
70279        3,
70280        &pInfo->nColumn,
70281        &pInfo->nColumnAlloc,
70282        &i
70283   );
70284   return i;
70285 }    
70286
70287 /*
70288 ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
70289 ** the new element.  Return a negative number if malloc fails.
70290 */
70291 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
70292   int i;
70293   pInfo->aFunc = sqlite3ArrayAllocate(
70294        db, 
70295        pInfo->aFunc,
70296        sizeof(pInfo->aFunc[0]),
70297        3,
70298        &pInfo->nFunc,
70299        &pInfo->nFuncAlloc,
70300        &i
70301   );
70302   return i;
70303 }    
70304
70305 /*
70306 ** This is the xExprCallback for a tree walker.  It is used to
70307 ** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
70308 ** for additional information.
70309 */
70310 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
70311   int i;
70312   NameContext *pNC = pWalker->u.pNC;
70313   Parse *pParse = pNC->pParse;
70314   SrcList *pSrcList = pNC->pSrcList;
70315   AggInfo *pAggInfo = pNC->pAggInfo;
70316
70317   switch( pExpr->op ){
70318     case TK_AGG_COLUMN:
70319     case TK_COLUMN: {
70320       testcase( pExpr->op==TK_AGG_COLUMN );
70321       testcase( pExpr->op==TK_COLUMN );
70322       /* Check to see if the column is in one of the tables in the FROM
70323       ** clause of the aggregate query */
70324       if( ALWAYS(pSrcList!=0) ){
70325         struct SrcList_item *pItem = pSrcList->a;
70326         for(i=0; i<pSrcList->nSrc; i++, pItem++){
70327           struct AggInfo_col *pCol;
70328           assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
70329           if( pExpr->iTable==pItem->iCursor ){
70330             /* If we reach this point, it means that pExpr refers to a table
70331             ** that is in the FROM clause of the aggregate query.  
70332             **
70333             ** Make an entry for the column in pAggInfo->aCol[] if there
70334             ** is not an entry there already.
70335             */
70336             int k;
70337             pCol = pAggInfo->aCol;
70338             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
70339               if( pCol->iTable==pExpr->iTable &&
70340                   pCol->iColumn==pExpr->iColumn ){
70341                 break;
70342               }
70343             }
70344             if( (k>=pAggInfo->nColumn)
70345              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0 
70346             ){
70347               pCol = &pAggInfo->aCol[k];
70348               pCol->pTab = pExpr->pTab;
70349               pCol->iTable = pExpr->iTable;
70350               pCol->iColumn = pExpr->iColumn;
70351               pCol->iMem = ++pParse->nMem;
70352               pCol->iSorterColumn = -1;
70353               pCol->pExpr = pExpr;
70354               if( pAggInfo->pGroupBy ){
70355                 int j, n;
70356                 ExprList *pGB = pAggInfo->pGroupBy;
70357                 struct ExprList_item *pTerm = pGB->a;
70358                 n = pGB->nExpr;
70359                 for(j=0; j<n; j++, pTerm++){
70360                   Expr *pE = pTerm->pExpr;
70361                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
70362                       pE->iColumn==pExpr->iColumn ){
70363                     pCol->iSorterColumn = j;
70364                     break;
70365                   }
70366                 }
70367               }
70368               if( pCol->iSorterColumn<0 ){
70369                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
70370               }
70371             }
70372             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
70373             ** because it was there before or because we just created it).
70374             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
70375             ** pAggInfo->aCol[] entry.
70376             */
70377             ExprSetIrreducible(pExpr);
70378             pExpr->pAggInfo = pAggInfo;
70379             pExpr->op = TK_AGG_COLUMN;
70380             pExpr->iAgg = (i16)k;
70381             break;
70382           } /* endif pExpr->iTable==pItem->iCursor */
70383         } /* end loop over pSrcList */
70384       }
70385       return WRC_Prune;
70386     }
70387     case TK_AGG_FUNCTION: {
70388       /* The pNC->nDepth==0 test causes aggregate functions in subqueries
70389       ** to be ignored */
70390       if( pNC->nDepth==0 ){
70391         /* Check to see if pExpr is a duplicate of another aggregate 
70392         ** function that is already in the pAggInfo structure
70393         */
70394         struct AggInfo_func *pItem = pAggInfo->aFunc;
70395         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
70396           if( sqlite3ExprCompare(pItem->pExpr, pExpr)==0 ){
70397             break;
70398           }
70399         }
70400         if( i>=pAggInfo->nFunc ){
70401           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
70402           */
70403           u8 enc = ENC(pParse->db);
70404           i = addAggInfoFunc(pParse->db, pAggInfo);
70405           if( i>=0 ){
70406             assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
70407             pItem = &pAggInfo->aFunc[i];
70408             pItem->pExpr = pExpr;
70409             pItem->iMem = ++pParse->nMem;
70410             assert( !ExprHasProperty(pExpr, EP_IntValue) );
70411             pItem->pFunc = sqlite3FindFunction(pParse->db,
70412                    pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
70413                    pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
70414             if( pExpr->flags & EP_Distinct ){
70415               pItem->iDistinct = pParse->nTab++;
70416             }else{
70417               pItem->iDistinct = -1;
70418             }
70419           }
70420         }
70421         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
70422         */
70423         assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
70424         ExprSetIrreducible(pExpr);
70425         pExpr->iAgg = (i16)i;
70426         pExpr->pAggInfo = pAggInfo;
70427         return WRC_Prune;
70428       }
70429     }
70430   }
70431   return WRC_Continue;
70432 }
70433 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
70434   NameContext *pNC = pWalker->u.pNC;
70435   if( pNC->nDepth==0 ){
70436     pNC->nDepth++;
70437     sqlite3WalkSelect(pWalker, pSelect);
70438     pNC->nDepth--;
70439     return WRC_Prune;
70440   }else{
70441     return WRC_Continue;
70442   }
70443 }
70444
70445 /*
70446 ** Analyze the given expression looking for aggregate functions and
70447 ** for variables that need to be added to the pParse->aAgg[] array.
70448 ** Make additional entries to the pParse->aAgg[] array as necessary.
70449 **
70450 ** This routine should only be called after the expression has been
70451 ** analyzed by sqlite3ResolveExprNames().
70452 */
70453 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
70454   Walker w;
70455   w.xExprCallback = analyzeAggregate;
70456   w.xSelectCallback = analyzeAggregatesInSelect;
70457   w.u.pNC = pNC;
70458   assert( pNC->pSrcList!=0 );
70459   sqlite3WalkExpr(&w, pExpr);
70460 }
70461
70462 /*
70463 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
70464 ** expression list.  Return the number of errors.
70465 **
70466 ** If an error is found, the analysis is cut short.
70467 */
70468 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
70469   struct ExprList_item *pItem;
70470   int i;
70471   if( pList ){
70472     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
70473       sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
70474     }
70475   }
70476 }
70477
70478 /*
70479 ** Allocate a single new register for use to hold some intermediate result.
70480 */
70481 SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
70482   if( pParse->nTempReg==0 ){
70483     return ++pParse->nMem;
70484   }
70485   return pParse->aTempReg[--pParse->nTempReg];
70486 }
70487
70488 /*
70489 ** Deallocate a register, making available for reuse for some other
70490 ** purpose.
70491 **
70492 ** If a register is currently being used by the column cache, then
70493 ** the dallocation is deferred until the column cache line that uses
70494 ** the register becomes stale.
70495 */
70496 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
70497   if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
70498     int i;
70499     struct yColCache *p;
70500     for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
70501       if( p->iReg==iReg ){
70502         p->tempReg = 1;
70503         return;
70504       }
70505     }
70506     pParse->aTempReg[pParse->nTempReg++] = iReg;
70507   }
70508 }
70509
70510 /*
70511 ** Allocate or deallocate a block of nReg consecutive registers
70512 */
70513 SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
70514   int i, n;
70515   i = pParse->iRangeReg;
70516   n = pParse->nRangeReg;
70517   if( nReg<=n ){
70518     assert( !usedAsColumnCache(pParse, i, i+n-1) );
70519     pParse->iRangeReg += nReg;
70520     pParse->nRangeReg -= nReg;
70521   }else{
70522     i = pParse->nMem+1;
70523     pParse->nMem += nReg;
70524   }
70525   return i;
70526 }
70527 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
70528   sqlite3ExprCacheRemove(pParse, iReg, nReg);
70529   if( nReg>pParse->nRangeReg ){
70530     pParse->nRangeReg = nReg;
70531     pParse->iRangeReg = iReg;
70532   }
70533 }
70534
70535 /************** End of expr.c ************************************************/
70536 /************** Begin file alter.c *******************************************/
70537 /*
70538 ** 2005 February 15
70539 **
70540 ** The author disclaims copyright to this source code.  In place of
70541 ** a legal notice, here is a blessing:
70542 **
70543 **    May you do good and not evil.
70544 **    May you find forgiveness for yourself and forgive others.
70545 **    May you share freely, never taking more than you give.
70546 **
70547 *************************************************************************
70548 ** This file contains C code routines that used to generate VDBE code
70549 ** that implements the ALTER TABLE command.
70550 */
70551
70552 /*
70553 ** The code in this file only exists if we are not omitting the
70554 ** ALTER TABLE logic from the build.
70555 */
70556 #ifndef SQLITE_OMIT_ALTERTABLE
70557
70558
70559 /*
70560 ** This function is used by SQL generated to implement the 
70561 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
70562 ** CREATE INDEX command. The second is a table name. The table name in 
70563 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
70564 ** argument and the result returned. Examples:
70565 **
70566 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
70567 **     -> 'CREATE TABLE def(a, b, c)'
70568 **
70569 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
70570 **     -> 'CREATE INDEX i ON def(a, b, c)'
70571 */
70572 static void renameTableFunc(
70573   sqlite3_context *context,
70574   int NotUsed,
70575   sqlite3_value **argv
70576 ){
70577   unsigned char const *zSql = sqlite3_value_text(argv[0]);
70578   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
70579
70580   int token;
70581   Token tname;
70582   unsigned char const *zCsr = zSql;
70583   int len = 0;
70584   char *zRet;
70585
70586   sqlite3 *db = sqlite3_context_db_handle(context);
70587
70588   UNUSED_PARAMETER(NotUsed);
70589
70590   /* The principle used to locate the table name in the CREATE TABLE 
70591   ** statement is that the table name is the first non-space token that
70592   ** is immediately followed by a TK_LP or TK_USING token.
70593   */
70594   if( zSql ){
70595     do {
70596       if( !*zCsr ){
70597         /* Ran out of input before finding an opening bracket. Return NULL. */
70598         return;
70599       }
70600
70601       /* Store the token that zCsr points to in tname. */
70602       tname.z = (char*)zCsr;
70603       tname.n = len;
70604
70605       /* Advance zCsr to the next token. Store that token type in 'token',
70606       ** and its length in 'len' (to be used next iteration of this loop).
70607       */
70608       do {
70609         zCsr += len;
70610         len = sqlite3GetToken(zCsr, &token);
70611       } while( token==TK_SPACE );
70612       assert( len>0 );
70613     } while( token!=TK_LP && token!=TK_USING );
70614
70615     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql, 
70616        zTableName, tname.z+tname.n);
70617     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
70618   }
70619 }
70620
70621 /*
70622 ** This C function implements an SQL user function that is used by SQL code
70623 ** generated by the ALTER TABLE ... RENAME command to modify the definition
70624 ** of any foreign key constraints that use the table being renamed as the 
70625 ** parent table. It is passed three arguments:
70626 **
70627 **   1) The complete text of the CREATE TABLE statement being modified,
70628 **   2) The old name of the table being renamed, and
70629 **   3) The new name of the table being renamed.
70630 **
70631 ** It returns the new CREATE TABLE statement. For example:
70632 **
70633 **   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
70634 **       -> 'CREATE TABLE t1(a REFERENCES t3)'
70635 */
70636 #ifndef SQLITE_OMIT_FOREIGN_KEY
70637 static void renameParentFunc(
70638   sqlite3_context *context,
70639   int NotUsed,
70640   sqlite3_value **argv
70641 ){
70642   sqlite3 *db = sqlite3_context_db_handle(context);
70643   char *zOutput = 0;
70644   char *zResult;
70645   unsigned char const *zInput = sqlite3_value_text(argv[0]);
70646   unsigned char const *zOld = sqlite3_value_text(argv[1]);
70647   unsigned char const *zNew = sqlite3_value_text(argv[2]);
70648
70649   unsigned const char *z;         /* Pointer to token */
70650   int n;                          /* Length of token z */
70651   int token;                      /* Type of token */
70652
70653   UNUSED_PARAMETER(NotUsed);
70654   for(z=zInput; *z; z=z+n){
70655     n = sqlite3GetToken(z, &token);
70656     if( token==TK_REFERENCES ){
70657       char *zParent;
70658       do {
70659         z += n;
70660         n = sqlite3GetToken(z, &token);
70661       }while( token==TK_SPACE );
70662
70663       zParent = sqlite3DbStrNDup(db, (const char *)z, n);
70664       if( zParent==0 ) break;
70665       sqlite3Dequote(zParent);
70666       if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
70667         char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"", 
70668             (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
70669         );
70670         sqlite3DbFree(db, zOutput);
70671         zOutput = zOut;
70672         zInput = &z[n];
70673       }
70674       sqlite3DbFree(db, zParent);
70675     }
70676   }
70677
70678   zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput), 
70679   sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
70680   sqlite3DbFree(db, zOutput);
70681 }
70682 #endif
70683
70684 #ifndef SQLITE_OMIT_TRIGGER
70685 /* This function is used by SQL generated to implement the
70686 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER 
70687 ** statement. The second is a table name. The table name in the CREATE 
70688 ** TRIGGER statement is replaced with the third argument and the result 
70689 ** returned. This is analagous to renameTableFunc() above, except for CREATE
70690 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
70691 */
70692 static void renameTriggerFunc(
70693   sqlite3_context *context,
70694   int NotUsed,
70695   sqlite3_value **argv
70696 ){
70697   unsigned char const *zSql = sqlite3_value_text(argv[0]);
70698   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
70699
70700   int token;
70701   Token tname;
70702   int dist = 3;
70703   unsigned char const *zCsr = zSql;
70704   int len = 0;
70705   char *zRet;
70706   sqlite3 *db = sqlite3_context_db_handle(context);
70707
70708   UNUSED_PARAMETER(NotUsed);
70709
70710   /* The principle used to locate the table name in the CREATE TRIGGER 
70711   ** statement is that the table name is the first token that is immediatedly
70712   ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
70713   ** of TK_WHEN, TK_BEGIN or TK_FOR.
70714   */
70715   if( zSql ){
70716     do {
70717
70718       if( !*zCsr ){
70719         /* Ran out of input before finding the table name. Return NULL. */
70720         return;
70721       }
70722
70723       /* Store the token that zCsr points to in tname. */
70724       tname.z = (char*)zCsr;
70725       tname.n = len;
70726
70727       /* Advance zCsr to the next token. Store that token type in 'token',
70728       ** and its length in 'len' (to be used next iteration of this loop).
70729       */
70730       do {
70731         zCsr += len;
70732         len = sqlite3GetToken(zCsr, &token);
70733       }while( token==TK_SPACE );
70734       assert( len>0 );
70735
70736       /* Variable 'dist' stores the number of tokens read since the most
70737       ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN 
70738       ** token is read and 'dist' equals 2, the condition stated above
70739       ** to be met.
70740       **
70741       ** Note that ON cannot be a database, table or column name, so
70742       ** there is no need to worry about syntax like 
70743       ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
70744       */
70745       dist++;
70746       if( token==TK_DOT || token==TK_ON ){
70747         dist = 0;
70748       }
70749     } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
70750
70751     /* Variable tname now contains the token that is the old table-name
70752     ** in the CREATE TRIGGER statement.
70753     */
70754     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql, 
70755        zTableName, tname.z+tname.n);
70756     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
70757   }
70758 }
70759 #endif   /* !SQLITE_OMIT_TRIGGER */
70760
70761 /*
70762 ** Register built-in functions used to help implement ALTER TABLE
70763 */
70764 SQLITE_PRIVATE void sqlite3AlterFunctions(void){
70765   static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
70766     FUNCTION(sqlite_rename_table,   2, 0, 0, renameTableFunc),
70767 #ifndef SQLITE_OMIT_TRIGGER
70768     FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
70769 #endif
70770 #ifndef SQLITE_OMIT_FOREIGN_KEY
70771     FUNCTION(sqlite_rename_parent,  3, 0, 0, renameParentFunc),
70772 #endif
70773   };
70774   int i;
70775   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
70776   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
70777
70778   for(i=0; i<ArraySize(aAlterTableFuncs); i++){
70779     sqlite3FuncDefInsert(pHash, &aFunc[i]);
70780   }
70781 }
70782
70783 /*
70784 ** This function is used to create the text of expressions of the form:
70785 **
70786 **   name=<constant1> OR name=<constant2> OR ...
70787 **
70788 ** If argument zWhere is NULL, then a pointer string containing the text 
70789 ** "name=<constant>" is returned, where <constant> is the quoted version
70790 ** of the string passed as argument zConstant. The returned buffer is
70791 ** allocated using sqlite3DbMalloc(). It is the responsibility of the
70792 ** caller to ensure that it is eventually freed.
70793 **
70794 ** If argument zWhere is not NULL, then the string returned is 
70795 ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
70796 ** In this case zWhere is passed to sqlite3DbFree() before returning.
70797 ** 
70798 */
70799 static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
70800   char *zNew;
70801   if( !zWhere ){
70802     zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
70803   }else{
70804     zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
70805     sqlite3DbFree(db, zWhere);
70806   }
70807   return zNew;
70808 }
70809
70810 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
70811 /*
70812 ** Generate the text of a WHERE expression which can be used to select all
70813 ** tables that have foreign key constraints that refer to table pTab (i.e.
70814 ** constraints for which pTab is the parent table) from the sqlite_master
70815 ** table.
70816 */
70817 static char *whereForeignKeys(Parse *pParse, Table *pTab){
70818   FKey *p;
70819   char *zWhere = 0;
70820   for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
70821     zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
70822   }
70823   return zWhere;
70824 }
70825 #endif
70826
70827 /*
70828 ** Generate the text of a WHERE expression which can be used to select all
70829 ** temporary triggers on table pTab from the sqlite_temp_master table. If
70830 ** table pTab has no temporary triggers, or is itself stored in the 
70831 ** temporary database, NULL is returned.
70832 */
70833 static char *whereTempTriggers(Parse *pParse, Table *pTab){
70834   Trigger *pTrig;
70835   char *zWhere = 0;
70836   const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
70837
70838   /* If the table is not located in the temp-db (in which case NULL is 
70839   ** returned, loop through the tables list of triggers. For each trigger
70840   ** that is not part of the temp-db schema, add a clause to the WHERE 
70841   ** expression being built up in zWhere.
70842   */
70843   if( pTab->pSchema!=pTempSchema ){
70844     sqlite3 *db = pParse->db;
70845     for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
70846       if( pTrig->pSchema==pTempSchema ){
70847         zWhere = whereOrName(db, zWhere, pTrig->zName);
70848       }
70849     }
70850   }
70851   return zWhere;
70852 }
70853
70854 /*
70855 ** Generate code to drop and reload the internal representation of table
70856 ** pTab from the database, including triggers and temporary triggers.
70857 ** Argument zName is the name of the table in the database schema at
70858 ** the time the generated code is executed. This can be different from
70859 ** pTab->zName if this function is being called to code part of an 
70860 ** "ALTER TABLE RENAME TO" statement.
70861 */
70862 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
70863   Vdbe *v;
70864   char *zWhere;
70865   int iDb;                   /* Index of database containing pTab */
70866 #ifndef SQLITE_OMIT_TRIGGER
70867   Trigger *pTrig;
70868 #endif
70869
70870   v = sqlite3GetVdbe(pParse);
70871   if( NEVER(v==0) ) return;
70872   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
70873   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
70874   assert( iDb>=0 );
70875
70876 #ifndef SQLITE_OMIT_TRIGGER
70877   /* Drop any table triggers from the internal schema. */
70878   for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
70879     int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
70880     assert( iTrigDb==iDb || iTrigDb==1 );
70881     sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
70882   }
70883 #endif
70884
70885   /* Drop the table and index from the internal schema.  */
70886   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
70887
70888   /* Reload the table, index and permanent trigger schemas. */
70889   zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
70890   if( !zWhere ) return;
70891   sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
70892
70893 #ifndef SQLITE_OMIT_TRIGGER
70894   /* Now, if the table is not stored in the temp database, reload any temp 
70895   ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined. 
70896   */
70897   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
70898     sqlite3VdbeAddOp4(v, OP_ParseSchema, 1, 0, 0, zWhere, P4_DYNAMIC);
70899   }
70900 #endif
70901 }
70902
70903 /*
70904 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy" 
70905 ** command. 
70906 */
70907 SQLITE_PRIVATE void sqlite3AlterRenameTable(
70908   Parse *pParse,            /* Parser context. */
70909   SrcList *pSrc,            /* The table to rename. */
70910   Token *pName              /* The new table name. */
70911 ){
70912   int iDb;                  /* Database that contains the table */
70913   char *zDb;                /* Name of database iDb */
70914   Table *pTab;              /* Table being renamed */
70915   char *zName = 0;          /* NULL-terminated version of pName */ 
70916   sqlite3 *db = pParse->db; /* Database connection */
70917   int nTabName;             /* Number of UTF-8 characters in zTabName */
70918   const char *zTabName;     /* Original name of the table */
70919   Vdbe *v;
70920 #ifndef SQLITE_OMIT_TRIGGER
70921   char *zWhere = 0;         /* Where clause to locate temp triggers */
70922 #endif
70923   VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
70924   int savedDbFlags;         /* Saved value of db->flags */
70925
70926   savedDbFlags = db->flags;  
70927   if( NEVER(db->mallocFailed) ) goto exit_rename_table;
70928   assert( pSrc->nSrc==1 );
70929   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
70930
70931   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
70932   if( !pTab ) goto exit_rename_table;
70933   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
70934   zDb = db->aDb[iDb].zName;
70935   db->flags |= SQLITE_PreferBuiltin;
70936
70937   /* Get a NULL terminated version of the new table name. */
70938   zName = sqlite3NameFromToken(db, pName);
70939   if( !zName ) goto exit_rename_table;
70940
70941   /* Check that a table or index named 'zName' does not already exist
70942   ** in database iDb. If so, this is an error.
70943   */
70944   if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
70945     sqlite3ErrorMsg(pParse, 
70946         "there is already another table or index with this name: %s", zName);
70947     goto exit_rename_table;
70948   }
70949
70950   /* Make sure it is not a system table being altered, or a reserved name
70951   ** that the table is being renamed to.
70952   */
70953   if( sqlite3Strlen30(pTab->zName)>6 
70954    && 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7)
70955   ){
70956     sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
70957     goto exit_rename_table;
70958   }
70959   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
70960     goto exit_rename_table;
70961   }
70962
70963 #ifndef SQLITE_OMIT_VIEW
70964   if( pTab->pSelect ){
70965     sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
70966     goto exit_rename_table;
70967   }
70968 #endif
70969
70970 #ifndef SQLITE_OMIT_AUTHORIZATION
70971   /* Invoke the authorization callback. */
70972   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
70973     goto exit_rename_table;
70974   }
70975 #endif
70976
70977 #ifndef SQLITE_OMIT_VIRTUALTABLE
70978   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
70979     goto exit_rename_table;
70980   }
70981   if( IsVirtual(pTab) ){
70982     pVTab = sqlite3GetVTable(db, pTab);
70983     if( pVTab->pVtab->pModule->xRename==0 ){
70984       pVTab = 0;
70985     }
70986   }
70987 #endif
70988
70989   /* Begin a transaction and code the VerifyCookie for database iDb. 
70990   ** Then modify the schema cookie (since the ALTER TABLE modifies the
70991   ** schema). Open a statement transaction if the table is a virtual
70992   ** table.
70993   */
70994   v = sqlite3GetVdbe(pParse);
70995   if( v==0 ){
70996     goto exit_rename_table;
70997   }
70998   sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
70999   sqlite3ChangeCookie(pParse, iDb);
71000
71001   /* If this is a virtual table, invoke the xRename() function if
71002   ** one is defined. The xRename() callback will modify the names
71003   ** of any resources used by the v-table implementation (including other
71004   ** SQLite tables) that are identified by the name of the virtual table.
71005   */
71006 #ifndef SQLITE_OMIT_VIRTUALTABLE
71007   if( pVTab ){
71008     int i = ++pParse->nMem;
71009     sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
71010     sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
71011     sqlite3MayAbort(pParse);
71012   }
71013 #endif
71014
71015   /* figure out how many UTF-8 characters are in zName */
71016   zTabName = pTab->zName;
71017   nTabName = sqlite3Utf8CharLen(zTabName, -1);
71018
71019 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
71020   if( db->flags&SQLITE_ForeignKeys ){
71021     /* If foreign-key support is enabled, rewrite the CREATE TABLE 
71022     ** statements corresponding to all child tables of foreign key constraints
71023     ** for which the renamed table is the parent table.  */
71024     if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
71025       sqlite3NestedParse(pParse, 
71026           "UPDATE \"%w\".%s SET "
71027               "sql = sqlite_rename_parent(sql, %Q, %Q) "
71028               "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
71029       sqlite3DbFree(db, zWhere);
71030     }
71031   }
71032 #endif
71033
71034   /* Modify the sqlite_master table to use the new table name. */
71035   sqlite3NestedParse(pParse,
71036       "UPDATE %Q.%s SET "
71037 #ifdef SQLITE_OMIT_TRIGGER
71038           "sql = sqlite_rename_table(sql, %Q), "
71039 #else
71040           "sql = CASE "
71041             "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
71042             "ELSE sqlite_rename_table(sql, %Q) END, "
71043 #endif
71044           "tbl_name = %Q, "
71045           "name = CASE "
71046             "WHEN type='table' THEN %Q "
71047             "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
71048              "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
71049             "ELSE name END "
71050       "WHERE tbl_name=%Q AND "
71051           "(type='table' OR type='index' OR type='trigger');", 
71052       zDb, SCHEMA_TABLE(iDb), zName, zName, zName, 
71053 #ifndef SQLITE_OMIT_TRIGGER
71054       zName,
71055 #endif
71056       zName, nTabName, zTabName
71057   );
71058
71059 #ifndef SQLITE_OMIT_AUTOINCREMENT
71060   /* If the sqlite_sequence table exists in this database, then update 
71061   ** it with the new table name.
71062   */
71063   if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
71064     sqlite3NestedParse(pParse,
71065         "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
71066         zDb, zName, pTab->zName);
71067   }
71068 #endif
71069
71070 #ifndef SQLITE_OMIT_TRIGGER
71071   /* If there are TEMP triggers on this table, modify the sqlite_temp_master
71072   ** table. Don't do this if the table being ALTERed is itself located in
71073   ** the temp database.
71074   */
71075   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
71076     sqlite3NestedParse(pParse, 
71077         "UPDATE sqlite_temp_master SET "
71078             "sql = sqlite_rename_trigger(sql, %Q), "
71079             "tbl_name = %Q "
71080             "WHERE %s;", zName, zName, zWhere);
71081     sqlite3DbFree(db, zWhere);
71082   }
71083 #endif
71084
71085 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
71086   if( db->flags&SQLITE_ForeignKeys ){
71087     FKey *p;
71088     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
71089       Table *pFrom = p->pFrom;
71090       if( pFrom!=pTab ){
71091         reloadTableSchema(pParse, p->pFrom, pFrom->zName);
71092       }
71093     }
71094   }
71095 #endif
71096
71097   /* Drop and reload the internal table schema. */
71098   reloadTableSchema(pParse, pTab, zName);
71099
71100 exit_rename_table:
71101   sqlite3SrcListDelete(db, pSrc);
71102   sqlite3DbFree(db, zName);
71103   db->flags = savedDbFlags;
71104 }
71105
71106
71107 /*
71108 ** Generate code to make sure the file format number is at least minFormat.
71109 ** The generated code will increase the file format number if necessary.
71110 */
71111 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
71112   Vdbe *v;
71113   v = sqlite3GetVdbe(pParse);
71114   /* The VDBE should have been allocated before this routine is called.
71115   ** If that allocation failed, we would have quit before reaching this
71116   ** point */
71117   if( ALWAYS(v) ){
71118     int r1 = sqlite3GetTempReg(pParse);
71119     int r2 = sqlite3GetTempReg(pParse);
71120     int j1;
71121     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
71122     sqlite3VdbeUsesBtree(v, iDb);
71123     sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
71124     j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
71125     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
71126     sqlite3VdbeJumpHere(v, j1);
71127     sqlite3ReleaseTempReg(pParse, r1);
71128     sqlite3ReleaseTempReg(pParse, r2);
71129   }
71130 }
71131
71132 /*
71133 ** This function is called after an "ALTER TABLE ... ADD" statement
71134 ** has been parsed. Argument pColDef contains the text of the new
71135 ** column definition.
71136 **
71137 ** The Table structure pParse->pNewTable was extended to include
71138 ** the new column during parsing.
71139 */
71140 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
71141   Table *pNew;              /* Copy of pParse->pNewTable */
71142   Table *pTab;              /* Table being altered */
71143   int iDb;                  /* Database number */
71144   const char *zDb;          /* Database name */
71145   const char *zTab;         /* Table name */
71146   char *zCol;               /* Null-terminated column definition */
71147   Column *pCol;             /* The new column */
71148   Expr *pDflt;              /* Default value for the new column */
71149   sqlite3 *db;              /* The database connection; */
71150
71151   db = pParse->db;
71152   if( pParse->nErr || db->mallocFailed ) return;
71153   pNew = pParse->pNewTable;
71154   assert( pNew );
71155
71156   assert( sqlite3BtreeHoldsAllMutexes(db) );
71157   iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
71158   zDb = db->aDb[iDb].zName;
71159   zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
71160   pCol = &pNew->aCol[pNew->nCol-1];
71161   pDflt = pCol->pDflt;
71162   pTab = sqlite3FindTable(db, zTab, zDb);
71163   assert( pTab );
71164
71165 #ifndef SQLITE_OMIT_AUTHORIZATION
71166   /* Invoke the authorization callback. */
71167   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
71168     return;
71169   }
71170 #endif
71171
71172   /* If the default value for the new column was specified with a 
71173   ** literal NULL, then set pDflt to 0. This simplifies checking
71174   ** for an SQL NULL default below.
71175   */
71176   if( pDflt && pDflt->op==TK_NULL ){
71177     pDflt = 0;
71178   }
71179
71180   /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
71181   ** If there is a NOT NULL constraint, then the default value for the
71182   ** column must not be NULL.
71183   */
71184   if( pCol->isPrimKey ){
71185     sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
71186     return;
71187   }
71188   if( pNew->pIndex ){
71189     sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
71190     return;
71191   }
71192   if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
71193     sqlite3ErrorMsg(pParse, 
71194         "Cannot add a REFERENCES column with non-NULL default value");
71195     return;
71196   }
71197   if( pCol->notNull && !pDflt ){
71198     sqlite3ErrorMsg(pParse, 
71199         "Cannot add a NOT NULL column with default value NULL");
71200     return;
71201   }
71202
71203   /* Ensure the default expression is something that sqlite3ValueFromExpr()
71204   ** can handle (i.e. not CURRENT_TIME etc.)
71205   */
71206   if( pDflt ){
71207     sqlite3_value *pVal;
71208     if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
71209       db->mallocFailed = 1;
71210       return;
71211     }
71212     if( !pVal ){
71213       sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
71214       return;
71215     }
71216     sqlite3ValueFree(pVal);
71217   }
71218
71219   /* Modify the CREATE TABLE statement. */
71220   zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
71221   if( zCol ){
71222     char *zEnd = &zCol[pColDef->n-1];
71223     int savedDbFlags = db->flags;
71224     while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
71225       *zEnd-- = '\0';
71226     }
71227     db->flags |= SQLITE_PreferBuiltin;
71228     sqlite3NestedParse(pParse, 
71229         "UPDATE \"%w\".%s SET "
71230           "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
71231         "WHERE type = 'table' AND name = %Q", 
71232       zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
71233       zTab
71234     );
71235     sqlite3DbFree(db, zCol);
71236     db->flags = savedDbFlags;
71237   }
71238
71239   /* If the default value of the new column is NULL, then set the file
71240   ** format to 2. If the default value of the new column is not NULL,
71241   ** the file format becomes 3.
71242   */
71243   sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
71244
71245   /* Reload the schema of the modified table. */
71246   reloadTableSchema(pParse, pTab, pTab->zName);
71247 }
71248
71249 /*
71250 ** This function is called by the parser after the table-name in
71251 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument 
71252 ** pSrc is the full-name of the table being altered.
71253 **
71254 ** This routine makes a (partial) copy of the Table structure
71255 ** for the table being altered and sets Parse.pNewTable to point
71256 ** to it. Routines called by the parser as the column definition
71257 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to 
71258 ** the copy. The copy of the Table structure is deleted by tokenize.c 
71259 ** after parsing is finished.
71260 **
71261 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
71262 ** coding the "ALTER TABLE ... ADD" statement.
71263 */
71264 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
71265   Table *pNew;
71266   Table *pTab;
71267   Vdbe *v;
71268   int iDb;
71269   int i;
71270   int nAlloc;
71271   sqlite3 *db = pParse->db;
71272
71273   /* Look up the table being altered. */
71274   assert( pParse->pNewTable==0 );
71275   assert( sqlite3BtreeHoldsAllMutexes(db) );
71276   if( db->mallocFailed ) goto exit_begin_add_column;
71277   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
71278   if( !pTab ) goto exit_begin_add_column;
71279
71280 #ifndef SQLITE_OMIT_VIRTUALTABLE
71281   if( IsVirtual(pTab) ){
71282     sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
71283     goto exit_begin_add_column;
71284   }
71285 #endif
71286
71287   /* Make sure this is not an attempt to ALTER a view. */
71288   if( pTab->pSelect ){
71289     sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
71290     goto exit_begin_add_column;
71291   }
71292
71293   assert( pTab->addColOffset>0 );
71294   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
71295
71296   /* Put a copy of the Table struct in Parse.pNewTable for the
71297   ** sqlite3AddColumn() function and friends to modify.  But modify
71298   ** the name by adding an "sqlite_altertab_" prefix.  By adding this
71299   ** prefix, we insure that the name will not collide with an existing
71300   ** table because user table are not allowed to have the "sqlite_"
71301   ** prefix on their name.
71302   */
71303   pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
71304   if( !pNew ) goto exit_begin_add_column;
71305   pParse->pNewTable = pNew;
71306   pNew->nRef = 1;
71307   pNew->dbMem = pTab->dbMem;
71308   pNew->nCol = pTab->nCol;
71309   assert( pNew->nCol>0 );
71310   nAlloc = (((pNew->nCol-1)/8)*8)+8;
71311   assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
71312   pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
71313   pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
71314   if( !pNew->aCol || !pNew->zName ){
71315     db->mallocFailed = 1;
71316     goto exit_begin_add_column;
71317   }
71318   memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
71319   for(i=0; i<pNew->nCol; i++){
71320     Column *pCol = &pNew->aCol[i];
71321     pCol->zName = sqlite3DbStrDup(db, pCol->zName);
71322     pCol->zColl = 0;
71323     pCol->zType = 0;
71324     pCol->pDflt = 0;
71325     pCol->zDflt = 0;
71326   }
71327   pNew->pSchema = db->aDb[iDb].pSchema;
71328   pNew->addColOffset = pTab->addColOffset;
71329   pNew->nRef = 1;
71330
71331   /* Begin a transaction and increment the schema cookie.  */
71332   sqlite3BeginWriteOperation(pParse, 0, iDb);
71333   v = sqlite3GetVdbe(pParse);
71334   if( !v ) goto exit_begin_add_column;
71335   sqlite3ChangeCookie(pParse, iDb);
71336
71337 exit_begin_add_column:
71338   sqlite3SrcListDelete(db, pSrc);
71339   return;
71340 }
71341 #endif  /* SQLITE_ALTER_TABLE */
71342
71343 /************** End of alter.c ***********************************************/
71344 /************** Begin file analyze.c *****************************************/
71345 /*
71346 ** 2005 July 8
71347 **
71348 ** The author disclaims copyright to this source code.  In place of
71349 ** a legal notice, here is a blessing:
71350 **
71351 **    May you do good and not evil.
71352 **    May you find forgiveness for yourself and forgive others.
71353 **    May you share freely, never taking more than you give.
71354 **
71355 *************************************************************************
71356 ** This file contains code associated with the ANALYZE command.
71357 */
71358 #ifndef SQLITE_OMIT_ANALYZE
71359
71360 /*
71361 ** This routine generates code that opens the sqlite_stat1 table for
71362 ** writing with cursor iStatCur. If the library was built with the
71363 ** SQLITE_ENABLE_STAT2 macro defined, then the sqlite_stat2 table is
71364 ** opened for writing using cursor (iStatCur+1)
71365 **
71366 ** If the sqlite_stat1 tables does not previously exist, it is created.
71367 ** Similarly, if the sqlite_stat2 table does not exist and the library
71368 ** is compiled with SQLITE_ENABLE_STAT2 defined, it is created. 
71369 **
71370 ** Argument zWhere may be a pointer to a buffer containing a table name,
71371 ** or it may be a NULL pointer. If it is not NULL, then all entries in
71372 ** the sqlite_stat1 and (if applicable) sqlite_stat2 tables associated
71373 ** with the named table are deleted. If zWhere==0, then code is generated
71374 ** to delete all stat table entries.
71375 */
71376 static void openStatTable(
71377   Parse *pParse,          /* Parsing context */
71378   int iDb,                /* The database we are looking in */
71379   int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
71380   const char *zWhere      /* Delete entries associated with this table */
71381 ){
71382   static const struct {
71383     const char *zName;
71384     const char *zCols;
71385   } aTable[] = {
71386     { "sqlite_stat1", "tbl,idx,stat" },
71387 #ifdef SQLITE_ENABLE_STAT2
71388     { "sqlite_stat2", "tbl,idx,sampleno,sample" },
71389 #endif
71390   };
71391
71392   int aRoot[] = {0, 0};
71393   u8 aCreateTbl[] = {0, 0};
71394
71395   int i;
71396   sqlite3 *db = pParse->db;
71397   Db *pDb;
71398   Vdbe *v = sqlite3GetVdbe(pParse);
71399   if( v==0 ) return;
71400   assert( sqlite3BtreeHoldsAllMutexes(db) );
71401   assert( sqlite3VdbeDb(v)==db );
71402   pDb = &db->aDb[iDb];
71403
71404   for(i=0; i<ArraySize(aTable); i++){
71405     const char *zTab = aTable[i].zName;
71406     Table *pStat;
71407     if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
71408       /* The sqlite_stat[12] table does not exist. Create it. Note that a 
71409       ** side-effect of the CREATE TABLE statement is to leave the rootpage 
71410       ** of the new table in register pParse->regRoot. This is important 
71411       ** because the OpenWrite opcode below will be needing it. */
71412       sqlite3NestedParse(pParse,
71413           "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
71414       );
71415       aRoot[i] = pParse->regRoot;
71416       aCreateTbl[i] = 1;
71417     }else{
71418       /* The table already exists. If zWhere is not NULL, delete all entries 
71419       ** associated with the table zWhere. If zWhere is NULL, delete the
71420       ** entire contents of the table. */
71421       aRoot[i] = pStat->tnum;
71422       sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
71423       if( zWhere ){
71424         sqlite3NestedParse(pParse,
71425            "DELETE FROM %Q.%s WHERE tbl=%Q", pDb->zName, zTab, zWhere
71426         );
71427       }else{
71428         /* The sqlite_stat[12] table already exists.  Delete all rows. */
71429         sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
71430       }
71431     }
71432   }
71433
71434   /* Open the sqlite_stat[12] tables for writing. */
71435   for(i=0; i<ArraySize(aTable); i++){
71436     sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb);
71437     sqlite3VdbeChangeP4(v, -1, (char *)3, P4_INT32);
71438     sqlite3VdbeChangeP5(v, aCreateTbl[i]);
71439   }
71440 }
71441
71442 /*
71443 ** Generate code to do an analysis of all indices associated with
71444 ** a single table.
71445 */
71446 static void analyzeOneTable(
71447   Parse *pParse,   /* Parser context */
71448   Table *pTab,     /* Table whose indices are to be analyzed */
71449   int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
71450   int iMem         /* Available memory locations begin here */
71451 ){
71452   sqlite3 *db = pParse->db;    /* Database handle */
71453   Index *pIdx;                 /* An index to being analyzed */
71454   int iIdxCur;                 /* Cursor open on index being analyzed */
71455   Vdbe *v;                     /* The virtual machine being built up */
71456   int i;                       /* Loop counter */
71457   int topOfLoop;               /* The top of the loop */
71458   int endOfLoop;               /* The end of the loop */
71459   int addr;                    /* The address of an instruction */
71460   int iDb;                     /* Index of database containing pTab */
71461   int regTabname = iMem++;     /* Register containing table name */
71462   int regIdxname = iMem++;     /* Register containing index name */
71463   int regSampleno = iMem++;    /* Register containing next sample number */
71464   int regCol = iMem++;         /* Content of a column analyzed table */
71465   int regRec = iMem++;         /* Register holding completed record */
71466   int regTemp = iMem++;        /* Temporary use register */
71467   int regRowid = iMem++;       /* Rowid for the inserted record */
71468
71469 #ifdef SQLITE_ENABLE_STAT2
71470   int regTemp2 = iMem++;       /* Temporary use register */
71471   int regSamplerecno = iMem++; /* Index of next sample to record */
71472   int regRecno = iMem++;       /* Current sample index */
71473   int regLast = iMem++;        /* Index of last sample to record */
71474   int regFirst = iMem++;       /* Index of first sample to record */
71475 #endif
71476
71477   v = sqlite3GetVdbe(pParse);
71478   if( v==0 || NEVER(pTab==0) || pTab->pIndex==0 ){
71479     /* Do no analysis for tables that have no indices */
71480     return;
71481   }
71482   assert( sqlite3BtreeHoldsAllMutexes(db) );
71483   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
71484   assert( iDb>=0 );
71485 #ifndef SQLITE_OMIT_AUTHORIZATION
71486   if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
71487       db->aDb[iDb].zName ) ){
71488     return;
71489   }
71490 #endif
71491
71492   /* Establish a read-lock on the table at the shared-cache level. */
71493   sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
71494
71495   iIdxCur = pParse->nTab++;
71496   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
71497     int nCol = pIdx->nColumn;
71498     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
71499
71500     if( iMem+1+(nCol*2)>pParse->nMem ){
71501       pParse->nMem = iMem+1+(nCol*2);
71502     }
71503
71504     /* Open a cursor to the index to be analyzed. */
71505     assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
71506     sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
71507         (char *)pKey, P4_KEYINFO_HANDOFF);
71508     VdbeComment((v, "%s", pIdx->zName));
71509
71510     /* Populate the registers containing the table and index names. */
71511     if( pTab->pIndex==pIdx ){
71512       sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
71513     }
71514     sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
71515
71516 #ifdef SQLITE_ENABLE_STAT2
71517
71518     /* If this iteration of the loop is generating code to analyze the
71519     ** first index in the pTab->pIndex list, then register regLast has
71520     ** not been populated. In this case populate it now.  */
71521     if( pTab->pIndex==pIdx ){
71522       sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES, regSamplerecno);
71523       sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES*2-1, regTemp);
71524       sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES*2, regTemp2);
71525
71526       sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regLast);
71527       sqlite3VdbeAddOp2(v, OP_Null, 0, regFirst);
71528       addr = sqlite3VdbeAddOp3(v, OP_Lt, regSamplerecno, 0, regLast);
71529       sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regLast, regFirst);
71530       sqlite3VdbeAddOp3(v, OP_Multiply, regLast, regTemp, regLast);
71531       sqlite3VdbeAddOp2(v, OP_AddImm, regLast, SQLITE_INDEX_SAMPLES*2-2);
71532       sqlite3VdbeAddOp3(v, OP_Divide,  regTemp2, regLast, regLast);
71533       sqlite3VdbeJumpHere(v, addr);
71534     }
71535
71536     /* Zero the regSampleno and regRecno registers. */
71537     sqlite3VdbeAddOp2(v, OP_Integer, 0, regSampleno);
71538     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRecno);
71539     sqlite3VdbeAddOp2(v, OP_Copy, regFirst, regSamplerecno);
71540 #endif
71541
71542     /* The block of memory cells initialized here is used as follows.
71543     **
71544     **    iMem:                
71545     **        The total number of rows in the table.
71546     **
71547     **    iMem+1 .. iMem+nCol: 
71548     **        Number of distinct entries in index considering the 
71549     **        left-most N columns only, where N is between 1 and nCol, 
71550     **        inclusive.
71551     **
71552     **    iMem+nCol+1 .. Mem+2*nCol:  
71553     **        Previous value of indexed columns, from left to right.
71554     **
71555     ** Cells iMem through iMem+nCol are initialized to 0. The others are 
71556     ** initialized to contain an SQL NULL.
71557     */
71558     for(i=0; i<=nCol; i++){
71559       sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
71560     }
71561     for(i=0; i<nCol; i++){
71562       sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
71563     }
71564
71565     /* Start the analysis loop. This loop runs through all the entries in
71566     ** the index b-tree.  */
71567     endOfLoop = sqlite3VdbeMakeLabel(v);
71568     sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
71569     topOfLoop = sqlite3VdbeCurrentAddr(v);
71570     sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1);
71571
71572     for(i=0; i<nCol; i++){
71573       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
71574 #ifdef SQLITE_ENABLE_STAT2
71575       if( i==0 ){
71576         /* Check if the record that cursor iIdxCur points to contains a
71577         ** value that should be stored in the sqlite_stat2 table. If so,
71578         ** store it.  */
71579         int ne = sqlite3VdbeAddOp3(v, OP_Ne, regRecno, 0, regSamplerecno);
71580         assert( regTabname+1==regIdxname 
71581              && regTabname+2==regSampleno
71582              && regTabname+3==regCol
71583         );
71584         sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
71585         sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 4, regRec, "aaab", 0);
71586         sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regRowid);
71587         sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regRec, regRowid);
71588
71589         /* Calculate new values for regSamplerecno and regSampleno.
71590         **
71591         **   sampleno = sampleno + 1
71592         **   samplerecno = samplerecno+(remaining records)/(remaining samples)
71593         */
71594         sqlite3VdbeAddOp2(v, OP_AddImm, regSampleno, 1);
71595         sqlite3VdbeAddOp3(v, OP_Subtract, regRecno, regLast, regTemp);
71596         sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
71597         sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES, regTemp2);
71598         sqlite3VdbeAddOp3(v, OP_Subtract, regSampleno, regTemp2, regTemp2);
71599         sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regTemp, regTemp);
71600         sqlite3VdbeAddOp3(v, OP_Add, regSamplerecno, regTemp, regSamplerecno);
71601
71602         sqlite3VdbeJumpHere(v, ne);
71603         sqlite3VdbeAddOp2(v, OP_AddImm, regRecno, 1);
71604       }
71605 #endif
71606
71607       sqlite3VdbeAddOp3(v, OP_Ne, regCol, 0, iMem+nCol+i+1);
71608       /**** TODO:  add collating sequence *****/
71609       sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
71610     }
71611     if( db->mallocFailed ){
71612       /* If a malloc failure has occurred, then the result of the expression 
71613       ** passed as the second argument to the call to sqlite3VdbeJumpHere() 
71614       ** below may be negative. Which causes an assert() to fail (or an
71615       ** out-of-bounds write if SQLITE_DEBUG is not defined).  */
71616       return;
71617     }
71618     sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
71619     for(i=0; i<nCol; i++){
71620       sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-(nCol*2));
71621       sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
71622       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
71623     }
71624
71625     /* End of the analysis loop. */
71626     sqlite3VdbeResolveLabel(v, endOfLoop);
71627     sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
71628     sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
71629
71630     /* Store the results in sqlite_stat1.
71631     **
71632     ** The result is a single row of the sqlite_stat1 table.  The first
71633     ** two columns are the names of the table and index.  The third column
71634     ** is a string composed of a list of integer statistics about the
71635     ** index.  The first integer in the list is the total number of entries
71636     ** in the index.  There is one additional integer in the list for each
71637     ** column of the table.  This additional integer is a guess of how many
71638     ** rows of the table the index will select.  If D is the count of distinct
71639     ** values and K is the total number of rows, then the integer is computed
71640     ** as:
71641     **
71642     **        I = (K+D-1)/D
71643     **
71644     ** If K==0 then no entry is made into the sqlite_stat1 table.  
71645     ** If K>0 then it is always the case the D>0 so division by zero
71646     ** is never possible.
71647     */
71648     addr = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
71649     sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regSampleno);
71650     for(i=0; i<nCol; i++){
71651       sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
71652       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
71653       sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
71654       sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
71655       sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
71656       sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
71657       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
71658     }
71659     sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
71660     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
71661     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
71662     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
71663     sqlite3VdbeJumpHere(v, addr);
71664   }
71665 }
71666
71667 /*
71668 ** Generate code that will cause the most recent index analysis to
71669 ** be laoded into internal hash tables where is can be used.
71670 */
71671 static void loadAnalysis(Parse *pParse, int iDb){
71672   Vdbe *v = sqlite3GetVdbe(pParse);
71673   if( v ){
71674     sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
71675   }
71676 }
71677
71678 /*
71679 ** Generate code that will do an analysis of an entire database
71680 */
71681 static void analyzeDatabase(Parse *pParse, int iDb){
71682   sqlite3 *db = pParse->db;
71683   Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
71684   HashElem *k;
71685   int iStatCur;
71686   int iMem;
71687
71688   sqlite3BeginWriteOperation(pParse, 0, iDb);
71689   iStatCur = pParse->nTab;
71690   pParse->nTab += 2;
71691   openStatTable(pParse, iDb, iStatCur, 0);
71692   iMem = pParse->nMem+1;
71693   for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
71694     Table *pTab = (Table*)sqliteHashData(k);
71695     analyzeOneTable(pParse, pTab, iStatCur, iMem);
71696   }
71697   loadAnalysis(pParse, iDb);
71698 }
71699
71700 /*
71701 ** Generate code that will do an analysis of a single table in
71702 ** a database.
71703 */
71704 static void analyzeTable(Parse *pParse, Table *pTab){
71705   int iDb;
71706   int iStatCur;
71707
71708   assert( pTab!=0 );
71709   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
71710   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
71711   sqlite3BeginWriteOperation(pParse, 0, iDb);
71712   iStatCur = pParse->nTab;
71713   pParse->nTab += 2;
71714   openStatTable(pParse, iDb, iStatCur, pTab->zName);
71715   analyzeOneTable(pParse, pTab, iStatCur, pParse->nMem+1);
71716   loadAnalysis(pParse, iDb);
71717 }
71718
71719 /*
71720 ** Generate code for the ANALYZE command.  The parser calls this routine
71721 ** when it recognizes an ANALYZE command.
71722 **
71723 **        ANALYZE                            -- 1
71724 **        ANALYZE  <database>                -- 2
71725 **        ANALYZE  ?<database>.?<tablename>  -- 3
71726 **
71727 ** Form 1 causes all indices in all attached databases to be analyzed.
71728 ** Form 2 analyzes all indices the single database named.
71729 ** Form 3 analyzes all indices associated with the named table.
71730 */
71731 SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
71732   sqlite3 *db = pParse->db;
71733   int iDb;
71734   int i;
71735   char *z, *zDb;
71736   Table *pTab;
71737   Token *pTableName;
71738
71739   /* Read the database schema. If an error occurs, leave an error message
71740   ** and code in pParse and return NULL. */
71741   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
71742   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
71743     return;
71744   }
71745
71746   assert( pName2!=0 || pName1==0 );
71747   if( pName1==0 ){
71748     /* Form 1:  Analyze everything */
71749     for(i=0; i<db->nDb; i++){
71750       if( i==1 ) continue;  /* Do not analyze the TEMP database */
71751       analyzeDatabase(pParse, i);
71752     }
71753   }else if( pName2->n==0 ){
71754     /* Form 2:  Analyze the database or table named */
71755     iDb = sqlite3FindDb(db, pName1);
71756     if( iDb>=0 ){
71757       analyzeDatabase(pParse, iDb);
71758     }else{
71759       z = sqlite3NameFromToken(db, pName1);
71760       if( z ){
71761         pTab = sqlite3LocateTable(pParse, 0, z, 0);
71762         sqlite3DbFree(db, z);
71763         if( pTab ){
71764           analyzeTable(pParse, pTab);
71765         }
71766       }
71767     }
71768   }else{
71769     /* Form 3: Analyze the fully qualified table name */
71770     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
71771     if( iDb>=0 ){
71772       zDb = db->aDb[iDb].zName;
71773       z = sqlite3NameFromToken(db, pTableName);
71774       if( z ){
71775         pTab = sqlite3LocateTable(pParse, 0, z, zDb);
71776         sqlite3DbFree(db, z);
71777         if( pTab ){
71778           analyzeTable(pParse, pTab);
71779         }
71780       }
71781     }   
71782   }
71783 }
71784
71785 /*
71786 ** Used to pass information from the analyzer reader through to the
71787 ** callback routine.
71788 */
71789 typedef struct analysisInfo analysisInfo;
71790 struct analysisInfo {
71791   sqlite3 *db;
71792   const char *zDatabase;
71793 };
71794
71795 /*
71796 ** This callback is invoked once for each index when reading the
71797 ** sqlite_stat1 table.  
71798 **
71799 **     argv[0] = name of the index
71800 **     argv[1] = results of analysis - on integer for each column
71801 */
71802 static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
71803   analysisInfo *pInfo = (analysisInfo*)pData;
71804   Index *pIndex;
71805   int i, c;
71806   unsigned int v;
71807   const char *z;
71808
71809   assert( argc==2 );
71810   UNUSED_PARAMETER2(NotUsed, argc);
71811
71812   if( argv==0 || argv[0]==0 || argv[1]==0 ){
71813     return 0;
71814   }
71815   pIndex = sqlite3FindIndex(pInfo->db, argv[0], pInfo->zDatabase);
71816   if( pIndex==0 ){
71817     return 0;
71818   }
71819   z = argv[1];
71820   for(i=0; *z && i<=pIndex->nColumn; i++){
71821     v = 0;
71822     while( (c=z[0])>='0' && c<='9' ){
71823       v = v*10 + c - '0';
71824       z++;
71825     }
71826     pIndex->aiRowEst[i] = v;
71827     if( *z==' ' ) z++;
71828   }
71829   return 0;
71830 }
71831
71832 /*
71833 ** If the Index.aSample variable is not NULL, delete the aSample[] array
71834 ** and its contents.
71835 */
71836 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(Index *pIdx){
71837 #ifdef SQLITE_ENABLE_STAT2
71838   if( pIdx->aSample ){
71839     int j;
71840     sqlite3 *dbMem = pIdx->pTable->dbMem;
71841     for(j=0; j<SQLITE_INDEX_SAMPLES; j++){
71842       IndexSample *p = &pIdx->aSample[j];
71843       if( p->eType==SQLITE_TEXT || p->eType==SQLITE_BLOB ){
71844         sqlite3DbFree(pIdx->pTable->dbMem, p->u.z);
71845       }
71846     }
71847     sqlite3DbFree(dbMem, pIdx->aSample);
71848     pIdx->aSample = 0;
71849   }
71850 #else
71851   UNUSED_PARAMETER(pIdx);
71852 #endif
71853 }
71854
71855 /*
71856 ** Load the content of the sqlite_stat1 and sqlite_stat2 tables. The
71857 ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
71858 ** arrays. The contents of sqlite_stat2 are used to populate the
71859 ** Index.aSample[] arrays.
71860 **
71861 ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
71862 ** is returned. In this case, even if SQLITE_ENABLE_STAT2 was defined 
71863 ** during compilation and the sqlite_stat2 table is present, no data is 
71864 ** read from it.
71865 **
71866 ** If SQLITE_ENABLE_STAT2 was defined during compilation and the 
71867 ** sqlite_stat2 table is not present in the database, SQLITE_ERROR is
71868 ** returned. However, in this case, data is read from the sqlite_stat1
71869 ** table (if it is present) before returning.
71870 **
71871 ** If an OOM error occurs, this function always sets db->mallocFailed.
71872 ** This means if the caller does not care about other errors, the return
71873 ** code may be ignored.
71874 */
71875 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
71876   analysisInfo sInfo;
71877   HashElem *i;
71878   char *zSql;
71879   int rc;
71880
71881   assert( iDb>=0 && iDb<db->nDb );
71882   assert( db->aDb[iDb].pBt!=0 );
71883   assert( sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
71884
71885   /* Clear any prior statistics */
71886   for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
71887     Index *pIdx = sqliteHashData(i);
71888     sqlite3DefaultRowEst(pIdx);
71889     sqlite3DeleteIndexSamples(pIdx);
71890   }
71891
71892   /* Check to make sure the sqlite_stat1 table exists */
71893   sInfo.db = db;
71894   sInfo.zDatabase = db->aDb[iDb].zName;
71895   if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
71896     return SQLITE_ERROR;
71897   }
71898
71899   /* Load new statistics out of the sqlite_stat1 table */
71900   zSql = sqlite3MPrintf(db, 
71901       "SELECT idx, stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
71902   if( zSql==0 ){
71903     rc = SQLITE_NOMEM;
71904   }else{
71905     rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
71906     sqlite3DbFree(db, zSql);
71907   }
71908
71909
71910   /* Load the statistics from the sqlite_stat2 table. */
71911 #ifdef SQLITE_ENABLE_STAT2
71912   if( rc==SQLITE_OK && !sqlite3FindTable(db, "sqlite_stat2", sInfo.zDatabase) ){
71913     rc = SQLITE_ERROR;
71914   }
71915   if( rc==SQLITE_OK ){
71916     sqlite3_stmt *pStmt = 0;
71917
71918     zSql = sqlite3MPrintf(db, 
71919         "SELECT idx,sampleno,sample FROM %Q.sqlite_stat2", sInfo.zDatabase);
71920     if( !zSql ){
71921       rc = SQLITE_NOMEM;
71922     }else{
71923       rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
71924       sqlite3DbFree(db, zSql);
71925     }
71926
71927     if( rc==SQLITE_OK ){
71928       while( sqlite3_step(pStmt)==SQLITE_ROW ){
71929         char *zIndex = (char *)sqlite3_column_text(pStmt, 0);
71930         Index *pIdx = sqlite3FindIndex(db, zIndex, sInfo.zDatabase);
71931         if( pIdx ){
71932           int iSample = sqlite3_column_int(pStmt, 1);
71933           sqlite3 *dbMem = pIdx->pTable->dbMem;
71934           assert( dbMem==db || dbMem==0 );
71935           if( iSample<SQLITE_INDEX_SAMPLES && iSample>=0 ){
71936             int eType = sqlite3_column_type(pStmt, 2);
71937
71938             if( pIdx->aSample==0 ){
71939               static const int sz = sizeof(IndexSample)*SQLITE_INDEX_SAMPLES;
71940               pIdx->aSample = (IndexSample *)sqlite3DbMallocZero(dbMem, sz);
71941               if( pIdx->aSample==0 ){
71942                 db->mallocFailed = 1;
71943                 break;
71944               }
71945             }
71946
71947             assert( pIdx->aSample );
71948             {
71949               IndexSample *pSample = &pIdx->aSample[iSample];
71950               pSample->eType = (u8)eType;
71951               if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
71952                 pSample->u.r = sqlite3_column_double(pStmt, 2);
71953               }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
71954                 const char *z = (const char *)(
71955                     (eType==SQLITE_BLOB) ?
71956                     sqlite3_column_blob(pStmt, 2):
71957                     sqlite3_column_text(pStmt, 2)
71958                 );
71959                 int n = sqlite3_column_bytes(pStmt, 2);
71960                 if( n>24 ){
71961                   n = 24;
71962                 }
71963                 pSample->nByte = (u8)n;
71964                 if( n < 1){
71965                   pSample->u.z = 0;
71966                 }else{
71967                   pSample->u.z = sqlite3DbMallocRaw(dbMem, n);
71968                   if( pSample->u.z ){
71969                     memcpy(pSample->u.z, z, n);
71970                   }else{
71971                     db->mallocFailed = 1;
71972                     break;
71973                   }
71974                 }
71975               }
71976             }
71977           }
71978         }
71979       }
71980       rc = sqlite3_finalize(pStmt);
71981     }
71982   }
71983 #endif
71984
71985   if( rc==SQLITE_NOMEM ){
71986     db->mallocFailed = 1;
71987   }
71988   return rc;
71989 }
71990
71991
71992 #endif /* SQLITE_OMIT_ANALYZE */
71993
71994 /************** End of analyze.c *********************************************/
71995 /************** Begin file attach.c ******************************************/
71996 /*
71997 ** 2003 April 6
71998 **
71999 ** The author disclaims copyright to this source code.  In place of
72000 ** a legal notice, here is a blessing:
72001 **
72002 **    May you do good and not evil.
72003 **    May you find forgiveness for yourself and forgive others.
72004 **    May you share freely, never taking more than you give.
72005 **
72006 *************************************************************************
72007 ** This file contains code used to implement the ATTACH and DETACH commands.
72008 */
72009
72010 #ifndef SQLITE_OMIT_ATTACH
72011 /*
72012 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
72013 ** is slightly different from resolving a normal SQL expression, because simple
72014 ** identifiers are treated as strings, not possible column names or aliases.
72015 **
72016 ** i.e. if the parser sees:
72017 **
72018 **     ATTACH DATABASE abc AS def
72019 **
72020 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
72021 ** looking for columns of the same name.
72022 **
72023 ** This only applies to the root node of pExpr, so the statement:
72024 **
72025 **     ATTACH DATABASE abc||def AS 'db2'
72026 **
72027 ** will fail because neither abc or def can be resolved.
72028 */
72029 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
72030 {
72031   int rc = SQLITE_OK;
72032   if( pExpr ){
72033     if( pExpr->op!=TK_ID ){
72034       rc = sqlite3ResolveExprNames(pName, pExpr);
72035       if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
72036         sqlite3ErrorMsg(pName->pParse, "invalid name: \"%s\"", pExpr->u.zToken);
72037         return SQLITE_ERROR;
72038       }
72039     }else{
72040       pExpr->op = TK_STRING;
72041     }
72042   }
72043   return rc;
72044 }
72045
72046 /*
72047 ** An SQL user-function registered to do the work of an ATTACH statement. The
72048 ** three arguments to the function come directly from an attach statement:
72049 **
72050 **     ATTACH DATABASE x AS y KEY z
72051 **
72052 **     SELECT sqlite_attach(x, y, z)
72053 **
72054 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
72055 ** third argument.
72056 */
72057 static void attachFunc(
72058   sqlite3_context *context,
72059   int NotUsed,
72060   sqlite3_value **argv
72061 ){
72062   int i;
72063   int rc = 0;
72064   sqlite3 *db = sqlite3_context_db_handle(context);
72065   const char *zName;
72066   const char *zFile;
72067   Db *aNew;
72068   char *zErrDyn = 0;
72069
72070   UNUSED_PARAMETER(NotUsed);
72071
72072   zFile = (const char *)sqlite3_value_text(argv[0]);
72073   zName = (const char *)sqlite3_value_text(argv[1]);
72074   if( zFile==0 ) zFile = "";
72075   if( zName==0 ) zName = "";
72076
72077   /* Check for the following errors:
72078   **
72079   **     * Too many attached databases,
72080   **     * Transaction currently open
72081   **     * Specified database name already being used.
72082   */
72083   if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
72084     zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d", 
72085       db->aLimit[SQLITE_LIMIT_ATTACHED]
72086     );
72087     goto attach_error;
72088   }
72089   if( !db->autoCommit ){
72090     zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
72091     goto attach_error;
72092   }
72093   for(i=0; i<db->nDb; i++){
72094     char *z = db->aDb[i].zName;
72095     assert( z && zName );
72096     if( sqlite3StrICmp(z, zName)==0 ){
72097       zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
72098       goto attach_error;
72099     }
72100   }
72101
72102   /* Allocate the new entry in the db->aDb[] array and initialise the schema
72103   ** hash tables.
72104   */
72105   if( db->aDb==db->aDbStatic ){
72106     aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
72107     if( aNew==0 ) return;
72108     memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
72109   }else{
72110     aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
72111     if( aNew==0 ) return;
72112   }
72113   db->aDb = aNew;
72114   aNew = &db->aDb[db->nDb];
72115   memset(aNew, 0, sizeof(*aNew));
72116
72117   /* Open the database file. If the btree is successfully opened, use
72118   ** it to obtain the database schema. At this point the schema may
72119   ** or may not be initialised.
72120   */
72121   rc = sqlite3BtreeFactory(db, zFile, 0, SQLITE_DEFAULT_CACHE_SIZE,
72122                            db->openFlags | SQLITE_OPEN_MAIN_DB,
72123                            &aNew->pBt);
72124   db->nDb++;
72125   if( rc==SQLITE_CONSTRAINT ){
72126     rc = SQLITE_ERROR;
72127     zErrDyn = sqlite3MPrintf(db, "database is already attached");
72128   }else if( rc==SQLITE_OK ){
72129     Pager *pPager;
72130     aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
72131     if( !aNew->pSchema ){
72132       rc = SQLITE_NOMEM;
72133     }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
72134       zErrDyn = sqlite3MPrintf(db, 
72135         "attached databases must use the same text encoding as main database");
72136       rc = SQLITE_ERROR;
72137     }
72138     pPager = sqlite3BtreePager(aNew->pBt);
72139     sqlite3PagerLockingMode(pPager, db->dfltLockMode);
72140     sqlite3BtreeSecureDelete(aNew->pBt,
72141                              sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
72142   }
72143   aNew->safety_level = 3;
72144   aNew->zName = sqlite3DbStrDup(db, zName);
72145   if( rc==SQLITE_OK && aNew->zName==0 ){
72146     rc = SQLITE_NOMEM;
72147   }
72148
72149
72150 #ifdef SQLITE_HAS_CODEC
72151   if( rc==SQLITE_OK ){
72152     extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
72153     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
72154     int nKey;
72155     char *zKey;
72156     int t = sqlite3_value_type(argv[2]);
72157     switch( t ){
72158       case SQLITE_INTEGER:
72159       case SQLITE_FLOAT:
72160         zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
72161         rc = SQLITE_ERROR;
72162         break;
72163         
72164       case SQLITE_TEXT:
72165       case SQLITE_BLOB:
72166         nKey = sqlite3_value_bytes(argv[2]);
72167         zKey = (char *)sqlite3_value_blob(argv[2]);
72168         rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
72169         break;
72170
72171       case SQLITE_NULL:
72172         /* No key specified.  Use the key from the main database */
72173         sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
72174         rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
72175         break;
72176     }
72177   }
72178 #endif
72179
72180   /* If the file was opened successfully, read the schema for the new database.
72181   ** If this fails, or if opening the file failed, then close the file and 
72182   ** remove the entry from the db->aDb[] array. i.e. put everything back the way
72183   ** we found it.
72184   */
72185   if( rc==SQLITE_OK ){
72186     sqlite3BtreeEnterAll(db);
72187     rc = sqlite3Init(db, &zErrDyn);
72188     sqlite3BtreeLeaveAll(db);
72189   }
72190   if( rc ){
72191     int iDb = db->nDb - 1;
72192     assert( iDb>=2 );
72193     if( db->aDb[iDb].pBt ){
72194       sqlite3BtreeClose(db->aDb[iDb].pBt);
72195       db->aDb[iDb].pBt = 0;
72196       db->aDb[iDb].pSchema = 0;
72197     }
72198     sqlite3ResetInternalSchema(db, 0);
72199     db->nDb = iDb;
72200     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
72201       db->mallocFailed = 1;
72202       sqlite3DbFree(db, zErrDyn);
72203       zErrDyn = sqlite3MPrintf(db, "out of memory");
72204     }else if( zErrDyn==0 ){
72205       zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
72206     }
72207     goto attach_error;
72208   }
72209   
72210   return;
72211
72212 attach_error:
72213   /* Return an error if we get here */
72214   if( zErrDyn ){
72215     sqlite3_result_error(context, zErrDyn, -1);
72216     sqlite3DbFree(db, zErrDyn);
72217   }
72218   if( rc ) sqlite3_result_error_code(context, rc);
72219 }
72220
72221 /*
72222 ** An SQL user-function registered to do the work of an DETACH statement. The
72223 ** three arguments to the function come directly from a detach statement:
72224 **
72225 **     DETACH DATABASE x
72226 **
72227 **     SELECT sqlite_detach(x)
72228 */
72229 static void detachFunc(
72230   sqlite3_context *context,
72231   int NotUsed,
72232   sqlite3_value **argv
72233 ){
72234   const char *zName = (const char *)sqlite3_value_text(argv[0]);
72235   sqlite3 *db = sqlite3_context_db_handle(context);
72236   int i;
72237   Db *pDb = 0;
72238   char zErr[128];
72239
72240   UNUSED_PARAMETER(NotUsed);
72241
72242   if( zName==0 ) zName = "";
72243   for(i=0; i<db->nDb; i++){
72244     pDb = &db->aDb[i];
72245     if( pDb->pBt==0 ) continue;
72246     if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
72247   }
72248
72249   if( i>=db->nDb ){
72250     sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
72251     goto detach_error;
72252   }
72253   if( i<2 ){
72254     sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
72255     goto detach_error;
72256   }
72257   if( !db->autoCommit ){
72258     sqlite3_snprintf(sizeof(zErr), zErr,
72259                      "cannot DETACH database within transaction");
72260     goto detach_error;
72261   }
72262   if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
72263     sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
72264     goto detach_error;
72265   }
72266
72267   sqlite3BtreeClose(pDb->pBt);
72268   pDb->pBt = 0;
72269   pDb->pSchema = 0;
72270   sqlite3ResetInternalSchema(db, 0);
72271   return;
72272
72273 detach_error:
72274   sqlite3_result_error(context, zErr, -1);
72275 }
72276
72277 /*
72278 ** This procedure generates VDBE code for a single invocation of either the
72279 ** sqlite_detach() or sqlite_attach() SQL user functions.
72280 */
72281 static void codeAttach(
72282   Parse *pParse,       /* The parser context */
72283   int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
72284   FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
72285   Expr *pAuthArg,      /* Expression to pass to authorization callback */
72286   Expr *pFilename,     /* Name of database file */
72287   Expr *pDbname,       /* Name of the database to use internally */
72288   Expr *pKey           /* Database key for encryption extension */
72289 ){
72290   int rc;
72291   NameContext sName;
72292   Vdbe *v;
72293   sqlite3* db = pParse->db;
72294   int regArgs;
72295
72296   memset(&sName, 0, sizeof(NameContext));
72297   sName.pParse = pParse;
72298
72299   if( 
72300       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
72301       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
72302       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
72303   ){
72304     pParse->nErr++;
72305     goto attach_end;
72306   }
72307
72308 #ifndef SQLITE_OMIT_AUTHORIZATION
72309   if( pAuthArg ){
72310     char *zAuthArg = pAuthArg->u.zToken;
72311     if( NEVER(zAuthArg==0) ){
72312       goto attach_end;
72313     }
72314     rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
72315     if(rc!=SQLITE_OK ){
72316       goto attach_end;
72317     }
72318   }
72319 #endif /* SQLITE_OMIT_AUTHORIZATION */
72320
72321
72322   v = sqlite3GetVdbe(pParse);
72323   regArgs = sqlite3GetTempRange(pParse, 4);
72324   sqlite3ExprCode(pParse, pFilename, regArgs);
72325   sqlite3ExprCode(pParse, pDbname, regArgs+1);
72326   sqlite3ExprCode(pParse, pKey, regArgs+2);
72327
72328   assert( v || db->mallocFailed );
72329   if( v ){
72330     sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
72331     assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
72332     sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
72333     sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
72334
72335     /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
72336     ** statement only). For DETACH, set it to false (expire all existing
72337     ** statements).
72338     */
72339     sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
72340   }
72341   
72342 attach_end:
72343   sqlite3ExprDelete(db, pFilename);
72344   sqlite3ExprDelete(db, pDbname);
72345   sqlite3ExprDelete(db, pKey);
72346 }
72347
72348 /*
72349 ** Called by the parser to compile a DETACH statement.
72350 **
72351 **     DETACH pDbname
72352 */
72353 SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
72354   static const FuncDef detach_func = {
72355     1,                /* nArg */
72356     SQLITE_UTF8,      /* iPrefEnc */
72357     0,                /* flags */
72358     0,                /* pUserData */
72359     0,                /* pNext */
72360     detachFunc,       /* xFunc */
72361     0,                /* xStep */
72362     0,                /* xFinalize */
72363     "sqlite_detach",  /* zName */
72364     0                 /* pHash */
72365   };
72366   codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
72367 }
72368
72369 /*
72370 ** Called by the parser to compile an ATTACH statement.
72371 **
72372 **     ATTACH p AS pDbname KEY pKey
72373 */
72374 SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
72375   static const FuncDef attach_func = {
72376     3,                /* nArg */
72377     SQLITE_UTF8,      /* iPrefEnc */
72378     0,                /* flags */
72379     0,                /* pUserData */
72380     0,                /* pNext */
72381     attachFunc,       /* xFunc */
72382     0,                /* xStep */
72383     0,                /* xFinalize */
72384     "sqlite_attach",  /* zName */
72385     0                 /* pHash */
72386   };
72387   codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
72388 }
72389 #endif /* SQLITE_OMIT_ATTACH */
72390
72391 /*
72392 ** Initialize a DbFixer structure.  This routine must be called prior
72393 ** to passing the structure to one of the sqliteFixAAAA() routines below.
72394 **
72395 ** The return value indicates whether or not fixation is required.  TRUE
72396 ** means we do need to fix the database references, FALSE means we do not.
72397 */
72398 SQLITE_PRIVATE int sqlite3FixInit(
72399   DbFixer *pFix,      /* The fixer to be initialized */
72400   Parse *pParse,      /* Error messages will be written here */
72401   int iDb,            /* This is the database that must be used */
72402   const char *zType,  /* "view", "trigger", or "index" */
72403   const Token *pName  /* Name of the view, trigger, or index */
72404 ){
72405   sqlite3 *db;
72406
72407   if( NEVER(iDb<0) || iDb==1 ) return 0;
72408   db = pParse->db;
72409   assert( db->nDb>iDb );
72410   pFix->pParse = pParse;
72411   pFix->zDb = db->aDb[iDb].zName;
72412   pFix->zType = zType;
72413   pFix->pName = pName;
72414   return 1;
72415 }
72416
72417 /*
72418 ** The following set of routines walk through the parse tree and assign
72419 ** a specific database to all table references where the database name
72420 ** was left unspecified in the original SQL statement.  The pFix structure
72421 ** must have been initialized by a prior call to sqlite3FixInit().
72422 **
72423 ** These routines are used to make sure that an index, trigger, or
72424 ** view in one database does not refer to objects in a different database.
72425 ** (Exception: indices, triggers, and views in the TEMP database are
72426 ** allowed to refer to anything.)  If a reference is explicitly made
72427 ** to an object in a different database, an error message is added to
72428 ** pParse->zErrMsg and these routines return non-zero.  If everything
72429 ** checks out, these routines return 0.
72430 */
72431 SQLITE_PRIVATE int sqlite3FixSrcList(
72432   DbFixer *pFix,       /* Context of the fixation */
72433   SrcList *pList       /* The Source list to check and modify */
72434 ){
72435   int i;
72436   const char *zDb;
72437   struct SrcList_item *pItem;
72438
72439   if( NEVER(pList==0) ) return 0;
72440   zDb = pFix->zDb;
72441   for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
72442     if( pItem->zDatabase==0 ){
72443       pItem->zDatabase = sqlite3DbStrDup(pFix->pParse->db, zDb);
72444     }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
72445       sqlite3ErrorMsg(pFix->pParse,
72446          "%s %T cannot reference objects in database %s",
72447          pFix->zType, pFix->pName, pItem->zDatabase);
72448       return 1;
72449     }
72450 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
72451     if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
72452     if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
72453 #endif
72454   }
72455   return 0;
72456 }
72457 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
72458 SQLITE_PRIVATE int sqlite3FixSelect(
72459   DbFixer *pFix,       /* Context of the fixation */
72460   Select *pSelect      /* The SELECT statement to be fixed to one database */
72461 ){
72462   while( pSelect ){
72463     if( sqlite3FixExprList(pFix, pSelect->pEList) ){
72464       return 1;
72465     }
72466     if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
72467       return 1;
72468     }
72469     if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
72470       return 1;
72471     }
72472     if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
72473       return 1;
72474     }
72475     pSelect = pSelect->pPrior;
72476   }
72477   return 0;
72478 }
72479 SQLITE_PRIVATE int sqlite3FixExpr(
72480   DbFixer *pFix,     /* Context of the fixation */
72481   Expr *pExpr        /* The expression to be fixed to one database */
72482 ){
72483   while( pExpr ){
72484     if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ) break;
72485     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
72486       if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
72487     }else{
72488       if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
72489     }
72490     if( sqlite3FixExpr(pFix, pExpr->pRight) ){
72491       return 1;
72492     }
72493     pExpr = pExpr->pLeft;
72494   }
72495   return 0;
72496 }
72497 SQLITE_PRIVATE int sqlite3FixExprList(
72498   DbFixer *pFix,     /* Context of the fixation */
72499   ExprList *pList    /* The expression to be fixed to one database */
72500 ){
72501   int i;
72502   struct ExprList_item *pItem;
72503   if( pList==0 ) return 0;
72504   for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
72505     if( sqlite3FixExpr(pFix, pItem->pExpr) ){
72506       return 1;
72507     }
72508   }
72509   return 0;
72510 }
72511 #endif
72512
72513 #ifndef SQLITE_OMIT_TRIGGER
72514 SQLITE_PRIVATE int sqlite3FixTriggerStep(
72515   DbFixer *pFix,     /* Context of the fixation */
72516   TriggerStep *pStep /* The trigger step be fixed to one database */
72517 ){
72518   while( pStep ){
72519     if( sqlite3FixSelect(pFix, pStep->pSelect) ){
72520       return 1;
72521     }
72522     if( sqlite3FixExpr(pFix, pStep->pWhere) ){
72523       return 1;
72524     }
72525     if( sqlite3FixExprList(pFix, pStep->pExprList) ){
72526       return 1;
72527     }
72528     pStep = pStep->pNext;
72529   }
72530   return 0;
72531 }
72532 #endif
72533
72534 /************** End of attach.c **********************************************/
72535 /************** Begin file auth.c ********************************************/
72536 /*
72537 ** 2003 January 11
72538 **
72539 ** The author disclaims copyright to this source code.  In place of
72540 ** a legal notice, here is a blessing:
72541 **
72542 **    May you do good and not evil.
72543 **    May you find forgiveness for yourself and forgive others.
72544 **    May you share freely, never taking more than you give.
72545 **
72546 *************************************************************************
72547 ** This file contains code used to implement the sqlite3_set_authorizer()
72548 ** API.  This facility is an optional feature of the library.  Embedded
72549 ** systems that do not need this facility may omit it by recompiling
72550 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
72551 */
72552
72553 /*
72554 ** All of the code in this file may be omitted by defining a single
72555 ** macro.
72556 */
72557 #ifndef SQLITE_OMIT_AUTHORIZATION
72558
72559 /*
72560 ** Set or clear the access authorization function.
72561 **
72562 ** The access authorization function is be called during the compilation
72563 ** phase to verify that the user has read and/or write access permission on
72564 ** various fields of the database.  The first argument to the auth function
72565 ** is a copy of the 3rd argument to this routine.  The second argument
72566 ** to the auth function is one of these constants:
72567 **
72568 **       SQLITE_CREATE_INDEX
72569 **       SQLITE_CREATE_TABLE
72570 **       SQLITE_CREATE_TEMP_INDEX
72571 **       SQLITE_CREATE_TEMP_TABLE
72572 **       SQLITE_CREATE_TEMP_TRIGGER
72573 **       SQLITE_CREATE_TEMP_VIEW
72574 **       SQLITE_CREATE_TRIGGER
72575 **       SQLITE_CREATE_VIEW
72576 **       SQLITE_DELETE
72577 **       SQLITE_DROP_INDEX
72578 **       SQLITE_DROP_TABLE
72579 **       SQLITE_DROP_TEMP_INDEX
72580 **       SQLITE_DROP_TEMP_TABLE
72581 **       SQLITE_DROP_TEMP_TRIGGER
72582 **       SQLITE_DROP_TEMP_VIEW
72583 **       SQLITE_DROP_TRIGGER
72584 **       SQLITE_DROP_VIEW
72585 **       SQLITE_INSERT
72586 **       SQLITE_PRAGMA
72587 **       SQLITE_READ
72588 **       SQLITE_SELECT
72589 **       SQLITE_TRANSACTION
72590 **       SQLITE_UPDATE
72591 **
72592 ** The third and fourth arguments to the auth function are the name of
72593 ** the table and the column that are being accessed.  The auth function
72594 ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
72595 ** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
72596 ** means that the SQL statement will never-run - the sqlite3_exec() call
72597 ** will return with an error.  SQLITE_IGNORE means that the SQL statement
72598 ** should run but attempts to read the specified column will return NULL
72599 ** and attempts to write the column will be ignored.
72600 **
72601 ** Setting the auth function to NULL disables this hook.  The default
72602 ** setting of the auth function is NULL.
72603 */
72604 SQLITE_API int sqlite3_set_authorizer(
72605   sqlite3 *db,
72606   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
72607   void *pArg
72608 ){
72609   sqlite3_mutex_enter(db->mutex);
72610   db->xAuth = xAuth;
72611   db->pAuthArg = pArg;
72612   sqlite3ExpirePreparedStatements(db);
72613   sqlite3_mutex_leave(db->mutex);
72614   return SQLITE_OK;
72615 }
72616
72617 /*
72618 ** Write an error message into pParse->zErrMsg that explains that the
72619 ** user-supplied authorization function returned an illegal value.
72620 */
72621 static void sqliteAuthBadReturnCode(Parse *pParse){
72622   sqlite3ErrorMsg(pParse, "authorizer malfunction");
72623   pParse->rc = SQLITE_ERROR;
72624 }
72625
72626 /*
72627 ** Invoke the authorization callback for permission to read column zCol from
72628 ** table zTab in database zDb. This function assumes that an authorization
72629 ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
72630 **
72631 ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
72632 ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
72633 ** is treated as SQLITE_DENY. In this case an error is left in pParse.
72634 */
72635 SQLITE_PRIVATE int sqlite3AuthReadCol(
72636   Parse *pParse,                  /* The parser context */
72637   const char *zTab,               /* Table name */
72638   const char *zCol,               /* Column name */
72639   int iDb                         /* Index of containing database. */
72640 ){
72641   sqlite3 *db = pParse->db;       /* Database handle */
72642   char *zDb = db->aDb[iDb].zName; /* Name of attached database */
72643   int rc;                         /* Auth callback return code */
72644
72645   rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
72646   if( rc==SQLITE_DENY ){
72647     if( db->nDb>2 || iDb!=0 ){
72648       sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
72649     }else{
72650       sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
72651     }
72652     pParse->rc = SQLITE_AUTH;
72653   }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
72654     sqliteAuthBadReturnCode(pParse);
72655   }
72656   return rc;
72657 }
72658
72659 /*
72660 ** The pExpr should be a TK_COLUMN expression.  The table referred to
72661 ** is in pTabList or else it is the NEW or OLD table of a trigger.  
72662 ** Check to see if it is OK to read this particular column.
72663 **
72664 ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN 
72665 ** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
72666 ** then generate an error.
72667 */
72668 SQLITE_PRIVATE void sqlite3AuthRead(
72669   Parse *pParse,        /* The parser context */
72670   Expr *pExpr,          /* The expression to check authorization on */
72671   Schema *pSchema,      /* The schema of the expression */
72672   SrcList *pTabList     /* All table that pExpr might refer to */
72673 ){
72674   sqlite3 *db = pParse->db;
72675   Table *pTab = 0;      /* The table being read */
72676   const char *zCol;     /* Name of the column of the table */
72677   int iSrc;             /* Index in pTabList->a[] of table being read */
72678   int iDb;              /* The index of the database the expression refers to */
72679   int iCol;             /* Index of column in table */
72680
72681   if( db->xAuth==0 ) return;
72682   iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
72683   if( iDb<0 ){
72684     /* An attempt to read a column out of a subquery or other
72685     ** temporary table. */
72686     return;
72687   }
72688
72689   assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
72690   if( pExpr->op==TK_TRIGGER ){
72691     pTab = pParse->pTriggerTab;
72692   }else{
72693     assert( pTabList );
72694     for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
72695       if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
72696         pTab = pTabList->a[iSrc].pTab;
72697         break;
72698       }
72699     }
72700   }
72701   iCol = pExpr->iColumn;
72702   if( NEVER(pTab==0) ) return;
72703
72704   if( iCol>=0 ){
72705     assert( iCol<pTab->nCol );
72706     zCol = pTab->aCol[iCol].zName;
72707   }else if( pTab->iPKey>=0 ){
72708     assert( pTab->iPKey<pTab->nCol );
72709     zCol = pTab->aCol[pTab->iPKey].zName;
72710   }else{
72711     zCol = "ROWID";
72712   }
72713   assert( iDb>=0 && iDb<db->nDb );
72714   if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
72715     pExpr->op = TK_NULL;
72716   }
72717 }
72718
72719 /*
72720 ** Do an authorization check using the code and arguments given.  Return
72721 ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
72722 ** is returned, then the error count and error message in pParse are
72723 ** modified appropriately.
72724 */
72725 SQLITE_PRIVATE int sqlite3AuthCheck(
72726   Parse *pParse,
72727   int code,
72728   const char *zArg1,
72729   const char *zArg2,
72730   const char *zArg3
72731 ){
72732   sqlite3 *db = pParse->db;
72733   int rc;
72734
72735   /* Don't do any authorization checks if the database is initialising
72736   ** or if the parser is being invoked from within sqlite3_declare_vtab.
72737   */
72738   if( db->init.busy || IN_DECLARE_VTAB ){
72739     return SQLITE_OK;
72740   }
72741
72742   if( db->xAuth==0 ){
72743     return SQLITE_OK;
72744   }
72745   rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
72746   if( rc==SQLITE_DENY ){
72747     sqlite3ErrorMsg(pParse, "not authorized");
72748     pParse->rc = SQLITE_AUTH;
72749   }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
72750     rc = SQLITE_DENY;
72751     sqliteAuthBadReturnCode(pParse);
72752   }
72753   return rc;
72754 }
72755
72756 /*
72757 ** Push an authorization context.  After this routine is called, the
72758 ** zArg3 argument to authorization callbacks will be zContext until
72759 ** popped.  Or if pParse==0, this routine is a no-op.
72760 */
72761 SQLITE_PRIVATE void sqlite3AuthContextPush(
72762   Parse *pParse,
72763   AuthContext *pContext, 
72764   const char *zContext
72765 ){
72766   assert( pParse );
72767   pContext->pParse = pParse;
72768   pContext->zAuthContext = pParse->zAuthContext;
72769   pParse->zAuthContext = zContext;
72770 }
72771
72772 /*
72773 ** Pop an authorization context that was previously pushed
72774 ** by sqlite3AuthContextPush
72775 */
72776 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
72777   if( pContext->pParse ){
72778     pContext->pParse->zAuthContext = pContext->zAuthContext;
72779     pContext->pParse = 0;
72780   }
72781 }
72782
72783 #endif /* SQLITE_OMIT_AUTHORIZATION */
72784
72785 /************** End of auth.c ************************************************/
72786 /************** Begin file build.c *******************************************/
72787 /*
72788 ** 2001 September 15
72789 **
72790 ** The author disclaims copyright to this source code.  In place of
72791 ** a legal notice, here is a blessing:
72792 **
72793 **    May you do good and not evil.
72794 **    May you find forgiveness for yourself and forgive others.
72795 **    May you share freely, never taking more than you give.
72796 **
72797 *************************************************************************
72798 ** This file contains C code routines that are called by the SQLite parser
72799 ** when syntax rules are reduced.  The routines in this file handle the
72800 ** following kinds of SQL syntax:
72801 **
72802 **     CREATE TABLE
72803 **     DROP TABLE
72804 **     CREATE INDEX
72805 **     DROP INDEX
72806 **     creating ID lists
72807 **     BEGIN TRANSACTION
72808 **     COMMIT
72809 **     ROLLBACK
72810 */
72811
72812 /*
72813 ** This routine is called when a new SQL statement is beginning to
72814 ** be parsed.  Initialize the pParse structure as needed.
72815 */
72816 SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
72817   pParse->explain = (u8)explainFlag;
72818   pParse->nVar = 0;
72819 }
72820
72821 #ifndef SQLITE_OMIT_SHARED_CACHE
72822 /*
72823 ** The TableLock structure is only used by the sqlite3TableLock() and
72824 ** codeTableLocks() functions.
72825 */
72826 struct TableLock {
72827   int iDb;             /* The database containing the table to be locked */
72828   int iTab;            /* The root page of the table to be locked */
72829   u8 isWriteLock;      /* True for write lock.  False for a read lock */
72830   const char *zName;   /* Name of the table */
72831 };
72832
72833 /*
72834 ** Record the fact that we want to lock a table at run-time.  
72835 **
72836 ** The table to be locked has root page iTab and is found in database iDb.
72837 ** A read or a write lock can be taken depending on isWritelock.
72838 **
72839 ** This routine just records the fact that the lock is desired.  The
72840 ** code to make the lock occur is generated by a later call to
72841 ** codeTableLocks() which occurs during sqlite3FinishCoding().
72842 */
72843 SQLITE_PRIVATE void sqlite3TableLock(
72844   Parse *pParse,     /* Parsing context */
72845   int iDb,           /* Index of the database containing the table to lock */
72846   int iTab,          /* Root page number of the table to be locked */
72847   u8 isWriteLock,    /* True for a write lock */
72848   const char *zName  /* Name of the table to be locked */
72849 ){
72850   Parse *pToplevel = sqlite3ParseToplevel(pParse);
72851   int i;
72852   int nBytes;
72853   TableLock *p;
72854   assert( iDb>=0 );
72855
72856   for(i=0; i<pToplevel->nTableLock; i++){
72857     p = &pToplevel->aTableLock[i];
72858     if( p->iDb==iDb && p->iTab==iTab ){
72859       p->isWriteLock = (p->isWriteLock || isWriteLock);
72860       return;
72861     }
72862   }
72863
72864   nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
72865   pToplevel->aTableLock =
72866       sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
72867   if( pToplevel->aTableLock ){
72868     p = &pToplevel->aTableLock[pToplevel->nTableLock++];
72869     p->iDb = iDb;
72870     p->iTab = iTab;
72871     p->isWriteLock = isWriteLock;
72872     p->zName = zName;
72873   }else{
72874     pToplevel->nTableLock = 0;
72875     pToplevel->db->mallocFailed = 1;
72876   }
72877 }
72878
72879 /*
72880 ** Code an OP_TableLock instruction for each table locked by the
72881 ** statement (configured by calls to sqlite3TableLock()).
72882 */
72883 static void codeTableLocks(Parse *pParse){
72884   int i;
72885   Vdbe *pVdbe; 
72886
72887   pVdbe = sqlite3GetVdbe(pParse);
72888   assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
72889
72890   for(i=0; i<pParse->nTableLock; i++){
72891     TableLock *p = &pParse->aTableLock[i];
72892     int p1 = p->iDb;
72893     sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
72894                       p->zName, P4_STATIC);
72895   }
72896 }
72897 #else
72898   #define codeTableLocks(x)
72899 #endif
72900
72901 /*
72902 ** This routine is called after a single SQL statement has been
72903 ** parsed and a VDBE program to execute that statement has been
72904 ** prepared.  This routine puts the finishing touches on the
72905 ** VDBE program and resets the pParse structure for the next
72906 ** parse.
72907 **
72908 ** Note that if an error occurred, it might be the case that
72909 ** no VDBE code was generated.
72910 */
72911 SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
72912   sqlite3 *db;
72913   Vdbe *v;
72914
72915   db = pParse->db;
72916   if( db->mallocFailed ) return;
72917   if( pParse->nested ) return;
72918   if( pParse->nErr ) return;
72919
72920   /* Begin by generating some termination code at the end of the
72921   ** vdbe program
72922   */
72923   v = sqlite3GetVdbe(pParse);
72924   assert( !pParse->isMultiWrite 
72925        || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
72926   if( v ){
72927     sqlite3VdbeAddOp0(v, OP_Halt);
72928
72929     /* The cookie mask contains one bit for each database file open.
72930     ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
72931     ** set for each database that is used.  Generate code to start a
72932     ** transaction on each used database and to verify the schema cookie
72933     ** on each used database.
72934     */
72935     if( pParse->cookieGoto>0 ){
72936       u32 mask;
72937       int iDb;
72938       sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
72939       for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
72940         if( (mask & pParse->cookieMask)==0 ) continue;
72941         sqlite3VdbeUsesBtree(v, iDb);
72942         sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
72943         if( db->init.busy==0 ){
72944           sqlite3VdbeAddOp2(v,OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
72945         }
72946       }
72947 #ifndef SQLITE_OMIT_VIRTUALTABLE
72948       {
72949         int i;
72950         for(i=0; i<pParse->nVtabLock; i++){
72951           char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
72952           sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
72953         }
72954         pParse->nVtabLock = 0;
72955       }
72956 #endif
72957
72958       /* Once all the cookies have been verified and transactions opened, 
72959       ** obtain the required table-locks. This is a no-op unless the 
72960       ** shared-cache feature is enabled.
72961       */
72962       codeTableLocks(pParse);
72963
72964       /* Initialize any AUTOINCREMENT data structures required.
72965       */
72966       sqlite3AutoincrementBegin(pParse);
72967
72968       /* Finally, jump back to the beginning of the executable code. */
72969       sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
72970     }
72971   }
72972
72973
72974   /* Get the VDBE program ready for execution
72975   */
72976   if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
72977 #ifdef SQLITE_DEBUG
72978     FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
72979     sqlite3VdbeTrace(v, trace);
72980 #endif
72981     assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
72982     /* A minimum of one cursor is required if autoincrement is used
72983     *  See ticket [a696379c1f08866] */
72984     if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
72985     sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem,
72986                          pParse->nTab, pParse->nMaxArg, pParse->explain,
72987                          pParse->isMultiWrite && pParse->mayAbort);
72988     pParse->rc = SQLITE_DONE;
72989     pParse->colNamesSet = 0;
72990   }else{
72991     pParse->rc = SQLITE_ERROR;
72992   }
72993   pParse->nTab = 0;
72994   pParse->nMem = 0;
72995   pParse->nSet = 0;
72996   pParse->nVar = 0;
72997   pParse->cookieMask = 0;
72998   pParse->cookieGoto = 0;
72999 }
73000
73001 /*
73002 ** Run the parser and code generator recursively in order to generate
73003 ** code for the SQL statement given onto the end of the pParse context
73004 ** currently under construction.  When the parser is run recursively
73005 ** this way, the final OP_Halt is not appended and other initialization
73006 ** and finalization steps are omitted because those are handling by the
73007 ** outermost parser.
73008 **
73009 ** Not everything is nestable.  This facility is designed to permit
73010 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
73011 ** care if you decide to try to use this routine for some other purposes.
73012 */
73013 SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
73014   va_list ap;
73015   char *zSql;
73016   char *zErrMsg = 0;
73017   sqlite3 *db = pParse->db;
73018 # define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
73019   char saveBuf[SAVE_SZ];
73020
73021   if( pParse->nErr ) return;
73022   assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
73023   va_start(ap, zFormat);
73024   zSql = sqlite3VMPrintf(db, zFormat, ap);
73025   va_end(ap);
73026   if( zSql==0 ){
73027     return;   /* A malloc must have failed */
73028   }
73029   pParse->nested++;
73030   memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
73031   memset(&pParse->nVar, 0, SAVE_SZ);
73032   sqlite3RunParser(pParse, zSql, &zErrMsg);
73033   sqlite3DbFree(db, zErrMsg);
73034   sqlite3DbFree(db, zSql);
73035   memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
73036   pParse->nested--;
73037 }
73038
73039 /*
73040 ** Locate the in-memory structure that describes a particular database
73041 ** table given the name of that table and (optionally) the name of the
73042 ** database containing the table.  Return NULL if not found.
73043 **
73044 ** If zDatabase is 0, all databases are searched for the table and the
73045 ** first matching table is returned.  (No checking for duplicate table
73046 ** names is done.)  The search order is TEMP first, then MAIN, then any
73047 ** auxiliary databases added using the ATTACH command.
73048 **
73049 ** See also sqlite3LocateTable().
73050 */
73051 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
73052   Table *p = 0;
73053   int i;
73054   int nName;
73055   assert( zName!=0 );
73056   nName = sqlite3Strlen30(zName);
73057   for(i=OMIT_TEMPDB; i<db->nDb; i++){
73058     int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
73059     if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
73060     p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
73061     if( p ) break;
73062   }
73063   return p;
73064 }
73065
73066 /*
73067 ** Locate the in-memory structure that describes a particular database
73068 ** table given the name of that table and (optionally) the name of the
73069 ** database containing the table.  Return NULL if not found.  Also leave an
73070 ** error message in pParse->zErrMsg.
73071 **
73072 ** The difference between this routine and sqlite3FindTable() is that this
73073 ** routine leaves an error message in pParse->zErrMsg where
73074 ** sqlite3FindTable() does not.
73075 */
73076 SQLITE_PRIVATE Table *sqlite3LocateTable(
73077   Parse *pParse,         /* context in which to report errors */
73078   int isView,            /* True if looking for a VIEW rather than a TABLE */
73079   const char *zName,     /* Name of the table we are looking for */
73080   const char *zDbase     /* Name of the database.  Might be NULL */
73081 ){
73082   Table *p;
73083
73084   /* Read the database schema. If an error occurs, leave an error message
73085   ** and code in pParse and return NULL. */
73086   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
73087     return 0;
73088   }
73089
73090   p = sqlite3FindTable(pParse->db, zName, zDbase);
73091   if( p==0 ){
73092     const char *zMsg = isView ? "no such view" : "no such table";
73093     if( zDbase ){
73094       sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
73095     }else{
73096       sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
73097     }
73098     pParse->checkSchema = 1;
73099   }
73100   return p;
73101 }
73102
73103 /*
73104 ** Locate the in-memory structure that describes 
73105 ** a particular index given the name of that index
73106 ** and the name of the database that contains the index.
73107 ** Return NULL if not found.
73108 **
73109 ** If zDatabase is 0, all databases are searched for the
73110 ** table and the first matching index is returned.  (No checking
73111 ** for duplicate index names is done.)  The search order is
73112 ** TEMP first, then MAIN, then any auxiliary databases added
73113 ** using the ATTACH command.
73114 */
73115 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
73116   Index *p = 0;
73117   int i;
73118   int nName = sqlite3Strlen30(zName);
73119   for(i=OMIT_TEMPDB; i<db->nDb; i++){
73120     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
73121     Schema *pSchema = db->aDb[j].pSchema;
73122     assert( pSchema );
73123     if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
73124     p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
73125     if( p ) break;
73126   }
73127   return p;
73128 }
73129
73130 /*
73131 ** Reclaim the memory used by an index
73132 */
73133 static void freeIndex(Index *p){
73134   sqlite3 *db = p->pTable->dbMem;
73135 #ifndef SQLITE_OMIT_ANALYZE
73136   sqlite3DeleteIndexSamples(p);
73137 #endif
73138   sqlite3DbFree(db, p->zColAff);
73139   sqlite3DbFree(db, p);
73140 }
73141
73142 /*
73143 ** Remove the given index from the index hash table, and free
73144 ** its memory structures.
73145 **
73146 ** The index is removed from the database hash tables but
73147 ** it is not unlinked from the Table that it indexes.
73148 ** Unlinking from the Table must be done by the calling function.
73149 */
73150 static void sqlite3DeleteIndex(Index *p){
73151   Index *pOld;
73152   const char *zName = p->zName;
73153
73154   pOld = sqlite3HashInsert(&p->pSchema->idxHash, zName,
73155                            sqlite3Strlen30(zName), 0);
73156   assert( pOld==0 || pOld==p );
73157   freeIndex(p);
73158 }
73159
73160 /*
73161 ** For the index called zIdxName which is found in the database iDb,
73162 ** unlike that index from its Table then remove the index from
73163 ** the index hash table and free all memory structures associated
73164 ** with the index.
73165 */
73166 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
73167   Index *pIndex;
73168   int len;
73169   Hash *pHash = &db->aDb[iDb].pSchema->idxHash;
73170
73171   len = sqlite3Strlen30(zIdxName);
73172   pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
73173   if( pIndex ){
73174     if( pIndex->pTable->pIndex==pIndex ){
73175       pIndex->pTable->pIndex = pIndex->pNext;
73176     }else{
73177       Index *p;
73178       /* Justification of ALWAYS();  The index must be on the list of
73179       ** indices. */
73180       p = pIndex->pTable->pIndex;
73181       while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
73182       if( ALWAYS(p && p->pNext==pIndex) ){
73183         p->pNext = pIndex->pNext;
73184       }
73185     }
73186     freeIndex(pIndex);
73187   }
73188   db->flags |= SQLITE_InternChanges;
73189 }
73190
73191 /*
73192 ** Erase all schema information from the in-memory hash tables of
73193 ** a single database.  This routine is called to reclaim memory
73194 ** before the database closes.  It is also called during a rollback
73195 ** if there were schema changes during the transaction or if a
73196 ** schema-cookie mismatch occurs.
73197 **
73198 ** If iDb==0 then reset the internal schema tables for all database
73199 ** files.  If iDb>=1 then reset the internal schema for only the
73200 ** single file indicated.
73201 */
73202 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
73203   int i, j;
73204   assert( iDb>=0 && iDb<db->nDb );
73205
73206   if( iDb==0 ){
73207     sqlite3BtreeEnterAll(db);
73208   }
73209   for(i=iDb; i<db->nDb; i++){
73210     Db *pDb = &db->aDb[i];
73211     if( pDb->pSchema ){
73212       assert(i==1 || (pDb->pBt && sqlite3BtreeHoldsMutex(pDb->pBt)));
73213       sqlite3SchemaFree(pDb->pSchema);
73214     }
73215     if( iDb>0 ) return;
73216   }
73217   assert( iDb==0 );
73218   db->flags &= ~SQLITE_InternChanges;
73219   sqlite3VtabUnlockList(db);
73220   sqlite3BtreeLeaveAll(db);
73221
73222   /* If one or more of the auxiliary database files has been closed,
73223   ** then remove them from the auxiliary database list.  We take the
73224   ** opportunity to do this here since we have just deleted all of the
73225   ** schema hash tables and therefore do not have to make any changes
73226   ** to any of those tables.
73227   */
73228   for(i=j=2; i<db->nDb; i++){
73229     struct Db *pDb = &db->aDb[i];
73230     if( pDb->pBt==0 ){
73231       sqlite3DbFree(db, pDb->zName);
73232       pDb->zName = 0;
73233       continue;
73234     }
73235     if( j<i ){
73236       db->aDb[j] = db->aDb[i];
73237     }
73238     j++;
73239   }
73240   memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
73241   db->nDb = j;
73242   if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
73243     memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
73244     sqlite3DbFree(db, db->aDb);
73245     db->aDb = db->aDbStatic;
73246   }
73247 }
73248
73249 /*
73250 ** This routine is called when a commit occurs.
73251 */
73252 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
73253   db->flags &= ~SQLITE_InternChanges;
73254 }
73255
73256 /*
73257 ** Clear the column names from a table or view.
73258 */
73259 static void sqliteResetColumnNames(Table *pTable){
73260   int i;
73261   Column *pCol;
73262   sqlite3 *db = pTable->dbMem;
73263   testcase( db==0 );
73264   assert( pTable!=0 );
73265   if( (pCol = pTable->aCol)!=0 ){
73266     for(i=0; i<pTable->nCol; i++, pCol++){
73267       sqlite3DbFree(db, pCol->zName);
73268       sqlite3ExprDelete(db, pCol->pDflt);
73269       sqlite3DbFree(db, pCol->zDflt);
73270       sqlite3DbFree(db, pCol->zType);
73271       sqlite3DbFree(db, pCol->zColl);
73272     }
73273     sqlite3DbFree(db, pTable->aCol);
73274   }
73275   pTable->aCol = 0;
73276   pTable->nCol = 0;
73277 }
73278
73279 /*
73280 ** Remove the memory data structures associated with the given
73281 ** Table.  No changes are made to disk by this routine.
73282 **
73283 ** This routine just deletes the data structure.  It does not unlink
73284 ** the table data structure from the hash table.  But it does destroy
73285 ** memory structures of the indices and foreign keys associated with 
73286 ** the table.
73287 */
73288 SQLITE_PRIVATE void sqlite3DeleteTable(Table *pTable){
73289   Index *pIndex, *pNext;
73290   sqlite3 *db;
73291
73292   if( pTable==0 ) return;
73293   db = pTable->dbMem;
73294   testcase( db==0 );
73295
73296   /* Do not delete the table until the reference count reaches zero. */
73297   pTable->nRef--;
73298   if( pTable->nRef>0 ){
73299     return;
73300   }
73301   assert( pTable->nRef==0 );
73302
73303   /* Delete all indices associated with this table
73304   */
73305   for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
73306     pNext = pIndex->pNext;
73307     assert( pIndex->pSchema==pTable->pSchema );
73308     sqlite3DeleteIndex(pIndex);
73309   }
73310
73311   /* Delete any foreign keys attached to this table. */
73312   sqlite3FkDelete(pTable);
73313
73314   /* Delete the Table structure itself.
73315   */
73316   sqliteResetColumnNames(pTable);
73317   sqlite3DbFree(db, pTable->zName);
73318   sqlite3DbFree(db, pTable->zColAff);
73319   sqlite3SelectDelete(db, pTable->pSelect);
73320 #ifndef SQLITE_OMIT_CHECK
73321   sqlite3ExprDelete(db, pTable->pCheck);
73322 #endif
73323   sqlite3VtabClear(pTable);
73324   sqlite3DbFree(db, pTable);
73325 }
73326
73327 /*
73328 ** Unlink the given table from the hash tables and the delete the
73329 ** table structure with all its indices and foreign keys.
73330 */
73331 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
73332   Table *p;
73333   Db *pDb;
73334
73335   assert( db!=0 );
73336   assert( iDb>=0 && iDb<db->nDb );
73337   assert( zTabName );
73338   testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
73339   pDb = &db->aDb[iDb];
73340   p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
73341                         sqlite3Strlen30(zTabName),0);
73342   sqlite3DeleteTable(p);
73343   db->flags |= SQLITE_InternChanges;
73344 }
73345
73346 /*
73347 ** Given a token, return a string that consists of the text of that
73348 ** token.  Space to hold the returned string
73349 ** is obtained from sqliteMalloc() and must be freed by the calling
73350 ** function.
73351 **
73352 ** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
73353 ** surround the body of the token are removed.
73354 **
73355 ** Tokens are often just pointers into the original SQL text and so
73356 ** are not \000 terminated and are not persistent.  The returned string
73357 ** is \000 terminated and is persistent.
73358 */
73359 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
73360   char *zName;
73361   if( pName ){
73362     zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
73363     sqlite3Dequote(zName);
73364   }else{
73365     zName = 0;
73366   }
73367   return zName;
73368 }
73369
73370 /*
73371 ** Open the sqlite_master table stored in database number iDb for
73372 ** writing. The table is opened using cursor 0.
73373 */
73374 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
73375   Vdbe *v = sqlite3GetVdbe(p);
73376   sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
73377   sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
73378   sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32);  /* 5 column table */
73379   if( p->nTab==0 ){
73380     p->nTab = 1;
73381   }
73382 }
73383
73384 /*
73385 ** Parameter zName points to a nul-terminated buffer containing the name
73386 ** of a database ("main", "temp" or the name of an attached db). This
73387 ** function returns the index of the named database in db->aDb[], or
73388 ** -1 if the named db cannot be found.
73389 */
73390 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
73391   int i = -1;         /* Database number */
73392   if( zName ){
73393     Db *pDb;
73394     int n = sqlite3Strlen30(zName);
73395     for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
73396       if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) && 
73397           0==sqlite3StrICmp(pDb->zName, zName) ){
73398         break;
73399       }
73400     }
73401   }
73402   return i;
73403 }
73404
73405 /*
73406 ** The token *pName contains the name of a database (either "main" or
73407 ** "temp" or the name of an attached db). This routine returns the
73408 ** index of the named database in db->aDb[], or -1 if the named db 
73409 ** does not exist.
73410 */
73411 SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
73412   int i;                               /* Database number */
73413   char *zName;                         /* Name we are searching for */
73414   zName = sqlite3NameFromToken(db, pName);
73415   i = sqlite3FindDbName(db, zName);
73416   sqlite3DbFree(db, zName);
73417   return i;
73418 }
73419
73420 /* The table or view or trigger name is passed to this routine via tokens
73421 ** pName1 and pName2. If the table name was fully qualified, for example:
73422 **
73423 ** CREATE TABLE xxx.yyy (...);
73424 ** 
73425 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
73426 ** the table name is not fully qualified, i.e.:
73427 **
73428 ** CREATE TABLE yyy(...);
73429 **
73430 ** Then pName1 is set to "yyy" and pName2 is "".
73431 **
73432 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
73433 ** pName2) that stores the unqualified table name.  The index of the
73434 ** database "xxx" is returned.
73435 */
73436 SQLITE_PRIVATE int sqlite3TwoPartName(
73437   Parse *pParse,      /* Parsing and code generating context */
73438   Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
73439   Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
73440   Token **pUnqual     /* Write the unqualified object name here */
73441 ){
73442   int iDb;                    /* Database holding the object */
73443   sqlite3 *db = pParse->db;
73444
73445   if( ALWAYS(pName2!=0) && pName2->n>0 ){
73446     if( db->init.busy ) {
73447       sqlite3ErrorMsg(pParse, "corrupt database");
73448       pParse->nErr++;
73449       return -1;
73450     }
73451     *pUnqual = pName2;
73452     iDb = sqlite3FindDb(db, pName1);
73453     if( iDb<0 ){
73454       sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
73455       pParse->nErr++;
73456       return -1;
73457     }
73458   }else{
73459     assert( db->init.iDb==0 || db->init.busy );
73460     iDb = db->init.iDb;
73461     *pUnqual = pName1;
73462   }
73463   return iDb;
73464 }
73465
73466 /*
73467 ** This routine is used to check if the UTF-8 string zName is a legal
73468 ** unqualified name for a new schema object (table, index, view or
73469 ** trigger). All names are legal except those that begin with the string
73470 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
73471 ** is reserved for internal use.
73472 */
73473 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
73474   if( !pParse->db->init.busy && pParse->nested==0 
73475           && (pParse->db->flags & SQLITE_WriteSchema)==0
73476           && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
73477     sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
73478     return SQLITE_ERROR;
73479   }
73480   return SQLITE_OK;
73481 }
73482
73483 /*
73484 ** Begin constructing a new table representation in memory.  This is
73485 ** the first of several action routines that get called in response
73486 ** to a CREATE TABLE statement.  In particular, this routine is called
73487 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
73488 ** flag is true if the table should be stored in the auxiliary database
73489 ** file instead of in the main database file.  This is normally the case
73490 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
73491 ** CREATE and TABLE.
73492 **
73493 ** The new table record is initialized and put in pParse->pNewTable.
73494 ** As more of the CREATE TABLE statement is parsed, additional action
73495 ** routines will be called to add more information to this record.
73496 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
73497 ** is called to complete the construction of the new table record.
73498 */
73499 SQLITE_PRIVATE void sqlite3StartTable(
73500   Parse *pParse,   /* Parser context */
73501   Token *pName1,   /* First part of the name of the table or view */
73502   Token *pName2,   /* Second part of the name of the table or view */
73503   int isTemp,      /* True if this is a TEMP table */
73504   int isView,      /* True if this is a VIEW */
73505   int isVirtual,   /* True if this is a VIRTUAL table */
73506   int noErr        /* Do nothing if table already exists */
73507 ){
73508   Table *pTable;
73509   char *zName = 0; /* The name of the new table */
73510   sqlite3 *db = pParse->db;
73511   Vdbe *v;
73512   int iDb;         /* Database number to create the table in */
73513   Token *pName;    /* Unqualified name of the table to create */
73514
73515   /* The table or view name to create is passed to this routine via tokens
73516   ** pName1 and pName2. If the table name was fully qualified, for example:
73517   **
73518   ** CREATE TABLE xxx.yyy (...);
73519   ** 
73520   ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
73521   ** the table name is not fully qualified, i.e.:
73522   **
73523   ** CREATE TABLE yyy(...);
73524   **
73525   ** Then pName1 is set to "yyy" and pName2 is "".
73526   **
73527   ** The call below sets the pName pointer to point at the token (pName1 or
73528   ** pName2) that stores the unqualified table name. The variable iDb is
73529   ** set to the index of the database that the table or view is to be
73530   ** created in.
73531   */
73532   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
73533   if( iDb<0 ) return;
73534   if( !OMIT_TEMPDB && isTemp && iDb>1 ){
73535     /* If creating a temp table, the name may not be qualified */
73536     sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
73537     return;
73538   }
73539   if( !OMIT_TEMPDB && isTemp ) iDb = 1;
73540
73541   pParse->sNameToken = *pName;
73542   zName = sqlite3NameFromToken(db, pName);
73543   if( zName==0 ) return;
73544   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
73545     goto begin_table_error;
73546   }
73547   if( db->init.iDb==1 ) isTemp = 1;
73548 #ifndef SQLITE_OMIT_AUTHORIZATION
73549   assert( (isTemp & 1)==isTemp );
73550   {
73551     int code;
73552     char *zDb = db->aDb[iDb].zName;
73553     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
73554       goto begin_table_error;
73555     }
73556     if( isView ){
73557       if( !OMIT_TEMPDB && isTemp ){
73558         code = SQLITE_CREATE_TEMP_VIEW;
73559       }else{
73560         code = SQLITE_CREATE_VIEW;
73561       }
73562     }else{
73563       if( !OMIT_TEMPDB && isTemp ){
73564         code = SQLITE_CREATE_TEMP_TABLE;
73565       }else{
73566         code = SQLITE_CREATE_TABLE;
73567       }
73568     }
73569     if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
73570       goto begin_table_error;
73571     }
73572   }
73573 #endif
73574
73575   /* Make sure the new table name does not collide with an existing
73576   ** index or table name in the same database.  Issue an error message if
73577   ** it does. The exception is if the statement being parsed was passed
73578   ** to an sqlite3_declare_vtab() call. In that case only the column names
73579   ** and types will be used, so there is no need to test for namespace
73580   ** collisions.
73581   */
73582   if( !IN_DECLARE_VTAB ){
73583     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
73584       goto begin_table_error;
73585     }
73586     pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName);
73587     if( pTable ){
73588       if( !noErr ){
73589         sqlite3ErrorMsg(pParse, "table %T already exists", pName);
73590       }
73591       goto begin_table_error;
73592     }
73593     if( sqlite3FindIndex(db, zName, 0)!=0 && (iDb==0 || !db->init.busy) ){
73594       sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
73595       goto begin_table_error;
73596     }
73597   }
73598
73599   pTable = sqlite3DbMallocZero(db, sizeof(Table));
73600   if( pTable==0 ){
73601     db->mallocFailed = 1;
73602     pParse->rc = SQLITE_NOMEM;
73603     pParse->nErr++;
73604     goto begin_table_error;
73605   }
73606   pTable->zName = zName;
73607   pTable->iPKey = -1;
73608   pTable->pSchema = db->aDb[iDb].pSchema;
73609   pTable->nRef = 1;
73610   pTable->dbMem = 0;
73611   assert( pParse->pNewTable==0 );
73612   pParse->pNewTable = pTable;
73613
73614   /* If this is the magic sqlite_sequence table used by autoincrement,
73615   ** then record a pointer to this table in the main database structure
73616   ** so that INSERT can find the table easily.
73617   */
73618 #ifndef SQLITE_OMIT_AUTOINCREMENT
73619   if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
73620     pTable->pSchema->pSeqTab = pTable;
73621   }
73622 #endif
73623
73624   /* Begin generating the code that will insert the table record into
73625   ** the SQLITE_MASTER table.  Note in particular that we must go ahead
73626   ** and allocate the record number for the table entry now.  Before any
73627   ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
73628   ** indices to be created and the table record must come before the 
73629   ** indices.  Hence, the record number for the table must be allocated
73630   ** now.
73631   */
73632   if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
73633     int j1;
73634     int fileFormat;
73635     int reg1, reg2, reg3;
73636     sqlite3BeginWriteOperation(pParse, 0, iDb);
73637
73638 #ifndef SQLITE_OMIT_VIRTUALTABLE
73639     if( isVirtual ){
73640       sqlite3VdbeAddOp0(v, OP_VBegin);
73641     }
73642 #endif
73643
73644     /* If the file format and encoding in the database have not been set, 
73645     ** set them now.
73646     */
73647     reg1 = pParse->regRowid = ++pParse->nMem;
73648     reg2 = pParse->regRoot = ++pParse->nMem;
73649     reg3 = ++pParse->nMem;
73650     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
73651     sqlite3VdbeUsesBtree(v, iDb);
73652     j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
73653     fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
73654                   1 : SQLITE_MAX_FILE_FORMAT;
73655     sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
73656     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
73657     sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
73658     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
73659     sqlite3VdbeJumpHere(v, j1);
73660
73661     /* This just creates a place-holder record in the sqlite_master table.
73662     ** The record created does not contain anything yet.  It will be replaced
73663     ** by the real entry in code generated at sqlite3EndTable().
73664     **
73665     ** The rowid for the new entry is left in register pParse->regRowid.
73666     ** The root page number of the new table is left in reg pParse->regRoot.
73667     ** The rowid and root page number values are needed by the code that
73668     ** sqlite3EndTable will generate.
73669     */
73670 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
73671     if( isView || isVirtual ){
73672       sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
73673     }else
73674 #endif
73675     {
73676       sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
73677     }
73678     sqlite3OpenMasterTable(pParse, iDb);
73679     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
73680     sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
73681     sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
73682     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
73683     sqlite3VdbeAddOp0(v, OP_Close);
73684   }
73685
73686   /* Normal (non-error) return. */
73687   return;
73688
73689   /* If an error occurs, we jump here */
73690 begin_table_error:
73691   sqlite3DbFree(db, zName);
73692   return;
73693 }
73694
73695 /*
73696 ** This macro is used to compare two strings in a case-insensitive manner.
73697 ** It is slightly faster than calling sqlite3StrICmp() directly, but
73698 ** produces larger code.
73699 **
73700 ** WARNING: This macro is not compatible with the strcmp() family. It
73701 ** returns true if the two strings are equal, otherwise false.
73702 */
73703 #define STRICMP(x, y) (\
73704 sqlite3UpperToLower[*(unsigned char *)(x)]==   \
73705 sqlite3UpperToLower[*(unsigned char *)(y)]     \
73706 && sqlite3StrICmp((x)+1,(y)+1)==0 )
73707
73708 /*
73709 ** Add a new column to the table currently being constructed.
73710 **
73711 ** The parser calls this routine once for each column declaration
73712 ** in a CREATE TABLE statement.  sqlite3StartTable() gets called
73713 ** first to get things going.  Then this routine is called for each
73714 ** column.
73715 */
73716 SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
73717   Table *p;
73718   int i;
73719   char *z;
73720   Column *pCol;
73721   sqlite3 *db = pParse->db;
73722   if( (p = pParse->pNewTable)==0 ) return;
73723 #if SQLITE_MAX_COLUMN
73724   if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
73725     sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
73726     return;
73727   }
73728 #endif
73729   z = sqlite3NameFromToken(db, pName);
73730   if( z==0 ) return;
73731   for(i=0; i<p->nCol; i++){
73732     if( STRICMP(z, p->aCol[i].zName) ){
73733       sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
73734       sqlite3DbFree(db, z);
73735       return;
73736     }
73737   }
73738   if( (p->nCol & 0x7)==0 ){
73739     Column *aNew;
73740     aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
73741     if( aNew==0 ){
73742       sqlite3DbFree(db, z);
73743       return;
73744     }
73745     p->aCol = aNew;
73746   }
73747   pCol = &p->aCol[p->nCol];
73748   memset(pCol, 0, sizeof(p->aCol[0]));
73749   pCol->zName = z;
73750  
73751   /* If there is no type specified, columns have the default affinity
73752   ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
73753   ** be called next to set pCol->affinity correctly.
73754   */
73755   pCol->affinity = SQLITE_AFF_NONE;
73756   p->nCol++;
73757 }
73758
73759 /*
73760 ** This routine is called by the parser while in the middle of
73761 ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
73762 ** been seen on a column.  This routine sets the notNull flag on
73763 ** the column currently under construction.
73764 */
73765 SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
73766   Table *p;
73767   p = pParse->pNewTable;
73768   if( p==0 || NEVER(p->nCol<1) ) return;
73769   p->aCol[p->nCol-1].notNull = (u8)onError;
73770 }
73771
73772 /*
73773 ** Scan the column type name zType (length nType) and return the
73774 ** associated affinity type.
73775 **
73776 ** This routine does a case-independent search of zType for the 
73777 ** substrings in the following table. If one of the substrings is
73778 ** found, the corresponding affinity is returned. If zType contains
73779 ** more than one of the substrings, entries toward the top of 
73780 ** the table take priority. For example, if zType is 'BLOBINT', 
73781 ** SQLITE_AFF_INTEGER is returned.
73782 **
73783 ** Substring     | Affinity
73784 ** --------------------------------
73785 ** 'INT'         | SQLITE_AFF_INTEGER
73786 ** 'CHAR'        | SQLITE_AFF_TEXT
73787 ** 'CLOB'        | SQLITE_AFF_TEXT
73788 ** 'TEXT'        | SQLITE_AFF_TEXT
73789 ** 'BLOB'        | SQLITE_AFF_NONE
73790 ** 'REAL'        | SQLITE_AFF_REAL
73791 ** 'FLOA'        | SQLITE_AFF_REAL
73792 ** 'DOUB'        | SQLITE_AFF_REAL
73793 **
73794 ** If none of the substrings in the above table are found,
73795 ** SQLITE_AFF_NUMERIC is returned.
73796 */
73797 SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn){
73798   u32 h = 0;
73799   char aff = SQLITE_AFF_NUMERIC;
73800
73801   if( zIn ) while( zIn[0] ){
73802     h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
73803     zIn++;
73804     if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
73805       aff = SQLITE_AFF_TEXT; 
73806     }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
73807       aff = SQLITE_AFF_TEXT;
73808     }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
73809       aff = SQLITE_AFF_TEXT;
73810     }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
73811         && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
73812       aff = SQLITE_AFF_NONE;
73813 #ifndef SQLITE_OMIT_FLOATING_POINT
73814     }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
73815         && aff==SQLITE_AFF_NUMERIC ){
73816       aff = SQLITE_AFF_REAL;
73817     }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
73818         && aff==SQLITE_AFF_NUMERIC ){
73819       aff = SQLITE_AFF_REAL;
73820     }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
73821         && aff==SQLITE_AFF_NUMERIC ){
73822       aff = SQLITE_AFF_REAL;
73823 #endif
73824     }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
73825       aff = SQLITE_AFF_INTEGER;
73826       break;
73827     }
73828   }
73829
73830   return aff;
73831 }
73832
73833 /*
73834 ** This routine is called by the parser while in the middle of
73835 ** parsing a CREATE TABLE statement.  The pFirst token is the first
73836 ** token in the sequence of tokens that describe the type of the
73837 ** column currently under construction.   pLast is the last token
73838 ** in the sequence.  Use this information to construct a string
73839 ** that contains the typename of the column and store that string
73840 ** in zType.
73841 */ 
73842 SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
73843   Table *p;
73844   Column *pCol;
73845
73846   p = pParse->pNewTable;
73847   if( p==0 || NEVER(p->nCol<1) ) return;
73848   pCol = &p->aCol[p->nCol-1];
73849   assert( pCol->zType==0 );
73850   pCol->zType = sqlite3NameFromToken(pParse->db, pType);
73851   pCol->affinity = sqlite3AffinityType(pCol->zType);
73852 }
73853
73854 /*
73855 ** The expression is the default value for the most recently added column
73856 ** of the table currently under construction.
73857 **
73858 ** Default value expressions must be constant.  Raise an exception if this
73859 ** is not the case.
73860 **
73861 ** This routine is called by the parser while in the middle of
73862 ** parsing a CREATE TABLE statement.
73863 */
73864 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
73865   Table *p;
73866   Column *pCol;
73867   sqlite3 *db = pParse->db;
73868   p = pParse->pNewTable;
73869   if( p!=0 ){
73870     pCol = &(p->aCol[p->nCol-1]);
73871     if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
73872       sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
73873           pCol->zName);
73874     }else{
73875       /* A copy of pExpr is used instead of the original, as pExpr contains
73876       ** tokens that point to volatile memory. The 'span' of the expression
73877       ** is required by pragma table_info.
73878       */
73879       sqlite3ExprDelete(db, pCol->pDflt);
73880       pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
73881       sqlite3DbFree(db, pCol->zDflt);
73882       pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
73883                                      (int)(pSpan->zEnd - pSpan->zStart));
73884     }
73885   }
73886   sqlite3ExprDelete(db, pSpan->pExpr);
73887 }
73888
73889 /*
73890 ** Designate the PRIMARY KEY for the table.  pList is a list of names 
73891 ** of columns that form the primary key.  If pList is NULL, then the
73892 ** most recently added column of the table is the primary key.
73893 **
73894 ** A table can have at most one primary key.  If the table already has
73895 ** a primary key (and this is the second primary key) then create an
73896 ** error.
73897 **
73898 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
73899 ** then we will try to use that column as the rowid.  Set the Table.iPKey
73900 ** field of the table under construction to be the index of the
73901 ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
73902 ** no INTEGER PRIMARY KEY.
73903 **
73904 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
73905 ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
73906 */
73907 SQLITE_PRIVATE void sqlite3AddPrimaryKey(
73908   Parse *pParse,    /* Parsing context */
73909   ExprList *pList,  /* List of field names to be indexed */
73910   int onError,      /* What to do with a uniqueness conflict */
73911   int autoInc,      /* True if the AUTOINCREMENT keyword is present */
73912   int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
73913 ){
73914   Table *pTab = pParse->pNewTable;
73915   char *zType = 0;
73916   int iCol = -1, i;
73917   if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
73918   if( pTab->tabFlags & TF_HasPrimaryKey ){
73919     sqlite3ErrorMsg(pParse, 
73920       "table \"%s\" has more than one primary key", pTab->zName);
73921     goto primary_key_exit;
73922   }
73923   pTab->tabFlags |= TF_HasPrimaryKey;
73924   if( pList==0 ){
73925     iCol = pTab->nCol - 1;
73926     pTab->aCol[iCol].isPrimKey = 1;
73927   }else{
73928     for(i=0; i<pList->nExpr; i++){
73929       for(iCol=0; iCol<pTab->nCol; iCol++){
73930         if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
73931           break;
73932         }
73933       }
73934       if( iCol<pTab->nCol ){
73935         pTab->aCol[iCol].isPrimKey = 1;
73936       }
73937     }
73938     if( pList->nExpr>1 ) iCol = -1;
73939   }
73940   if( iCol>=0 && iCol<pTab->nCol ){
73941     zType = pTab->aCol[iCol].zType;
73942   }
73943   if( zType && sqlite3StrICmp(zType, "INTEGER")==0
73944         && sortOrder==SQLITE_SO_ASC ){
73945     pTab->iPKey = iCol;
73946     pTab->keyConf = (u8)onError;
73947     assert( autoInc==0 || autoInc==1 );
73948     pTab->tabFlags |= autoInc*TF_Autoincrement;
73949   }else if( autoInc ){
73950 #ifndef SQLITE_OMIT_AUTOINCREMENT
73951     sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
73952        "INTEGER PRIMARY KEY");
73953 #endif
73954   }else{
73955     Index *p;
73956     p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
73957     if( p ){
73958       p->autoIndex = 2;
73959     }
73960     pList = 0;
73961   }
73962
73963 primary_key_exit:
73964   sqlite3ExprListDelete(pParse->db, pList);
73965   return;
73966 }
73967
73968 /*
73969 ** Add a new CHECK constraint to the table currently under construction.
73970 */
73971 SQLITE_PRIVATE void sqlite3AddCheckConstraint(
73972   Parse *pParse,    /* Parsing context */
73973   Expr *pCheckExpr  /* The check expression */
73974 ){
73975   sqlite3 *db = pParse->db;
73976 #ifndef SQLITE_OMIT_CHECK
73977   Table *pTab = pParse->pNewTable;
73978   if( pTab && !IN_DECLARE_VTAB ){
73979     pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, pCheckExpr);
73980   }else
73981 #endif
73982   {
73983     sqlite3ExprDelete(db, pCheckExpr);
73984   }
73985 }
73986
73987 /*
73988 ** Set the collation function of the most recently parsed table column
73989 ** to the CollSeq given.
73990 */
73991 SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
73992   Table *p;
73993   int i;
73994   char *zColl;              /* Dequoted name of collation sequence */
73995   sqlite3 *db;
73996
73997   if( (p = pParse->pNewTable)==0 ) return;
73998   i = p->nCol-1;
73999   db = pParse->db;
74000   zColl = sqlite3NameFromToken(db, pToken);
74001   if( !zColl ) return;
74002
74003   if( sqlite3LocateCollSeq(pParse, zColl) ){
74004     Index *pIdx;
74005     p->aCol[i].zColl = zColl;
74006   
74007     /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
74008     ** then an index may have been created on this column before the
74009     ** collation type was added. Correct this if it is the case.
74010     */
74011     for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
74012       assert( pIdx->nColumn==1 );
74013       if( pIdx->aiColumn[0]==i ){
74014         pIdx->azColl[0] = p->aCol[i].zColl;
74015       }
74016     }
74017   }else{
74018     sqlite3DbFree(db, zColl);
74019   }
74020 }
74021
74022 /*
74023 ** This function returns the collation sequence for database native text
74024 ** encoding identified by the string zName, length nName.
74025 **
74026 ** If the requested collation sequence is not available, or not available
74027 ** in the database native encoding, the collation factory is invoked to
74028 ** request it. If the collation factory does not supply such a sequence,
74029 ** and the sequence is available in another text encoding, then that is
74030 ** returned instead.
74031 **
74032 ** If no versions of the requested collations sequence are available, or
74033 ** another error occurs, NULL is returned and an error message written into
74034 ** pParse.
74035 **
74036 ** This routine is a wrapper around sqlite3FindCollSeq().  This routine
74037 ** invokes the collation factory if the named collation cannot be found
74038 ** and generates an error message.
74039 **
74040 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
74041 */
74042 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
74043   sqlite3 *db = pParse->db;
74044   u8 enc = ENC(db);
74045   u8 initbusy = db->init.busy;
74046   CollSeq *pColl;
74047
74048   pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
74049   if( !initbusy && (!pColl || !pColl->xCmp) ){
74050     pColl = sqlite3GetCollSeq(db, enc, pColl, zName);
74051     if( !pColl ){
74052       sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
74053     }
74054   }
74055
74056   return pColl;
74057 }
74058
74059
74060 /*
74061 ** Generate code that will increment the schema cookie.
74062 **
74063 ** The schema cookie is used to determine when the schema for the
74064 ** database changes.  After each schema change, the cookie value
74065 ** changes.  When a process first reads the schema it records the
74066 ** cookie.  Thereafter, whenever it goes to access the database,
74067 ** it checks the cookie to make sure the schema has not changed
74068 ** since it was last read.
74069 **
74070 ** This plan is not completely bullet-proof.  It is possible for
74071 ** the schema to change multiple times and for the cookie to be
74072 ** set back to prior value.  But schema changes are infrequent
74073 ** and the probability of hitting the same cookie value is only
74074 ** 1 chance in 2^32.  So we're safe enough.
74075 */
74076 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
74077   int r1 = sqlite3GetTempReg(pParse);
74078   sqlite3 *db = pParse->db;
74079   Vdbe *v = pParse->pVdbe;
74080   sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
74081   sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
74082   sqlite3ReleaseTempReg(pParse, r1);
74083 }
74084
74085 /*
74086 ** Measure the number of characters needed to output the given
74087 ** identifier.  The number returned includes any quotes used
74088 ** but does not include the null terminator.
74089 **
74090 ** The estimate is conservative.  It might be larger that what is
74091 ** really needed.
74092 */
74093 static int identLength(const char *z){
74094   int n;
74095   for(n=0; *z; n++, z++){
74096     if( *z=='"' ){ n++; }
74097   }
74098   return n + 2;
74099 }
74100
74101 /*
74102 ** The first parameter is a pointer to an output buffer. The second 
74103 ** parameter is a pointer to an integer that contains the offset at
74104 ** which to write into the output buffer. This function copies the
74105 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
74106 ** to the specified offset in the buffer and updates *pIdx to refer
74107 ** to the first byte after the last byte written before returning.
74108 ** 
74109 ** If the string zSignedIdent consists entirely of alpha-numeric
74110 ** characters, does not begin with a digit and is not an SQL keyword,
74111 ** then it is copied to the output buffer exactly as it is. Otherwise,
74112 ** it is quoted using double-quotes.
74113 */
74114 static void identPut(char *z, int *pIdx, char *zSignedIdent){
74115   unsigned char *zIdent = (unsigned char*)zSignedIdent;
74116   int i, j, needQuote;
74117   i = *pIdx;
74118
74119   for(j=0; zIdent[j]; j++){
74120     if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
74121   }
74122   needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
74123   if( !needQuote ){
74124     needQuote = zIdent[j];
74125   }
74126
74127   if( needQuote ) z[i++] = '"';
74128   for(j=0; zIdent[j]; j++){
74129     z[i++] = zIdent[j];
74130     if( zIdent[j]=='"' ) z[i++] = '"';
74131   }
74132   if( needQuote ) z[i++] = '"';
74133   z[i] = 0;
74134   *pIdx = i;
74135 }
74136
74137 /*
74138 ** Generate a CREATE TABLE statement appropriate for the given
74139 ** table.  Memory to hold the text of the statement is obtained
74140 ** from sqliteMalloc() and must be freed by the calling function.
74141 */
74142 static char *createTableStmt(sqlite3 *db, Table *p){
74143   int i, k, n;
74144   char *zStmt;
74145   char *zSep, *zSep2, *zEnd;
74146   Column *pCol;
74147   n = 0;
74148   for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
74149     n += identLength(pCol->zName) + 5;
74150   }
74151   n += identLength(p->zName);
74152   if( n<50 ){ 
74153     zSep = "";
74154     zSep2 = ",";
74155     zEnd = ")";
74156   }else{
74157     zSep = "\n  ";
74158     zSep2 = ",\n  ";
74159     zEnd = "\n)";
74160   }
74161   n += 35 + 6*p->nCol;
74162   zStmt = sqlite3Malloc( n );
74163   if( zStmt==0 ){
74164     db->mallocFailed = 1;
74165     return 0;
74166   }
74167   sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
74168   k = sqlite3Strlen30(zStmt);
74169   identPut(zStmt, &k, p->zName);
74170   zStmt[k++] = '(';
74171   for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
74172     static const char * const azType[] = {
74173         /* SQLITE_AFF_TEXT    */ " TEXT",
74174         /* SQLITE_AFF_NONE    */ "",
74175         /* SQLITE_AFF_NUMERIC */ " NUM",
74176         /* SQLITE_AFF_INTEGER */ " INT",
74177         /* SQLITE_AFF_REAL    */ " REAL"
74178     };
74179     int len;
74180     const char *zType;
74181
74182     sqlite3_snprintf(n-k, &zStmt[k], zSep);
74183     k += sqlite3Strlen30(&zStmt[k]);
74184     zSep = zSep2;
74185     identPut(zStmt, &k, pCol->zName);
74186     assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
74187     assert( pCol->affinity-SQLITE_AFF_TEXT < sizeof(azType)/sizeof(azType[0]) );
74188     testcase( pCol->affinity==SQLITE_AFF_TEXT );
74189     testcase( pCol->affinity==SQLITE_AFF_NONE );
74190     testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
74191     testcase( pCol->affinity==SQLITE_AFF_INTEGER );
74192     testcase( pCol->affinity==SQLITE_AFF_REAL );
74193     
74194     zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
74195     len = sqlite3Strlen30(zType);
74196     assert( pCol->affinity==SQLITE_AFF_NONE 
74197             || pCol->affinity==sqlite3AffinityType(zType) );
74198     memcpy(&zStmt[k], zType, len);
74199     k += len;
74200     assert( k<=n );
74201   }
74202   sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
74203   return zStmt;
74204 }
74205
74206 /*
74207 ** This routine is called to report the final ")" that terminates
74208 ** a CREATE TABLE statement.
74209 **
74210 ** The table structure that other action routines have been building
74211 ** is added to the internal hash tables, assuming no errors have
74212 ** occurred.
74213 **
74214 ** An entry for the table is made in the master table on disk, unless
74215 ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
74216 ** it means we are reading the sqlite_master table because we just
74217 ** connected to the database or because the sqlite_master table has
74218 ** recently changed, so the entry for this table already exists in
74219 ** the sqlite_master table.  We do not want to create it again.
74220 **
74221 ** If the pSelect argument is not NULL, it means that this routine
74222 ** was called to create a table generated from a 
74223 ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
74224 ** the new table will match the result set of the SELECT.
74225 */
74226 SQLITE_PRIVATE void sqlite3EndTable(
74227   Parse *pParse,          /* Parse context */
74228   Token *pCons,           /* The ',' token after the last column defn. */
74229   Token *pEnd,            /* The final ')' token in the CREATE TABLE */
74230   Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
74231 ){
74232   Table *p;
74233   sqlite3 *db = pParse->db;
74234   int iDb;
74235
74236   if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
74237     return;
74238   }
74239   p = pParse->pNewTable;
74240   if( p==0 ) return;
74241
74242   assert( !db->init.busy || !pSelect );
74243
74244   iDb = sqlite3SchemaToIndex(db, p->pSchema);
74245
74246 #ifndef SQLITE_OMIT_CHECK
74247   /* Resolve names in all CHECK constraint expressions.
74248   */
74249   if( p->pCheck ){
74250     SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
74251     NameContext sNC;                /* Name context for pParse->pNewTable */
74252
74253     memset(&sNC, 0, sizeof(sNC));
74254     memset(&sSrc, 0, sizeof(sSrc));
74255     sSrc.nSrc = 1;
74256     sSrc.a[0].zName = p->zName;
74257     sSrc.a[0].pTab = p;
74258     sSrc.a[0].iCursor = -1;
74259     sNC.pParse = pParse;
74260     sNC.pSrcList = &sSrc;
74261     sNC.isCheck = 1;
74262     if( sqlite3ResolveExprNames(&sNC, p->pCheck) ){
74263       return;
74264     }
74265   }
74266 #endif /* !defined(SQLITE_OMIT_CHECK) */
74267
74268   /* If the db->init.busy is 1 it means we are reading the SQL off the
74269   ** "sqlite_master" or "sqlite_temp_master" table on the disk.
74270   ** So do not write to the disk again.  Extract the root page number
74271   ** for the table from the db->init.newTnum field.  (The page number
74272   ** should have been put there by the sqliteOpenCb routine.)
74273   */
74274   if( db->init.busy ){
74275     p->tnum = db->init.newTnum;
74276   }
74277
74278   /* If not initializing, then create a record for the new table
74279   ** in the SQLITE_MASTER table of the database.
74280   **
74281   ** If this is a TEMPORARY table, write the entry into the auxiliary
74282   ** file instead of into the main database file.
74283   */
74284   if( !db->init.busy ){
74285     int n;
74286     Vdbe *v;
74287     char *zType;    /* "view" or "table" */
74288     char *zType2;   /* "VIEW" or "TABLE" */
74289     char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
74290
74291     v = sqlite3GetVdbe(pParse);
74292     if( NEVER(v==0) ) return;
74293
74294     sqlite3VdbeAddOp1(v, OP_Close, 0);
74295
74296     /* 
74297     ** Initialize zType for the new view or table.
74298     */
74299     if( p->pSelect==0 ){
74300       /* A regular table */
74301       zType = "table";
74302       zType2 = "TABLE";
74303 #ifndef SQLITE_OMIT_VIEW
74304     }else{
74305       /* A view */
74306       zType = "view";
74307       zType2 = "VIEW";
74308 #endif
74309     }
74310
74311     /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
74312     ** statement to populate the new table. The root-page number for the
74313     ** new table is in register pParse->regRoot.
74314     **
74315     ** Once the SELECT has been coded by sqlite3Select(), it is in a
74316     ** suitable state to query for the column names and types to be used
74317     ** by the new table.
74318     **
74319     ** A shared-cache write-lock is not required to write to the new table,
74320     ** as a schema-lock must have already been obtained to create it. Since
74321     ** a schema-lock excludes all other database users, the write-lock would
74322     ** be redundant.
74323     */
74324     if( pSelect ){
74325       SelectDest dest;
74326       Table *pSelTab;
74327
74328       assert(pParse->nTab==1);
74329       sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
74330       sqlite3VdbeChangeP5(v, 1);
74331       pParse->nTab = 2;
74332       sqlite3SelectDestInit(&dest, SRT_Table, 1);
74333       sqlite3Select(pParse, pSelect, &dest);
74334       sqlite3VdbeAddOp1(v, OP_Close, 1);
74335       if( pParse->nErr==0 ){
74336         pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
74337         if( pSelTab==0 ) return;
74338         assert( p->aCol==0 );
74339         p->nCol = pSelTab->nCol;
74340         p->aCol = pSelTab->aCol;
74341         pSelTab->nCol = 0;
74342         pSelTab->aCol = 0;
74343         sqlite3DeleteTable(pSelTab);
74344       }
74345     }
74346
74347     /* Compute the complete text of the CREATE statement */
74348     if( pSelect ){
74349       zStmt = createTableStmt(db, p);
74350     }else{
74351       n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
74352       zStmt = sqlite3MPrintf(db, 
74353           "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
74354       );
74355     }
74356
74357     /* A slot for the record has already been allocated in the 
74358     ** SQLITE_MASTER table.  We just need to update that slot with all
74359     ** the information we've collected.
74360     */
74361     sqlite3NestedParse(pParse,
74362       "UPDATE %Q.%s "
74363          "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
74364        "WHERE rowid=#%d",
74365       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
74366       zType,
74367       p->zName,
74368       p->zName,
74369       pParse->regRoot,
74370       zStmt,
74371       pParse->regRowid
74372     );
74373     sqlite3DbFree(db, zStmt);
74374     sqlite3ChangeCookie(pParse, iDb);
74375
74376 #ifndef SQLITE_OMIT_AUTOINCREMENT
74377     /* Check to see if we need to create an sqlite_sequence table for
74378     ** keeping track of autoincrement keys.
74379     */
74380     if( p->tabFlags & TF_Autoincrement ){
74381       Db *pDb = &db->aDb[iDb];
74382       if( pDb->pSchema->pSeqTab==0 ){
74383         sqlite3NestedParse(pParse,
74384           "CREATE TABLE %Q.sqlite_sequence(name,seq)",
74385           pDb->zName
74386         );
74387       }
74388     }
74389 #endif
74390
74391     /* Reparse everything to update our internal data structures */
74392     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
74393         sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P4_DYNAMIC);
74394   }
74395
74396
74397   /* Add the table to the in-memory representation of the database.
74398   */
74399   if( db->init.busy ){
74400     Table *pOld;
74401     Schema *pSchema = p->pSchema;
74402     pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
74403                              sqlite3Strlen30(p->zName),p);
74404     if( pOld ){
74405       assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
74406       db->mallocFailed = 1;
74407       return;
74408     }
74409     pParse->pNewTable = 0;
74410     db->nTable++;
74411     db->flags |= SQLITE_InternChanges;
74412
74413 #ifndef SQLITE_OMIT_ALTERTABLE
74414     if( !p->pSelect ){
74415       const char *zName = (const char *)pParse->sNameToken.z;
74416       int nName;
74417       assert( !pSelect && pCons && pEnd );
74418       if( pCons->z==0 ){
74419         pCons = pEnd;
74420       }
74421       nName = (int)((const char *)pCons->z - zName);
74422       p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
74423     }
74424 #endif
74425   }
74426 }
74427
74428 #ifndef SQLITE_OMIT_VIEW
74429 /*
74430 ** The parser calls this routine in order to create a new VIEW
74431 */
74432 SQLITE_PRIVATE void sqlite3CreateView(
74433   Parse *pParse,     /* The parsing context */
74434   Token *pBegin,     /* The CREATE token that begins the statement */
74435   Token *pName1,     /* The token that holds the name of the view */
74436   Token *pName2,     /* The token that holds the name of the view */
74437   Select *pSelect,   /* A SELECT statement that will become the new view */
74438   int isTemp,        /* TRUE for a TEMPORARY view */
74439   int noErr          /* Suppress error messages if VIEW already exists */
74440 ){
74441   Table *p;
74442   int n;
74443   const char *z;
74444   Token sEnd;
74445   DbFixer sFix;
74446   Token *pName;
74447   int iDb;
74448   sqlite3 *db = pParse->db;
74449
74450   if( pParse->nVar>0 ){
74451     sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
74452     sqlite3SelectDelete(db, pSelect);
74453     return;
74454   }
74455   sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
74456   p = pParse->pNewTable;
74457   if( p==0 ){
74458     sqlite3SelectDelete(db, pSelect);
74459     return;
74460   }
74461   assert( pParse->nErr==0 ); /* If sqlite3StartTable return non-NULL then
74462                              ** there could not have been an error */
74463   sqlite3TwoPartName(pParse, pName1, pName2, &pName);
74464   iDb = sqlite3SchemaToIndex(db, p->pSchema);
74465   if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
74466     && sqlite3FixSelect(&sFix, pSelect)
74467   ){
74468     sqlite3SelectDelete(db, pSelect);
74469     return;
74470   }
74471
74472   /* Make a copy of the entire SELECT statement that defines the view.
74473   ** This will force all the Expr.token.z values to be dynamically
74474   ** allocated rather than point to the input string - which means that
74475   ** they will persist after the current sqlite3_exec() call returns.
74476   */
74477   p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
74478   sqlite3SelectDelete(db, pSelect);
74479   if( db->mallocFailed ){
74480     return;
74481   }
74482   if( !db->init.busy ){
74483     sqlite3ViewGetColumnNames(pParse, p);
74484   }
74485
74486   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
74487   ** the end.
74488   */
74489   sEnd = pParse->sLastToken;
74490   if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
74491     sEnd.z += sEnd.n;
74492   }
74493   sEnd.n = 0;
74494   n = (int)(sEnd.z - pBegin->z);
74495   z = pBegin->z;
74496   while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
74497   sEnd.z = &z[n-1];
74498   sEnd.n = 1;
74499
74500   /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
74501   sqlite3EndTable(pParse, 0, &sEnd, 0);
74502   return;
74503 }
74504 #endif /* SQLITE_OMIT_VIEW */
74505
74506 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
74507 /*
74508 ** The Table structure pTable is really a VIEW.  Fill in the names of
74509 ** the columns of the view in the pTable structure.  Return the number
74510 ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
74511 */
74512 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
74513   Table *pSelTab;   /* A fake table from which we get the result set */
74514   Select *pSel;     /* Copy of the SELECT that implements the view */
74515   int nErr = 0;     /* Number of errors encountered */
74516   int n;            /* Temporarily holds the number of cursors assigned */
74517   sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
74518   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
74519
74520   assert( pTable );
74521
74522 #ifndef SQLITE_OMIT_VIRTUALTABLE
74523   if( sqlite3VtabCallConnect(pParse, pTable) ){
74524     return SQLITE_ERROR;
74525   }
74526   if( IsVirtual(pTable) ) return 0;
74527 #endif
74528
74529 #ifndef SQLITE_OMIT_VIEW
74530   /* A positive nCol means the columns names for this view are
74531   ** already known.
74532   */
74533   if( pTable->nCol>0 ) return 0;
74534
74535   /* A negative nCol is a special marker meaning that we are currently
74536   ** trying to compute the column names.  If we enter this routine with
74537   ** a negative nCol, it means two or more views form a loop, like this:
74538   **
74539   **     CREATE VIEW one AS SELECT * FROM two;
74540   **     CREATE VIEW two AS SELECT * FROM one;
74541   **
74542   ** Actually, the error above is now caught prior to reaching this point.
74543   ** But the following test is still important as it does come up
74544   ** in the following:
74545   ** 
74546   **     CREATE TABLE main.ex1(a);
74547   **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
74548   **     SELECT * FROM temp.ex1;
74549   */
74550   if( pTable->nCol<0 ){
74551     sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
74552     return 1;
74553   }
74554   assert( pTable->nCol>=0 );
74555
74556   /* If we get this far, it means we need to compute the table names.
74557   ** Note that the call to sqlite3ResultSetOfSelect() will expand any
74558   ** "*" elements in the results set of the view and will assign cursors
74559   ** to the elements of the FROM clause.  But we do not want these changes
74560   ** to be permanent.  So the computation is done on a copy of the SELECT
74561   ** statement that defines the view.
74562   */
74563   assert( pTable->pSelect );
74564   pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
74565   if( pSel ){
74566     u8 enableLookaside = db->lookaside.bEnabled;
74567     n = pParse->nTab;
74568     sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
74569     pTable->nCol = -1;
74570     db->lookaside.bEnabled = 0;
74571 #ifndef SQLITE_OMIT_AUTHORIZATION
74572     xAuth = db->xAuth;
74573     db->xAuth = 0;
74574     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
74575     db->xAuth = xAuth;
74576 #else
74577     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
74578 #endif
74579     db->lookaside.bEnabled = enableLookaside;
74580     pParse->nTab = n;
74581     if( pSelTab ){
74582       assert( pTable->aCol==0 );
74583       pTable->nCol = pSelTab->nCol;
74584       pTable->aCol = pSelTab->aCol;
74585       pSelTab->nCol = 0;
74586       pSelTab->aCol = 0;
74587       sqlite3DeleteTable(pSelTab);
74588       pTable->pSchema->flags |= DB_UnresetViews;
74589     }else{
74590       pTable->nCol = 0;
74591       nErr++;
74592     }
74593     sqlite3SelectDelete(db, pSel);
74594   } else {
74595     nErr++;
74596   }
74597 #endif /* SQLITE_OMIT_VIEW */
74598   return nErr;  
74599 }
74600 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
74601
74602 #ifndef SQLITE_OMIT_VIEW
74603 /*
74604 ** Clear the column names from every VIEW in database idx.
74605 */
74606 static void sqliteViewResetAll(sqlite3 *db, int idx){
74607   HashElem *i;
74608   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
74609   for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
74610     Table *pTab = sqliteHashData(i);
74611     if( pTab->pSelect ){
74612       sqliteResetColumnNames(pTab);
74613     }
74614   }
74615   DbClearProperty(db, idx, DB_UnresetViews);
74616 }
74617 #else
74618 # define sqliteViewResetAll(A,B)
74619 #endif /* SQLITE_OMIT_VIEW */
74620
74621 /*
74622 ** This function is called by the VDBE to adjust the internal schema
74623 ** used by SQLite when the btree layer moves a table root page. The
74624 ** root-page of a table or index in database iDb has changed from iFrom
74625 ** to iTo.
74626 **
74627 ** Ticket #1728:  The symbol table might still contain information
74628 ** on tables and/or indices that are the process of being deleted.
74629 ** If you are unlucky, one of those deleted indices or tables might
74630 ** have the same rootpage number as the real table or index that is
74631 ** being moved.  So we cannot stop searching after the first match 
74632 ** because the first match might be for one of the deleted indices
74633 ** or tables and not the table/index that is actually being moved.
74634 ** We must continue looping until all tables and indices with
74635 ** rootpage==iFrom have been converted to have a rootpage of iTo
74636 ** in order to be certain that we got the right one.
74637 */
74638 #ifndef SQLITE_OMIT_AUTOVACUUM
74639 SQLITE_PRIVATE void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
74640   HashElem *pElem;
74641   Hash *pHash;
74642
74643   pHash = &pDb->pSchema->tblHash;
74644   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
74645     Table *pTab = sqliteHashData(pElem);
74646     if( pTab->tnum==iFrom ){
74647       pTab->tnum = iTo;
74648     }
74649   }
74650   pHash = &pDb->pSchema->idxHash;
74651   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
74652     Index *pIdx = sqliteHashData(pElem);
74653     if( pIdx->tnum==iFrom ){
74654       pIdx->tnum = iTo;
74655     }
74656   }
74657 }
74658 #endif
74659
74660 /*
74661 ** Write code to erase the table with root-page iTable from database iDb.
74662 ** Also write code to modify the sqlite_master table and internal schema
74663 ** if a root-page of another table is moved by the btree-layer whilst
74664 ** erasing iTable (this can happen with an auto-vacuum database).
74665 */ 
74666 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
74667   Vdbe *v = sqlite3GetVdbe(pParse);
74668   int r1 = sqlite3GetTempReg(pParse);
74669   sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
74670   sqlite3MayAbort(pParse);
74671 #ifndef SQLITE_OMIT_AUTOVACUUM
74672   /* OP_Destroy stores an in integer r1. If this integer
74673   ** is non-zero, then it is the root page number of a table moved to
74674   ** location iTable. The following code modifies the sqlite_master table to
74675   ** reflect this.
74676   **
74677   ** The "#NNN" in the SQL is a special constant that means whatever value
74678   ** is in register NNN.  See grammar rules associated with the TK_REGISTER
74679   ** token for additional information.
74680   */
74681   sqlite3NestedParse(pParse, 
74682      "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
74683      pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
74684 #endif
74685   sqlite3ReleaseTempReg(pParse, r1);
74686 }
74687
74688 /*
74689 ** Write VDBE code to erase table pTab and all associated indices on disk.
74690 ** Code to update the sqlite_master tables and internal schema definitions
74691 ** in case a root-page belonging to another table is moved by the btree layer
74692 ** is also added (this can happen with an auto-vacuum database).
74693 */
74694 static void destroyTable(Parse *pParse, Table *pTab){
74695 #ifdef SQLITE_OMIT_AUTOVACUUM
74696   Index *pIdx;
74697   int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
74698   destroyRootPage(pParse, pTab->tnum, iDb);
74699   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
74700     destroyRootPage(pParse, pIdx->tnum, iDb);
74701   }
74702 #else
74703   /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
74704   ** is not defined), then it is important to call OP_Destroy on the
74705   ** table and index root-pages in order, starting with the numerically 
74706   ** largest root-page number. This guarantees that none of the root-pages
74707   ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
74708   ** following were coded:
74709   **
74710   ** OP_Destroy 4 0
74711   ** ...
74712   ** OP_Destroy 5 0
74713   **
74714   ** and root page 5 happened to be the largest root-page number in the
74715   ** database, then root page 5 would be moved to page 4 by the 
74716   ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
74717   ** a free-list page.
74718   */
74719   int iTab = pTab->tnum;
74720   int iDestroyed = 0;
74721
74722   while( 1 ){
74723     Index *pIdx;
74724     int iLargest = 0;
74725
74726     if( iDestroyed==0 || iTab<iDestroyed ){
74727       iLargest = iTab;
74728     }
74729     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
74730       int iIdx = pIdx->tnum;
74731       assert( pIdx->pSchema==pTab->pSchema );
74732       if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
74733         iLargest = iIdx;
74734       }
74735     }
74736     if( iLargest==0 ){
74737       return;
74738     }else{
74739       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
74740       destroyRootPage(pParse, iLargest, iDb);
74741       iDestroyed = iLargest;
74742     }
74743   }
74744 #endif
74745 }
74746
74747 /*
74748 ** This routine is called to do the work of a DROP TABLE statement.
74749 ** pName is the name of the table to be dropped.
74750 */
74751 SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
74752   Table *pTab;
74753   Vdbe *v;
74754   sqlite3 *db = pParse->db;
74755   int iDb;
74756
74757   if( db->mallocFailed ){
74758     goto exit_drop_table;
74759   }
74760   assert( pParse->nErr==0 );
74761   assert( pName->nSrc==1 );
74762   if( noErr ) db->suppressErr++;
74763   pTab = sqlite3LocateTable(pParse, isView, 
74764                             pName->a[0].zName, pName->a[0].zDatabase);
74765   if( noErr ) db->suppressErr--;
74766
74767   if( pTab==0 ){
74768     goto exit_drop_table;
74769   }
74770   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
74771   assert( iDb>=0 && iDb<db->nDb );
74772
74773   /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
74774   ** it is initialized.
74775   */
74776   if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
74777     goto exit_drop_table;
74778   }
74779 #ifndef SQLITE_OMIT_AUTHORIZATION
74780   {
74781     int code;
74782     const char *zTab = SCHEMA_TABLE(iDb);
74783     const char *zDb = db->aDb[iDb].zName;
74784     const char *zArg2 = 0;
74785     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
74786       goto exit_drop_table;
74787     }
74788     if( isView ){
74789       if( !OMIT_TEMPDB && iDb==1 ){
74790         code = SQLITE_DROP_TEMP_VIEW;
74791       }else{
74792         code = SQLITE_DROP_VIEW;
74793       }
74794 #ifndef SQLITE_OMIT_VIRTUALTABLE
74795     }else if( IsVirtual(pTab) ){
74796       code = SQLITE_DROP_VTABLE;
74797       zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
74798 #endif
74799     }else{
74800       if( !OMIT_TEMPDB && iDb==1 ){
74801         code = SQLITE_DROP_TEMP_TABLE;
74802       }else{
74803         code = SQLITE_DROP_TABLE;
74804       }
74805     }
74806     if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
74807       goto exit_drop_table;
74808     }
74809     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
74810       goto exit_drop_table;
74811     }
74812   }
74813 #endif
74814   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
74815     sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
74816     goto exit_drop_table;
74817   }
74818
74819 #ifndef SQLITE_OMIT_VIEW
74820   /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
74821   ** on a table.
74822   */
74823   if( isView && pTab->pSelect==0 ){
74824     sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
74825     goto exit_drop_table;
74826   }
74827   if( !isView && pTab->pSelect ){
74828     sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
74829     goto exit_drop_table;
74830   }
74831 #endif
74832
74833   /* Generate code to remove the table from the master table
74834   ** on disk.
74835   */
74836   v = sqlite3GetVdbe(pParse);
74837   if( v ){
74838     Trigger *pTrigger;
74839     Db *pDb = &db->aDb[iDb];
74840     sqlite3BeginWriteOperation(pParse, 1, iDb);
74841
74842 #ifndef SQLITE_OMIT_VIRTUALTABLE
74843     if( IsVirtual(pTab) ){
74844       sqlite3VdbeAddOp0(v, OP_VBegin);
74845     }
74846 #endif
74847     sqlite3FkDropTable(pParse, pName, pTab);
74848
74849     /* Drop all triggers associated with the table being dropped. Code
74850     ** is generated to remove entries from sqlite_master and/or
74851     ** sqlite_temp_master if required.
74852     */
74853     pTrigger = sqlite3TriggerList(pParse, pTab);
74854     while( pTrigger ){
74855       assert( pTrigger->pSchema==pTab->pSchema || 
74856           pTrigger->pSchema==db->aDb[1].pSchema );
74857       sqlite3DropTriggerPtr(pParse, pTrigger);
74858       pTrigger = pTrigger->pNext;
74859     }
74860
74861 #ifndef SQLITE_OMIT_AUTOINCREMENT
74862     /* Remove any entries of the sqlite_sequence table associated with
74863     ** the table being dropped. This is done before the table is dropped
74864     ** at the btree level, in case the sqlite_sequence table needs to
74865     ** move as a result of the drop (can happen in auto-vacuum mode).
74866     */
74867     if( pTab->tabFlags & TF_Autoincrement ){
74868       sqlite3NestedParse(pParse,
74869         "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
74870         pDb->zName, pTab->zName
74871       );
74872     }
74873 #endif
74874
74875     /* Drop all SQLITE_MASTER table and index entries that refer to the
74876     ** table. The program name loops through the master table and deletes
74877     ** every row that refers to a table of the same name as the one being
74878     ** dropped. Triggers are handled seperately because a trigger can be
74879     ** created in the temp database that refers to a table in another
74880     ** database.
74881     */
74882     sqlite3NestedParse(pParse, 
74883         "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
74884         pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
74885
74886     /* Drop any statistics from the sqlite_stat1 table, if it exists */
74887     if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
74888       sqlite3NestedParse(pParse,
74889         "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb->zName, pTab->zName
74890       );
74891     }
74892
74893     if( !isView && !IsVirtual(pTab) ){
74894       destroyTable(pParse, pTab);
74895     }
74896
74897     /* Remove the table entry from SQLite's internal schema and modify
74898     ** the schema cookie.
74899     */
74900     if( IsVirtual(pTab) ){
74901       sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
74902     }
74903     sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
74904     sqlite3ChangeCookie(pParse, iDb);
74905   }
74906   sqliteViewResetAll(db, iDb);
74907
74908 exit_drop_table:
74909   sqlite3SrcListDelete(db, pName);
74910 }
74911
74912 /*
74913 ** This routine is called to create a new foreign key on the table
74914 ** currently under construction.  pFromCol determines which columns
74915 ** in the current table point to the foreign key.  If pFromCol==0 then
74916 ** connect the key to the last column inserted.  pTo is the name of
74917 ** the table referred to.  pToCol is a list of tables in the other
74918 ** pTo table that the foreign key points to.  flags contains all
74919 ** information about the conflict resolution algorithms specified
74920 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
74921 **
74922 ** An FKey structure is created and added to the table currently
74923 ** under construction in the pParse->pNewTable field.
74924 **
74925 ** The foreign key is set for IMMEDIATE processing.  A subsequent call
74926 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
74927 */
74928 SQLITE_PRIVATE void sqlite3CreateForeignKey(
74929   Parse *pParse,       /* Parsing context */
74930   ExprList *pFromCol,  /* Columns in this table that point to other table */
74931   Token *pTo,          /* Name of the other table */
74932   ExprList *pToCol,    /* Columns in the other table */
74933   int flags            /* Conflict resolution algorithms. */
74934 ){
74935   sqlite3 *db = pParse->db;
74936 #ifndef SQLITE_OMIT_FOREIGN_KEY
74937   FKey *pFKey = 0;
74938   FKey *pNextTo;
74939   Table *p = pParse->pNewTable;
74940   int nByte;
74941   int i;
74942   int nCol;
74943   char *z;
74944
74945   assert( pTo!=0 );
74946   if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
74947   if( pFromCol==0 ){
74948     int iCol = p->nCol-1;
74949     if( NEVER(iCol<0) ) goto fk_end;
74950     if( pToCol && pToCol->nExpr!=1 ){
74951       sqlite3ErrorMsg(pParse, "foreign key on %s"
74952          " should reference only one column of table %T",
74953          p->aCol[iCol].zName, pTo);
74954       goto fk_end;
74955     }
74956     nCol = 1;
74957   }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
74958     sqlite3ErrorMsg(pParse,
74959         "number of columns in foreign key does not match the number of "
74960         "columns in the referenced table");
74961     goto fk_end;
74962   }else{
74963     nCol = pFromCol->nExpr;
74964   }
74965   nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
74966   if( pToCol ){
74967     for(i=0; i<pToCol->nExpr; i++){
74968       nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
74969     }
74970   }
74971   pFKey = sqlite3DbMallocZero(db, nByte );
74972   if( pFKey==0 ){
74973     goto fk_end;
74974   }
74975   pFKey->pFrom = p;
74976   pFKey->pNextFrom = p->pFKey;
74977   z = (char*)&pFKey->aCol[nCol];
74978   pFKey->zTo = z;
74979   memcpy(z, pTo->z, pTo->n);
74980   z[pTo->n] = 0;
74981   sqlite3Dequote(z);
74982   z += pTo->n+1;
74983   pFKey->nCol = nCol;
74984   if( pFromCol==0 ){
74985     pFKey->aCol[0].iFrom = p->nCol-1;
74986   }else{
74987     for(i=0; i<nCol; i++){
74988       int j;
74989       for(j=0; j<p->nCol; j++){
74990         if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
74991           pFKey->aCol[i].iFrom = j;
74992           break;
74993         }
74994       }
74995       if( j>=p->nCol ){
74996         sqlite3ErrorMsg(pParse, 
74997           "unknown column \"%s\" in foreign key definition", 
74998           pFromCol->a[i].zName);
74999         goto fk_end;
75000       }
75001     }
75002   }
75003   if( pToCol ){
75004     for(i=0; i<nCol; i++){
75005       int n = sqlite3Strlen30(pToCol->a[i].zName);
75006       pFKey->aCol[i].zCol = z;
75007       memcpy(z, pToCol->a[i].zName, n);
75008       z[n] = 0;
75009       z += n+1;
75010     }
75011   }
75012   pFKey->isDeferred = 0;
75013   pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
75014   pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
75015
75016   pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash, 
75017       pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
75018   );
75019   if( pNextTo==pFKey ){
75020     db->mallocFailed = 1;
75021     goto fk_end;
75022   }
75023   if( pNextTo ){
75024     assert( pNextTo->pPrevTo==0 );
75025     pFKey->pNextTo = pNextTo;
75026     pNextTo->pPrevTo = pFKey;
75027   }
75028
75029   /* Link the foreign key to the table as the last step.
75030   */
75031   p->pFKey = pFKey;
75032   pFKey = 0;
75033
75034 fk_end:
75035   sqlite3DbFree(db, pFKey);
75036 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
75037   sqlite3ExprListDelete(db, pFromCol);
75038   sqlite3ExprListDelete(db, pToCol);
75039 }
75040
75041 /*
75042 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
75043 ** clause is seen as part of a foreign key definition.  The isDeferred
75044 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
75045 ** The behavior of the most recently created foreign key is adjusted
75046 ** accordingly.
75047 */
75048 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
75049 #ifndef SQLITE_OMIT_FOREIGN_KEY
75050   Table *pTab;
75051   FKey *pFKey;
75052   if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
75053   assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
75054   pFKey->isDeferred = (u8)isDeferred;
75055 #endif
75056 }
75057
75058 /*
75059 ** Generate code that will erase and refill index *pIdx.  This is
75060 ** used to initialize a newly created index or to recompute the
75061 ** content of an index in response to a REINDEX command.
75062 **
75063 ** if memRootPage is not negative, it means that the index is newly
75064 ** created.  The register specified by memRootPage contains the
75065 ** root page number of the index.  If memRootPage is negative, then
75066 ** the index already exists and must be cleared before being refilled and
75067 ** the root page number of the index is taken from pIndex->tnum.
75068 */
75069 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
75070   Table *pTab = pIndex->pTable;  /* The table that is indexed */
75071   int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
75072   int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
75073   int addr1;                     /* Address of top of loop */
75074   int tnum;                      /* Root page of index */
75075   Vdbe *v;                       /* Generate code into this virtual machine */
75076   KeyInfo *pKey;                 /* KeyInfo for index */
75077   int regIdxKey;                 /* Registers containing the index key */
75078   int regRecord;                 /* Register holding assemblied index record */
75079   sqlite3 *db = pParse->db;      /* The database connection */
75080   int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
75081
75082 #ifndef SQLITE_OMIT_AUTHORIZATION
75083   if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
75084       db->aDb[iDb].zName ) ){
75085     return;
75086   }
75087 #endif
75088
75089   /* Require a write-lock on the table to perform this operation */
75090   sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
75091
75092   v = sqlite3GetVdbe(pParse);
75093   if( v==0 ) return;
75094   if( memRootPage>=0 ){
75095     tnum = memRootPage;
75096   }else{
75097     tnum = pIndex->tnum;
75098     sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
75099   }
75100   pKey = sqlite3IndexKeyinfo(pParse, pIndex);
75101   sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, 
75102                     (char *)pKey, P4_KEYINFO_HANDOFF);
75103   if( memRootPage>=0 ){
75104     sqlite3VdbeChangeP5(v, 1);
75105   }
75106   sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
75107   addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
75108   regRecord = sqlite3GetTempReg(pParse);
75109   regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
75110   if( pIndex->onError!=OE_None ){
75111     const int regRowid = regIdxKey + pIndex->nColumn;
75112     const int j2 = sqlite3VdbeCurrentAddr(v) + 2;
75113     void * const pRegKey = SQLITE_INT_TO_PTR(regIdxKey);
75114
75115     /* The registers accessed by the OP_IsUnique opcode were allocated
75116     ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()
75117     ** call above. Just before that function was freed they were released
75118     ** (made available to the compiler for reuse) using 
75119     ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique
75120     ** opcode use the values stored within seems dangerous. However, since
75121     ** we can be sure that no other temp registers have been allocated
75122     ** since sqlite3ReleaseTempRange() was called, it is safe to do so.
75123     */
75124     sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);
75125     sqlite3HaltConstraint(
75126         pParse, OE_Abort, "indexed columns are not unique", P4_STATIC);
75127   }
75128   sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
75129   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
75130   sqlite3ReleaseTempReg(pParse, regRecord);
75131   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
75132   sqlite3VdbeJumpHere(v, addr1);
75133   sqlite3VdbeAddOp1(v, OP_Close, iTab);
75134   sqlite3VdbeAddOp1(v, OP_Close, iIdx);
75135 }
75136
75137 /*
75138 ** Create a new index for an SQL table.  pName1.pName2 is the name of the index 
75139 ** and pTblList is the name of the table that is to be indexed.  Both will 
75140 ** be NULL for a primary key or an index that is created to satisfy a
75141 ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
75142 ** as the table to be indexed.  pParse->pNewTable is a table that is
75143 ** currently being constructed by a CREATE TABLE statement.
75144 **
75145 ** pList is a list of columns to be indexed.  pList will be NULL if this
75146 ** is a primary key or unique-constraint on the most recent column added
75147 ** to the table currently under construction.  
75148 **
75149 ** If the index is created successfully, return a pointer to the new Index
75150 ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
75151 ** as the tables primary key (Index.autoIndex==2).
75152 */
75153 SQLITE_PRIVATE Index *sqlite3CreateIndex(
75154   Parse *pParse,     /* All information about this parse */
75155   Token *pName1,     /* First part of index name. May be NULL */
75156   Token *pName2,     /* Second part of index name. May be NULL */
75157   SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
75158   ExprList *pList,   /* A list of columns to be indexed */
75159   int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
75160   Token *pStart,     /* The CREATE token that begins this statement */
75161   Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
75162   int sortOrder,     /* Sort order of primary key when pList==NULL */
75163   int ifNotExist     /* Omit error if index already exists */
75164 ){
75165   Index *pRet = 0;     /* Pointer to return */
75166   Table *pTab = 0;     /* Table to be indexed */
75167   Index *pIndex = 0;   /* The index to be created */
75168   char *zName = 0;     /* Name of the index */
75169   int nName;           /* Number of characters in zName */
75170   int i, j;
75171   Token nullId;        /* Fake token for an empty ID list */
75172   DbFixer sFix;        /* For assigning database names to pTable */
75173   int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
75174   sqlite3 *db = pParse->db;
75175   Db *pDb;             /* The specific table containing the indexed database */
75176   int iDb;             /* Index of the database that is being written */
75177   Token *pName = 0;    /* Unqualified name of the index to create */
75178   struct ExprList_item *pListItem; /* For looping over pList */
75179   int nCol;
75180   int nExtra = 0;
75181   char *zExtra;
75182
75183   assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
75184   assert( pParse->nErr==0 );      /* Never called with prior errors */
75185   if( db->mallocFailed || IN_DECLARE_VTAB ){
75186     goto exit_create_index;
75187   }
75188   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
75189     goto exit_create_index;
75190   }
75191
75192   /*
75193   ** Find the table that is to be indexed.  Return early if not found.
75194   */
75195   if( pTblName!=0 ){
75196
75197     /* Use the two-part index name to determine the database 
75198     ** to search for the table. 'Fix' the table name to this db
75199     ** before looking up the table.
75200     */
75201     assert( pName1 && pName2 );
75202     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
75203     if( iDb<0 ) goto exit_create_index;
75204
75205 #ifndef SQLITE_OMIT_TEMPDB
75206     /* If the index name was unqualified, check if the the table
75207     ** is a temp table. If so, set the database to 1. Do not do this
75208     ** if initialising a database schema.
75209     */
75210     if( !db->init.busy ){
75211       pTab = sqlite3SrcListLookup(pParse, pTblName);
75212       if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
75213         iDb = 1;
75214       }
75215     }
75216 #endif
75217
75218     if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
75219         sqlite3FixSrcList(&sFix, pTblName)
75220     ){
75221       /* Because the parser constructs pTblName from a single identifier,
75222       ** sqlite3FixSrcList can never fail. */
75223       assert(0);
75224     }
75225     pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName, 
75226         pTblName->a[0].zDatabase);
75227     if( !pTab || db->mallocFailed ) goto exit_create_index;
75228     assert( db->aDb[iDb].pSchema==pTab->pSchema );
75229   }else{
75230     assert( pName==0 );
75231     pTab = pParse->pNewTable;
75232     if( !pTab ) goto exit_create_index;
75233     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
75234   }
75235   pDb = &db->aDb[iDb];
75236
75237   assert( pTab!=0 );
75238   assert( pParse->nErr==0 );
75239   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 
75240        && memcmp(&pTab->zName[7],"altertab_",9)!=0 ){
75241     sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
75242     goto exit_create_index;
75243   }
75244 #ifndef SQLITE_OMIT_VIEW
75245   if( pTab->pSelect ){
75246     sqlite3ErrorMsg(pParse, "views may not be indexed");
75247     goto exit_create_index;
75248   }
75249 #endif
75250 #ifndef SQLITE_OMIT_VIRTUALTABLE
75251   if( IsVirtual(pTab) ){
75252     sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
75253     goto exit_create_index;
75254   }
75255 #endif
75256
75257   /*
75258   ** Find the name of the index.  Make sure there is not already another
75259   ** index or table with the same name.  
75260   **
75261   ** Exception:  If we are reading the names of permanent indices from the
75262   ** sqlite_master table (because some other process changed the schema) and
75263   ** one of the index names collides with the name of a temporary table or
75264   ** index, then we will continue to process this index.
75265   **
75266   ** If pName==0 it means that we are
75267   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
75268   ** own name.
75269   */
75270   if( pName ){
75271     zName = sqlite3NameFromToken(db, pName);
75272     if( zName==0 ) goto exit_create_index;
75273     if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
75274       goto exit_create_index;
75275     }
75276     if( !db->init.busy ){
75277       if( sqlite3FindTable(db, zName, 0)!=0 ){
75278         sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
75279         goto exit_create_index;
75280       }
75281     }
75282     if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
75283       if( !ifNotExist ){
75284         sqlite3ErrorMsg(pParse, "index %s already exists", zName);
75285       }
75286       goto exit_create_index;
75287     }
75288   }else{
75289     int n;
75290     Index *pLoop;
75291     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
75292     zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
75293     if( zName==0 ){
75294       goto exit_create_index;
75295     }
75296   }
75297
75298   /* Check for authorization to create an index.
75299   */
75300 #ifndef SQLITE_OMIT_AUTHORIZATION
75301   {
75302     const char *zDb = pDb->zName;
75303     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
75304       goto exit_create_index;
75305     }
75306     i = SQLITE_CREATE_INDEX;
75307     if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
75308     if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
75309       goto exit_create_index;
75310     }
75311   }
75312 #endif
75313
75314   /* If pList==0, it means this routine was called to make a primary
75315   ** key out of the last column added to the table under construction.
75316   ** So create a fake list to simulate this.
75317   */
75318   if( pList==0 ){
75319     nullId.z = pTab->aCol[pTab->nCol-1].zName;
75320     nullId.n = sqlite3Strlen30((char*)nullId.z);
75321     pList = sqlite3ExprListAppend(pParse, 0, 0);
75322     if( pList==0 ) goto exit_create_index;
75323     sqlite3ExprListSetName(pParse, pList, &nullId, 0);
75324     pList->a[0].sortOrder = (u8)sortOrder;
75325   }
75326
75327   /* Figure out how many bytes of space are required to store explicitly
75328   ** specified collation sequence names.
75329   */
75330   for(i=0; i<pList->nExpr; i++){
75331     Expr *pExpr = pList->a[i].pExpr;
75332     if( pExpr ){
75333       CollSeq *pColl = pExpr->pColl;
75334       /* Either pColl!=0 or there was an OOM failure.  But if an OOM
75335       ** failure we have quit before reaching this point. */
75336       if( ALWAYS(pColl) ){
75337         nExtra += (1 + sqlite3Strlen30(pColl->zName));
75338       }
75339     }
75340   }
75341
75342   /* 
75343   ** Allocate the index structure. 
75344   */
75345   nName = sqlite3Strlen30(zName);
75346   nCol = pList->nExpr;
75347   pIndex = sqlite3DbMallocZero(db, 
75348       sizeof(Index) +              /* Index structure  */
75349       sizeof(int)*nCol +           /* Index.aiColumn   */
75350       sizeof(int)*(nCol+1) +       /* Index.aiRowEst   */
75351       sizeof(char *)*nCol +        /* Index.azColl     */
75352       sizeof(u8)*nCol +            /* Index.aSortOrder */
75353       nName + 1 +                  /* Index.zName      */
75354       nExtra                       /* Collation sequence names */
75355   );
75356   if( db->mallocFailed ){
75357     goto exit_create_index;
75358   }
75359   pIndex->azColl = (char**)(&pIndex[1]);
75360   pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
75361   pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
75362   pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
75363   pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
75364   zExtra = (char *)(&pIndex->zName[nName+1]);
75365   memcpy(pIndex->zName, zName, nName+1);
75366   pIndex->pTable = pTab;
75367   pIndex->nColumn = pList->nExpr;
75368   pIndex->onError = (u8)onError;
75369   pIndex->autoIndex = (u8)(pName==0);
75370   pIndex->pSchema = db->aDb[iDb].pSchema;
75371
75372   /* Check to see if we should honor DESC requests on index columns
75373   */
75374   if( pDb->pSchema->file_format>=4 ){
75375     sortOrderMask = -1;   /* Honor DESC */
75376   }else{
75377     sortOrderMask = 0;    /* Ignore DESC */
75378   }
75379
75380   /* Scan the names of the columns of the table to be indexed and
75381   ** load the column indices into the Index structure.  Report an error
75382   ** if any column is not found.
75383   **
75384   ** TODO:  Add a test to make sure that the same column is not named
75385   ** more than once within the same index.  Only the first instance of
75386   ** the column will ever be used by the optimizer.  Note that using the
75387   ** same column more than once cannot be an error because that would 
75388   ** break backwards compatibility - it needs to be a warning.
75389   */
75390   for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
75391     const char *zColName = pListItem->zName;
75392     Column *pTabCol;
75393     int requestedSortOrder;
75394     char *zColl;                   /* Collation sequence name */
75395
75396     for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
75397       if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
75398     }
75399     if( j>=pTab->nCol ){
75400       sqlite3ErrorMsg(pParse, "table %s has no column named %s",
75401         pTab->zName, zColName);
75402       pParse->checkSchema = 1;
75403       goto exit_create_index;
75404     }
75405     pIndex->aiColumn[i] = j;
75406     /* Justification of the ALWAYS(pListItem->pExpr->pColl):  Because of
75407     ** the way the "idxlist" non-terminal is constructed by the parser,
75408     ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl
75409     ** must exist or else there must have been an OOM error.  But if there
75410     ** was an OOM error, we would never reach this point. */
75411     if( pListItem->pExpr && ALWAYS(pListItem->pExpr->pColl) ){
75412       int nColl;
75413       zColl = pListItem->pExpr->pColl->zName;
75414       nColl = sqlite3Strlen30(zColl) + 1;
75415       assert( nExtra>=nColl );
75416       memcpy(zExtra, zColl, nColl);
75417       zColl = zExtra;
75418       zExtra += nColl;
75419       nExtra -= nColl;
75420     }else{
75421       zColl = pTab->aCol[j].zColl;
75422       if( !zColl ){
75423         zColl = db->pDfltColl->zName;
75424       }
75425     }
75426     if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
75427       goto exit_create_index;
75428     }
75429     pIndex->azColl[i] = zColl;
75430     requestedSortOrder = pListItem->sortOrder & sortOrderMask;
75431     pIndex->aSortOrder[i] = (u8)requestedSortOrder;
75432   }
75433   sqlite3DefaultRowEst(pIndex);
75434
75435   if( pTab==pParse->pNewTable ){
75436     /* This routine has been called to create an automatic index as a
75437     ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
75438     ** a PRIMARY KEY or UNIQUE clause following the column definitions.
75439     ** i.e. one of:
75440     **
75441     ** CREATE TABLE t(x PRIMARY KEY, y);
75442     ** CREATE TABLE t(x, y, UNIQUE(x, y));
75443     **
75444     ** Either way, check to see if the table already has such an index. If
75445     ** so, don't bother creating this one. This only applies to
75446     ** automatically created indices. Users can do as they wish with
75447     ** explicit indices.
75448     **
75449     ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
75450     ** (and thus suppressing the second one) even if they have different
75451     ** sort orders.
75452     **
75453     ** If there are different collating sequences or if the columns of
75454     ** the constraint occur in different orders, then the constraints are
75455     ** considered distinct and both result in separate indices.
75456     */
75457     Index *pIdx;
75458     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
75459       int k;
75460       assert( pIdx->onError!=OE_None );
75461       assert( pIdx->autoIndex );
75462       assert( pIndex->onError!=OE_None );
75463
75464       if( pIdx->nColumn!=pIndex->nColumn ) continue;
75465       for(k=0; k<pIdx->nColumn; k++){
75466         const char *z1;
75467         const char *z2;
75468         if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
75469         z1 = pIdx->azColl[k];
75470         z2 = pIndex->azColl[k];
75471         if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
75472       }
75473       if( k==pIdx->nColumn ){
75474         if( pIdx->onError!=pIndex->onError ){
75475           /* This constraint creates the same index as a previous
75476           ** constraint specified somewhere in the CREATE TABLE statement.
75477           ** However the ON CONFLICT clauses are different. If both this 
75478           ** constraint and the previous equivalent constraint have explicit
75479           ** ON CONFLICT clauses this is an error. Otherwise, use the
75480           ** explicitly specified behaviour for the index.
75481           */
75482           if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
75483             sqlite3ErrorMsg(pParse, 
75484                 "conflicting ON CONFLICT clauses specified", 0);
75485           }
75486           if( pIdx->onError==OE_Default ){
75487             pIdx->onError = pIndex->onError;
75488           }
75489         }
75490         goto exit_create_index;
75491       }
75492     }
75493   }
75494
75495   /* Link the new Index structure to its table and to the other
75496   ** in-memory database structures. 
75497   */
75498   if( db->init.busy ){
75499     Index *p;
75500     p = sqlite3HashInsert(&pIndex->pSchema->idxHash, 
75501                           pIndex->zName, sqlite3Strlen30(pIndex->zName),
75502                           pIndex);
75503     if( p ){
75504       assert( p==pIndex );  /* Malloc must have failed */
75505       db->mallocFailed = 1;
75506       goto exit_create_index;
75507     }
75508     db->flags |= SQLITE_InternChanges;
75509     if( pTblName!=0 ){
75510       pIndex->tnum = db->init.newTnum;
75511     }
75512   }
75513
75514   /* If the db->init.busy is 0 then create the index on disk.  This
75515   ** involves writing the index into the master table and filling in the
75516   ** index with the current table contents.
75517   **
75518   ** The db->init.busy is 0 when the user first enters a CREATE INDEX 
75519   ** command.  db->init.busy is 1 when a database is opened and 
75520   ** CREATE INDEX statements are read out of the master table.  In
75521   ** the latter case the index already exists on disk, which is why
75522   ** we don't want to recreate it.
75523   **
75524   ** If pTblName==0 it means this index is generated as a primary key
75525   ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
75526   ** has just been created, it contains no data and the index initialization
75527   ** step can be skipped.
75528   */
75529   else{ /* if( db->init.busy==0 ) */
75530     Vdbe *v;
75531     char *zStmt;
75532     int iMem = ++pParse->nMem;
75533
75534     v = sqlite3GetVdbe(pParse);
75535     if( v==0 ) goto exit_create_index;
75536
75537
75538     /* Create the rootpage for the index
75539     */
75540     sqlite3BeginWriteOperation(pParse, 1, iDb);
75541     sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
75542
75543     /* Gather the complete text of the CREATE INDEX statement into
75544     ** the zStmt variable
75545     */
75546     if( pStart ){
75547       assert( pEnd!=0 );
75548       /* A named index with an explicit CREATE INDEX statement */
75549       zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
75550         onError==OE_None ? "" : " UNIQUE",
75551         pEnd->z - pName->z + 1,
75552         pName->z);
75553     }else{
75554       /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
75555       /* zStmt = sqlite3MPrintf(""); */
75556       zStmt = 0;
75557     }
75558
75559     /* Add an entry in sqlite_master for this index
75560     */
75561     sqlite3NestedParse(pParse, 
75562         "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
75563         db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
75564         pIndex->zName,
75565         pTab->zName,
75566         iMem,
75567         zStmt
75568     );
75569     sqlite3DbFree(db, zStmt);
75570
75571     /* Fill the index with data and reparse the schema. Code an OP_Expire
75572     ** to invalidate all pre-compiled statements.
75573     */
75574     if( pTblName ){
75575       sqlite3RefillIndex(pParse, pIndex, iMem);
75576       sqlite3ChangeCookie(pParse, iDb);
75577       sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
75578          sqlite3MPrintf(db, "name='%q'", pIndex->zName), P4_DYNAMIC);
75579       sqlite3VdbeAddOp1(v, OP_Expire, 0);
75580     }
75581   }
75582
75583   /* When adding an index to the list of indices for a table, make
75584   ** sure all indices labeled OE_Replace come after all those labeled
75585   ** OE_Ignore.  This is necessary for the correct constraint check
75586   ** processing (in sqlite3GenerateConstraintChecks()) as part of
75587   ** UPDATE and INSERT statements.  
75588   */
75589   if( db->init.busy || pTblName==0 ){
75590     if( onError!=OE_Replace || pTab->pIndex==0
75591          || pTab->pIndex->onError==OE_Replace){
75592       pIndex->pNext = pTab->pIndex;
75593       pTab->pIndex = pIndex;
75594     }else{
75595       Index *pOther = pTab->pIndex;
75596       while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
75597         pOther = pOther->pNext;
75598       }
75599       pIndex->pNext = pOther->pNext;
75600       pOther->pNext = pIndex;
75601     }
75602     pRet = pIndex;
75603     pIndex = 0;
75604   }
75605
75606   /* Clean up before exiting */
75607 exit_create_index:
75608   if( pIndex ){
75609     sqlite3_free(pIndex->zColAff);
75610     sqlite3DbFree(db, pIndex);
75611   }
75612   sqlite3ExprListDelete(db, pList);
75613   sqlite3SrcListDelete(db, pTblName);
75614   sqlite3DbFree(db, zName);
75615   return pRet;
75616 }
75617
75618 /*
75619 ** Fill the Index.aiRowEst[] array with default information - information
75620 ** to be used when we have not run the ANALYZE command.
75621 **
75622 ** aiRowEst[0] is suppose to contain the number of elements in the index.
75623 ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
75624 ** number of rows in the table that match any particular value of the
75625 ** first column of the index.  aiRowEst[2] is an estimate of the number
75626 ** of rows that match any particular combiniation of the first 2 columns
75627 ** of the index.  And so forth.  It must always be the case that
75628 *
75629 **           aiRowEst[N]<=aiRowEst[N-1]
75630 **           aiRowEst[N]>=1
75631 **
75632 ** Apart from that, we have little to go on besides intuition as to
75633 ** how aiRowEst[] should be initialized.  The numbers generated here
75634 ** are based on typical values found in actual indices.
75635 */
75636 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
75637   unsigned *a = pIdx->aiRowEst;
75638   int i;
75639   assert( a!=0 );
75640   a[0] = 1000000;
75641   for(i=pIdx->nColumn; i>=5; i--){
75642     a[i] = 5;
75643   }
75644   while( i>=1 ){
75645     a[i] = 11 - i;
75646     i--;
75647   }
75648   if( pIdx->onError!=OE_None ){
75649     a[pIdx->nColumn] = 1;
75650   }
75651 }
75652
75653 /*
75654 ** This routine will drop an existing named index.  This routine
75655 ** implements the DROP INDEX statement.
75656 */
75657 SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
75658   Index *pIndex;
75659   Vdbe *v;
75660   sqlite3 *db = pParse->db;
75661   int iDb;
75662
75663   assert( pParse->nErr==0 );   /* Never called with prior errors */
75664   if( db->mallocFailed ){
75665     goto exit_drop_index;
75666   }
75667   assert( pName->nSrc==1 );
75668   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
75669     goto exit_drop_index;
75670   }
75671   pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
75672   if( pIndex==0 ){
75673     if( !ifExists ){
75674       sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
75675     }
75676     pParse->checkSchema = 1;
75677     goto exit_drop_index;
75678   }
75679   if( pIndex->autoIndex ){
75680     sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
75681       "or PRIMARY KEY constraint cannot be dropped", 0);
75682     goto exit_drop_index;
75683   }
75684   iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
75685 #ifndef SQLITE_OMIT_AUTHORIZATION
75686   {
75687     int code = SQLITE_DROP_INDEX;
75688     Table *pTab = pIndex->pTable;
75689     const char *zDb = db->aDb[iDb].zName;
75690     const char *zTab = SCHEMA_TABLE(iDb);
75691     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
75692       goto exit_drop_index;
75693     }
75694     if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
75695     if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
75696       goto exit_drop_index;
75697     }
75698   }
75699 #endif
75700
75701   /* Generate code to remove the index and from the master table */
75702   v = sqlite3GetVdbe(pParse);
75703   if( v ){
75704     sqlite3BeginWriteOperation(pParse, 1, iDb);
75705     sqlite3NestedParse(pParse,
75706        "DELETE FROM %Q.%s WHERE name=%Q",
75707        db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
75708        pIndex->zName
75709     );
75710     if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
75711       sqlite3NestedParse(pParse,
75712         "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q",
75713         db->aDb[iDb].zName, pIndex->zName
75714       );
75715     }
75716     sqlite3ChangeCookie(pParse, iDb);
75717     destroyRootPage(pParse, pIndex->tnum, iDb);
75718     sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
75719   }
75720
75721 exit_drop_index:
75722   sqlite3SrcListDelete(db, pName);
75723 }
75724
75725 /*
75726 ** pArray is a pointer to an array of objects.  Each object in the
75727 ** array is szEntry bytes in size.  This routine allocates a new
75728 ** object on the end of the array.
75729 **
75730 ** *pnEntry is the number of entries already in use.  *pnAlloc is
75731 ** the previously allocated size of the array.  initSize is the
75732 ** suggested initial array size allocation.
75733 **
75734 ** The index of the new entry is returned in *pIdx.
75735 **
75736 ** This routine returns a pointer to the array of objects.  This
75737 ** might be the same as the pArray parameter or it might be a different
75738 ** pointer if the array was resized.
75739 */
75740 SQLITE_PRIVATE void *sqlite3ArrayAllocate(
75741   sqlite3 *db,      /* Connection to notify of malloc failures */
75742   void *pArray,     /* Array of objects.  Might be reallocated */
75743   int szEntry,      /* Size of each object in the array */
75744   int initSize,     /* Suggested initial allocation, in elements */
75745   int *pnEntry,     /* Number of objects currently in use */
75746   int *pnAlloc,     /* Current size of the allocation, in elements */
75747   int *pIdx         /* Write the index of a new slot here */
75748 ){
75749   char *z;
75750   if( *pnEntry >= *pnAlloc ){
75751     void *pNew;
75752     int newSize;
75753     newSize = (*pnAlloc)*2 + initSize;
75754     pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
75755     if( pNew==0 ){
75756       *pIdx = -1;
75757       return pArray;
75758     }
75759     *pnAlloc = sqlite3DbMallocSize(db, pNew)/szEntry;
75760     pArray = pNew;
75761   }
75762   z = (char*)pArray;
75763   memset(&z[*pnEntry * szEntry], 0, szEntry);
75764   *pIdx = *pnEntry;
75765   ++*pnEntry;
75766   return pArray;
75767 }
75768
75769 /*
75770 ** Append a new element to the given IdList.  Create a new IdList if
75771 ** need be.
75772 **
75773 ** A new IdList is returned, or NULL if malloc() fails.
75774 */
75775 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
75776   int i;
75777   if( pList==0 ){
75778     pList = sqlite3DbMallocZero(db, sizeof(IdList) );
75779     if( pList==0 ) return 0;
75780     pList->nAlloc = 0;
75781   }
75782   pList->a = sqlite3ArrayAllocate(
75783       db,
75784       pList->a,
75785       sizeof(pList->a[0]),
75786       5,
75787       &pList->nId,
75788       &pList->nAlloc,
75789       &i
75790   );
75791   if( i<0 ){
75792     sqlite3IdListDelete(db, pList);
75793     return 0;
75794   }
75795   pList->a[i].zName = sqlite3NameFromToken(db, pToken);
75796   return pList;
75797 }
75798
75799 /*
75800 ** Delete an IdList.
75801 */
75802 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
75803   int i;
75804   if( pList==0 ) return;
75805   for(i=0; i<pList->nId; i++){
75806     sqlite3DbFree(db, pList->a[i].zName);
75807   }
75808   sqlite3DbFree(db, pList->a);
75809   sqlite3DbFree(db, pList);
75810 }
75811
75812 /*
75813 ** Return the index in pList of the identifier named zId.  Return -1
75814 ** if not found.
75815 */
75816 SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
75817   int i;
75818   if( pList==0 ) return -1;
75819   for(i=0; i<pList->nId; i++){
75820     if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
75821   }
75822   return -1;
75823 }
75824
75825 /*
75826 ** Expand the space allocated for the given SrcList object by
75827 ** creating nExtra new slots beginning at iStart.  iStart is zero based.
75828 ** New slots are zeroed.
75829 **
75830 ** For example, suppose a SrcList initially contains two entries: A,B.
75831 ** To append 3 new entries onto the end, do this:
75832 **
75833 **    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
75834 **
75835 ** After the call above it would contain:  A, B, nil, nil, nil.
75836 ** If the iStart argument had been 1 instead of 2, then the result
75837 ** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
75838 ** the iStart value would be 0.  The result then would
75839 ** be: nil, nil, nil, A, B.
75840 **
75841 ** If a memory allocation fails the SrcList is unchanged.  The
75842 ** db->mallocFailed flag will be set to true.
75843 */
75844 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
75845   sqlite3 *db,       /* Database connection to notify of OOM errors */
75846   SrcList *pSrc,     /* The SrcList to be enlarged */
75847   int nExtra,        /* Number of new slots to add to pSrc->a[] */
75848   int iStart         /* Index in pSrc->a[] of first new slot */
75849 ){
75850   int i;
75851
75852   /* Sanity checking on calling parameters */
75853   assert( iStart>=0 );
75854   assert( nExtra>=1 );
75855   assert( pSrc!=0 );
75856   assert( iStart<=pSrc->nSrc );
75857
75858   /* Allocate additional space if needed */
75859   if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
75860     SrcList *pNew;
75861     int nAlloc = pSrc->nSrc+nExtra;
75862     int nGot;
75863     pNew = sqlite3DbRealloc(db, pSrc,
75864                sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
75865     if( pNew==0 ){
75866       assert( db->mallocFailed );
75867       return pSrc;
75868     }
75869     pSrc = pNew;
75870     nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
75871     pSrc->nAlloc = (u16)nGot;
75872   }
75873
75874   /* Move existing slots that come after the newly inserted slots
75875   ** out of the way */
75876   for(i=pSrc->nSrc-1; i>=iStart; i--){
75877     pSrc->a[i+nExtra] = pSrc->a[i];
75878   }
75879   pSrc->nSrc += (i16)nExtra;
75880
75881   /* Zero the newly allocated slots */
75882   memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
75883   for(i=iStart; i<iStart+nExtra; i++){
75884     pSrc->a[i].iCursor = -1;
75885   }
75886
75887   /* Return a pointer to the enlarged SrcList */
75888   return pSrc;
75889 }
75890
75891
75892 /*
75893 ** Append a new table name to the given SrcList.  Create a new SrcList if
75894 ** need be.  A new entry is created in the SrcList even if pTable is NULL.
75895 **
75896 ** A SrcList is returned, or NULL if there is an OOM error.  The returned
75897 ** SrcList might be the same as the SrcList that was input or it might be
75898 ** a new one.  If an OOM error does occurs, then the prior value of pList
75899 ** that is input to this routine is automatically freed.
75900 **
75901 ** If pDatabase is not null, it means that the table has an optional
75902 ** database name prefix.  Like this:  "database.table".  The pDatabase
75903 ** points to the table name and the pTable points to the database name.
75904 ** The SrcList.a[].zName field is filled with the table name which might
75905 ** come from pTable (if pDatabase is NULL) or from pDatabase.  
75906 ** SrcList.a[].zDatabase is filled with the database name from pTable,
75907 ** or with NULL if no database is specified.
75908 **
75909 ** In other words, if call like this:
75910 **
75911 **         sqlite3SrcListAppend(D,A,B,0);
75912 **
75913 ** Then B is a table name and the database name is unspecified.  If called
75914 ** like this:
75915 **
75916 **         sqlite3SrcListAppend(D,A,B,C);
75917 **
75918 ** Then C is the table name and B is the database name.  If C is defined
75919 ** then so is B.  In other words, we never have a case where:
75920 **
75921 **         sqlite3SrcListAppend(D,A,0,C);
75922 **
75923 ** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
75924 ** before being added to the SrcList.
75925 */
75926 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
75927   sqlite3 *db,        /* Connection to notify of malloc failures */
75928   SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
75929   Token *pTable,      /* Table to append */
75930   Token *pDatabase    /* Database of the table */
75931 ){
75932   struct SrcList_item *pItem;
75933   assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
75934   if( pList==0 ){
75935     pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
75936     if( pList==0 ) return 0;
75937     pList->nAlloc = 1;
75938   }
75939   pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
75940   if( db->mallocFailed ){
75941     sqlite3SrcListDelete(db, pList);
75942     return 0;
75943   }
75944   pItem = &pList->a[pList->nSrc-1];
75945   if( pDatabase && pDatabase->z==0 ){
75946     pDatabase = 0;
75947   }
75948   if( pDatabase ){
75949     Token *pTemp = pDatabase;
75950     pDatabase = pTable;
75951     pTable = pTemp;
75952   }
75953   pItem->zName = sqlite3NameFromToken(db, pTable);
75954   pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
75955   return pList;
75956 }
75957
75958 /*
75959 ** Assign VdbeCursor index numbers to all tables in a SrcList
75960 */
75961 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
75962   int i;
75963   struct SrcList_item *pItem;
75964   assert(pList || pParse->db->mallocFailed );
75965   if( pList ){
75966     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
75967       if( pItem->iCursor>=0 ) break;
75968       pItem->iCursor = pParse->nTab++;
75969       if( pItem->pSelect ){
75970         sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
75971       }
75972     }
75973   }
75974 }
75975
75976 /*
75977 ** Delete an entire SrcList including all its substructure.
75978 */
75979 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
75980   int i;
75981   struct SrcList_item *pItem;
75982   if( pList==0 ) return;
75983   for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
75984     sqlite3DbFree(db, pItem->zDatabase);
75985     sqlite3DbFree(db, pItem->zName);
75986     sqlite3DbFree(db, pItem->zAlias);
75987     sqlite3DbFree(db, pItem->zIndex);
75988     sqlite3DeleteTable(pItem->pTab);
75989     sqlite3SelectDelete(db, pItem->pSelect);
75990     sqlite3ExprDelete(db, pItem->pOn);
75991     sqlite3IdListDelete(db, pItem->pUsing);
75992   }
75993   sqlite3DbFree(db, pList);
75994 }
75995
75996 /*
75997 ** This routine is called by the parser to add a new term to the
75998 ** end of a growing FROM clause.  The "p" parameter is the part of
75999 ** the FROM clause that has already been constructed.  "p" is NULL
76000 ** if this is the first term of the FROM clause.  pTable and pDatabase
76001 ** are the name of the table and database named in the FROM clause term.
76002 ** pDatabase is NULL if the database name qualifier is missing - the
76003 ** usual case.  If the term has a alias, then pAlias points to the
76004 ** alias token.  If the term is a subquery, then pSubquery is the
76005 ** SELECT statement that the subquery encodes.  The pTable and
76006 ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
76007 ** parameters are the content of the ON and USING clauses.
76008 **
76009 ** Return a new SrcList which encodes is the FROM with the new
76010 ** term added.
76011 */
76012 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
76013   Parse *pParse,          /* Parsing context */
76014   SrcList *p,             /* The left part of the FROM clause already seen */
76015   Token *pTable,          /* Name of the table to add to the FROM clause */
76016   Token *pDatabase,       /* Name of the database containing pTable */
76017   Token *pAlias,          /* The right-hand side of the AS subexpression */
76018   Select *pSubquery,      /* A subquery used in place of a table name */
76019   Expr *pOn,              /* The ON clause of a join */
76020   IdList *pUsing          /* The USING clause of a join */
76021 ){
76022   struct SrcList_item *pItem;
76023   sqlite3 *db = pParse->db;
76024   if( !p && (pOn || pUsing) ){
76025     sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s", 
76026       (pOn ? "ON" : "USING")
76027     );
76028     goto append_from_error;
76029   }
76030   p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
76031   if( p==0 || NEVER(p->nSrc==0) ){
76032     goto append_from_error;
76033   }
76034   pItem = &p->a[p->nSrc-1];
76035   assert( pAlias!=0 );
76036   if( pAlias->n ){
76037     pItem->zAlias = sqlite3NameFromToken(db, pAlias);
76038   }
76039   pItem->pSelect = pSubquery;
76040   pItem->pOn = pOn;
76041   pItem->pUsing = pUsing;
76042   return p;
76043
76044  append_from_error:
76045   assert( p==0 );
76046   sqlite3ExprDelete(db, pOn);
76047   sqlite3IdListDelete(db, pUsing);
76048   sqlite3SelectDelete(db, pSubquery);
76049   return 0;
76050 }
76051
76052 /*
76053 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added 
76054 ** element of the source-list passed as the second argument.
76055 */
76056 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
76057   assert( pIndexedBy!=0 );
76058   if( p && ALWAYS(p->nSrc>0) ){
76059     struct SrcList_item *pItem = &p->a[p->nSrc-1];
76060     assert( pItem->notIndexed==0 && pItem->zIndex==0 );
76061     if( pIndexedBy->n==1 && !pIndexedBy->z ){
76062       /* A "NOT INDEXED" clause was supplied. See parse.y 
76063       ** construct "indexed_opt" for details. */
76064       pItem->notIndexed = 1;
76065     }else{
76066       pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
76067     }
76068   }
76069 }
76070
76071 /*
76072 ** When building up a FROM clause in the parser, the join operator
76073 ** is initially attached to the left operand.  But the code generator
76074 ** expects the join operator to be on the right operand.  This routine
76075 ** Shifts all join operators from left to right for an entire FROM
76076 ** clause.
76077 **
76078 ** Example: Suppose the join is like this:
76079 **
76080 **           A natural cross join B
76081 **
76082 ** The operator is "natural cross join".  The A and B operands are stored
76083 ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
76084 ** operator with A.  This routine shifts that operator over to B.
76085 */
76086 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
76087   if( p && p->a ){
76088     int i;
76089     for(i=p->nSrc-1; i>0; i--){
76090       p->a[i].jointype = p->a[i-1].jointype;
76091     }
76092     p->a[0].jointype = 0;
76093   }
76094 }
76095
76096 /*
76097 ** Begin a transaction
76098 */
76099 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
76100   sqlite3 *db;
76101   Vdbe *v;
76102   int i;
76103
76104   assert( pParse!=0 );
76105   db = pParse->db;
76106   assert( db!=0 );
76107 /*  if( db->aDb[0].pBt==0 ) return; */
76108   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
76109     return;
76110   }
76111   v = sqlite3GetVdbe(pParse);
76112   if( !v ) return;
76113   if( type!=TK_DEFERRED ){
76114     for(i=0; i<db->nDb; i++){
76115       sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
76116       sqlite3VdbeUsesBtree(v, i);
76117     }
76118   }
76119   sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
76120 }
76121
76122 /*
76123 ** Commit a transaction
76124 */
76125 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
76126   sqlite3 *db;
76127   Vdbe *v;
76128
76129   assert( pParse!=0 );
76130   db = pParse->db;
76131   assert( db!=0 );
76132 /*  if( db->aDb[0].pBt==0 ) return; */
76133   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
76134     return;
76135   }
76136   v = sqlite3GetVdbe(pParse);
76137   if( v ){
76138     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
76139   }
76140 }
76141
76142 /*
76143 ** Rollback a transaction
76144 */
76145 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
76146   sqlite3 *db;
76147   Vdbe *v;
76148
76149   assert( pParse!=0 );
76150   db = pParse->db;
76151   assert( db!=0 );
76152 /*  if( db->aDb[0].pBt==0 ) return; */
76153   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
76154     return;
76155   }
76156   v = sqlite3GetVdbe(pParse);
76157   if( v ){
76158     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
76159   }
76160 }
76161
76162 /*
76163 ** This function is called by the parser when it parses a command to create,
76164 ** release or rollback an SQL savepoint. 
76165 */
76166 SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
76167   char *zName = sqlite3NameFromToken(pParse->db, pName);
76168   if( zName ){
76169     Vdbe *v = sqlite3GetVdbe(pParse);
76170 #ifndef SQLITE_OMIT_AUTHORIZATION
76171     static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
76172     assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
76173 #endif
76174     if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
76175       sqlite3DbFree(pParse->db, zName);
76176       return;
76177     }
76178     sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
76179   }
76180 }
76181
76182 /*
76183 ** Make sure the TEMP database is open and available for use.  Return
76184 ** the number of errors.  Leave any error messages in the pParse structure.
76185 */
76186 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
76187   sqlite3 *db = pParse->db;
76188   if( db->aDb[1].pBt==0 && !pParse->explain ){
76189     int rc;
76190     Btree *pBt;
76191     static const int flags = 
76192           SQLITE_OPEN_READWRITE |
76193           SQLITE_OPEN_CREATE |
76194           SQLITE_OPEN_EXCLUSIVE |
76195           SQLITE_OPEN_DELETEONCLOSE |
76196           SQLITE_OPEN_TEMP_DB;
76197
76198     rc = sqlite3BtreeFactory(db, 0, 0, SQLITE_DEFAULT_CACHE_SIZE, flags, &pBt);
76199     if( rc!=SQLITE_OK ){
76200       sqlite3ErrorMsg(pParse, "unable to open a temporary database "
76201         "file for storing temporary tables");
76202       pParse->rc = rc;
76203       return 1;
76204     }
76205     db->aDb[1].pBt = pBt;
76206     assert( db->aDb[1].pSchema );
76207     if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
76208       db->mallocFailed = 1;
76209       return 1;
76210     }
76211   }
76212   return 0;
76213 }
76214
76215 /*
76216 ** Generate VDBE code that will verify the schema cookie and start
76217 ** a read-transaction for all named database files.
76218 **
76219 ** It is important that all schema cookies be verified and all
76220 ** read transactions be started before anything else happens in
76221 ** the VDBE program.  But this routine can be called after much other
76222 ** code has been generated.  So here is what we do:
76223 **
76224 ** The first time this routine is called, we code an OP_Goto that
76225 ** will jump to a subroutine at the end of the program.  Then we
76226 ** record every database that needs its schema verified in the
76227 ** pParse->cookieMask field.  Later, after all other code has been
76228 ** generated, the subroutine that does the cookie verifications and
76229 ** starts the transactions will be coded and the OP_Goto P2 value
76230 ** will be made to point to that subroutine.  The generation of the
76231 ** cookie verification subroutine code happens in sqlite3FinishCoding().
76232 **
76233 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
76234 ** schema on any databases.  This can be used to position the OP_Goto
76235 ** early in the code, before we know if any database tables will be used.
76236 */
76237 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
76238   Parse *pToplevel = sqlite3ParseToplevel(pParse);
76239
76240   if( pToplevel->cookieGoto==0 ){
76241     Vdbe *v = sqlite3GetVdbe(pToplevel);
76242     if( v==0 ) return;  /* This only happens if there was a prior error */
76243     pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
76244   }
76245   if( iDb>=0 ){
76246     sqlite3 *db = pToplevel->db;
76247     int mask;
76248
76249     assert( iDb<db->nDb );
76250     assert( db->aDb[iDb].pBt!=0 || iDb==1 );
76251     assert( iDb<SQLITE_MAX_ATTACHED+2 );
76252     mask = 1<<iDb;
76253     if( (pToplevel->cookieMask & mask)==0 ){
76254       pToplevel->cookieMask |= mask;
76255       pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
76256       if( !OMIT_TEMPDB && iDb==1 ){
76257         sqlite3OpenTempDatabase(pToplevel);
76258       }
76259     }
76260   }
76261 }
76262
76263 /*
76264 ** Generate VDBE code that prepares for doing an operation that
76265 ** might change the database.
76266 **
76267 ** This routine starts a new transaction if we are not already within
76268 ** a transaction.  If we are already within a transaction, then a checkpoint
76269 ** is set if the setStatement parameter is true.  A checkpoint should
76270 ** be set for operations that might fail (due to a constraint) part of
76271 ** the way through and which will need to undo some writes without having to
76272 ** rollback the whole transaction.  For operations where all constraints
76273 ** can be checked before any changes are made to the database, it is never
76274 ** necessary to undo a write and the checkpoint should not be set.
76275 */
76276 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
76277   Parse *pToplevel = sqlite3ParseToplevel(pParse);
76278   sqlite3CodeVerifySchema(pParse, iDb);
76279   pToplevel->writeMask |= 1<<iDb;
76280   pToplevel->isMultiWrite |= setStatement;
76281 }
76282
76283 /*
76284 ** Indicate that the statement currently under construction might write
76285 ** more than one entry (example: deleting one row then inserting another,
76286 ** inserting multiple rows in a table, or inserting a row and index entries.)
76287 ** If an abort occurs after some of these writes have completed, then it will
76288 ** be necessary to undo the completed writes.
76289 */
76290 SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
76291   Parse *pToplevel = sqlite3ParseToplevel(pParse);
76292   pToplevel->isMultiWrite = 1;
76293 }
76294
76295 /* 
76296 ** The code generator calls this routine if is discovers that it is
76297 ** possible to abort a statement prior to completion.  In order to 
76298 ** perform this abort without corrupting the database, we need to make
76299 ** sure that the statement is protected by a statement transaction.
76300 **
76301 ** Technically, we only need to set the mayAbort flag if the
76302 ** isMultiWrite flag was previously set.  There is a time dependency
76303 ** such that the abort must occur after the multiwrite.  This makes
76304 ** some statements involving the REPLACE conflict resolution algorithm
76305 ** go a little faster.  But taking advantage of this time dependency
76306 ** makes it more difficult to prove that the code is correct (in 
76307 ** particular, it prevents us from writing an effective
76308 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
76309 ** to take the safe route and skip the optimization.
76310 */
76311 SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
76312   Parse *pToplevel = sqlite3ParseToplevel(pParse);
76313   pToplevel->mayAbort = 1;
76314 }
76315
76316 /*
76317 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
76318 ** error. The onError parameter determines which (if any) of the statement
76319 ** and/or current transaction is rolled back.
76320 */
76321 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse *pParse, int onError, char *p4, int p4type){
76322   Vdbe *v = sqlite3GetVdbe(pParse);
76323   if( onError==OE_Abort ){
76324     sqlite3MayAbort(pParse);
76325   }
76326   sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type);
76327 }
76328
76329 /*
76330 ** Check to see if pIndex uses the collating sequence pColl.  Return
76331 ** true if it does and false if it does not.
76332 */
76333 #ifndef SQLITE_OMIT_REINDEX
76334 static int collationMatch(const char *zColl, Index *pIndex){
76335   int i;
76336   assert( zColl!=0 );
76337   for(i=0; i<pIndex->nColumn; i++){
76338     const char *z = pIndex->azColl[i];
76339     assert( z!=0 );
76340     if( 0==sqlite3StrICmp(z, zColl) ){
76341       return 1;
76342     }
76343   }
76344   return 0;
76345 }
76346 #endif
76347
76348 /*
76349 ** Recompute all indices of pTab that use the collating sequence pColl.
76350 ** If pColl==0 then recompute all indices of pTab.
76351 */
76352 #ifndef SQLITE_OMIT_REINDEX
76353 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
76354   Index *pIndex;              /* An index associated with pTab */
76355
76356   for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
76357     if( zColl==0 || collationMatch(zColl, pIndex) ){
76358       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
76359       sqlite3BeginWriteOperation(pParse, 0, iDb);
76360       sqlite3RefillIndex(pParse, pIndex, -1);
76361     }
76362   }
76363 }
76364 #endif
76365
76366 /*
76367 ** Recompute all indices of all tables in all databases where the
76368 ** indices use the collating sequence pColl.  If pColl==0 then recompute
76369 ** all indices everywhere.
76370 */
76371 #ifndef SQLITE_OMIT_REINDEX
76372 static void reindexDatabases(Parse *pParse, char const *zColl){
76373   Db *pDb;                    /* A single database */
76374   int iDb;                    /* The database index number */
76375   sqlite3 *db = pParse->db;   /* The database connection */
76376   HashElem *k;                /* For looping over tables in pDb */
76377   Table *pTab;                /* A table in the database */
76378
76379   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
76380     assert( pDb!=0 );
76381     for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
76382       pTab = (Table*)sqliteHashData(k);
76383       reindexTable(pParse, pTab, zColl);
76384     }
76385   }
76386 }
76387 #endif
76388
76389 /*
76390 ** Generate code for the REINDEX command.
76391 **
76392 **        REINDEX                            -- 1
76393 **        REINDEX  <collation>               -- 2
76394 **        REINDEX  ?<database>.?<tablename>  -- 3
76395 **        REINDEX  ?<database>.?<indexname>  -- 4
76396 **
76397 ** Form 1 causes all indices in all attached databases to be rebuilt.
76398 ** Form 2 rebuilds all indices in all databases that use the named
76399 ** collating function.  Forms 3 and 4 rebuild the named index or all
76400 ** indices associated with the named table.
76401 */
76402 #ifndef SQLITE_OMIT_REINDEX
76403 SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
76404   CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
76405   char *z;                    /* Name of a table or index */
76406   const char *zDb;            /* Name of the database */
76407   Table *pTab;                /* A table in the database */
76408   Index *pIndex;              /* An index associated with pTab */
76409   int iDb;                    /* The database index number */
76410   sqlite3 *db = pParse->db;   /* The database connection */
76411   Token *pObjName;            /* Name of the table or index to be reindexed */
76412
76413   /* Read the database schema. If an error occurs, leave an error message
76414   ** and code in pParse and return NULL. */
76415   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
76416     return;
76417   }
76418
76419   if( pName1==0 ){
76420     reindexDatabases(pParse, 0);
76421     return;
76422   }else if( NEVER(pName2==0) || pName2->z==0 ){
76423     char *zColl;
76424     assert( pName1->z );
76425     zColl = sqlite3NameFromToken(pParse->db, pName1);
76426     if( !zColl ) return;
76427     pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
76428     if( pColl ){
76429       reindexDatabases(pParse, zColl);
76430       sqlite3DbFree(db, zColl);
76431       return;
76432     }
76433     sqlite3DbFree(db, zColl);
76434   }
76435   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
76436   if( iDb<0 ) return;
76437   z = sqlite3NameFromToken(db, pObjName);
76438   if( z==0 ) return;
76439   zDb = db->aDb[iDb].zName;
76440   pTab = sqlite3FindTable(db, z, zDb);
76441   if( pTab ){
76442     reindexTable(pParse, pTab, 0);
76443     sqlite3DbFree(db, z);
76444     return;
76445   }
76446   pIndex = sqlite3FindIndex(db, z, zDb);
76447   sqlite3DbFree(db, z);
76448   if( pIndex ){
76449     sqlite3BeginWriteOperation(pParse, 0, iDb);
76450     sqlite3RefillIndex(pParse, pIndex, -1);
76451     return;
76452   }
76453   sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
76454 }
76455 #endif
76456
76457 /*
76458 ** Return a dynamicly allocated KeyInfo structure that can be used
76459 ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
76460 **
76461 ** If successful, a pointer to the new structure is returned. In this case
76462 ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned 
76463 ** pointer. If an error occurs (out of memory or missing collation 
76464 ** sequence), NULL is returned and the state of pParse updated to reflect
76465 ** the error.
76466 */
76467 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
76468   int i;
76469   int nCol = pIdx->nColumn;
76470   int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
76471   sqlite3 *db = pParse->db;
76472   KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
76473
76474   if( pKey ){
76475     pKey->db = pParse->db;
76476     pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
76477     assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
76478     for(i=0; i<nCol; i++){
76479       char *zColl = pIdx->azColl[i];
76480       assert( zColl );
76481       pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
76482       pKey->aSortOrder[i] = pIdx->aSortOrder[i];
76483     }
76484     pKey->nField = (u16)nCol;
76485   }
76486
76487   if( pParse->nErr ){
76488     sqlite3DbFree(db, pKey);
76489     pKey = 0;
76490   }
76491   return pKey;
76492 }
76493
76494 /************** End of build.c ***********************************************/
76495 /************** Begin file callback.c ****************************************/
76496 /*
76497 ** 2005 May 23 
76498 **
76499 ** The author disclaims copyright to this source code.  In place of
76500 ** a legal notice, here is a blessing:
76501 **
76502 **    May you do good and not evil.
76503 **    May you find forgiveness for yourself and forgive others.
76504 **    May you share freely, never taking more than you give.
76505 **
76506 *************************************************************************
76507 **
76508 ** This file contains functions used to access the internal hash tables
76509 ** of user defined functions and collation sequences.
76510 */
76511
76512
76513 /*
76514 ** Invoke the 'collation needed' callback to request a collation sequence
76515 ** in the encoding enc of name zName, length nName.
76516 */
76517 static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
76518   assert( !db->xCollNeeded || !db->xCollNeeded16 );
76519   if( db->xCollNeeded ){
76520     char *zExternal = sqlite3DbStrDup(db, zName);
76521     if( !zExternal ) return;
76522     db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
76523     sqlite3DbFree(db, zExternal);
76524   }
76525 #ifndef SQLITE_OMIT_UTF16
76526   if( db->xCollNeeded16 ){
76527     char const *zExternal;
76528     sqlite3_value *pTmp = sqlite3ValueNew(db);
76529     sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
76530     zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
76531     if( zExternal ){
76532       db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
76533     }
76534     sqlite3ValueFree(pTmp);
76535   }
76536 #endif
76537 }
76538
76539 /*
76540 ** This routine is called if the collation factory fails to deliver a
76541 ** collation function in the best encoding but there may be other versions
76542 ** of this collation function (for other text encodings) available. Use one
76543 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
76544 ** possible.
76545 */
76546 static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
76547   CollSeq *pColl2;
76548   char *z = pColl->zName;
76549   int i;
76550   static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
76551   for(i=0; i<3; i++){
76552     pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
76553     if( pColl2->xCmp!=0 ){
76554       memcpy(pColl, pColl2, sizeof(CollSeq));
76555       pColl->xDel = 0;         /* Do not copy the destructor */
76556       return SQLITE_OK;
76557     }
76558   }
76559   return SQLITE_ERROR;
76560 }
76561
76562 /*
76563 ** This function is responsible for invoking the collation factory callback
76564 ** or substituting a collation sequence of a different encoding when the
76565 ** requested collation sequence is not available in the desired encoding.
76566 ** 
76567 ** If it is not NULL, then pColl must point to the database native encoding 
76568 ** collation sequence with name zName, length nName.
76569 **
76570 ** The return value is either the collation sequence to be used in database
76571 ** db for collation type name zName, length nName, or NULL, if no collation
76572 ** sequence can be found.
76573 **
76574 ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
76575 */
76576 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
76577   sqlite3* db,          /* The database connection */
76578   u8 enc,               /* The desired encoding for the collating sequence */
76579   CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
76580   const char *zName     /* Collating sequence name */
76581 ){
76582   CollSeq *p;
76583
76584   p = pColl;
76585   if( !p ){
76586     p = sqlite3FindCollSeq(db, enc, zName, 0);
76587   }
76588   if( !p || !p->xCmp ){
76589     /* No collation sequence of this type for this encoding is registered.
76590     ** Call the collation factory to see if it can supply us with one.
76591     */
76592     callCollNeeded(db, enc, zName);
76593     p = sqlite3FindCollSeq(db, enc, zName, 0);
76594   }
76595   if( p && !p->xCmp && synthCollSeq(db, p) ){
76596     p = 0;
76597   }
76598   assert( !p || p->xCmp );
76599   return p;
76600 }
76601
76602 /*
76603 ** This routine is called on a collation sequence before it is used to
76604 ** check that it is defined. An undefined collation sequence exists when
76605 ** a database is loaded that contains references to collation sequences
76606 ** that have not been defined by sqlite3_create_collation() etc.
76607 **
76608 ** If required, this routine calls the 'collation needed' callback to
76609 ** request a definition of the collating sequence. If this doesn't work, 
76610 ** an equivalent collating sequence that uses a text encoding different
76611 ** from the main database is substituted, if one is available.
76612 */
76613 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
76614   if( pColl ){
76615     const char *zName = pColl->zName;
76616     sqlite3 *db = pParse->db;
76617     CollSeq *p = sqlite3GetCollSeq(db, ENC(db), pColl, zName);
76618     if( !p ){
76619       sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
76620       pParse->nErr++;
76621       return SQLITE_ERROR;
76622     }
76623     assert( p==pColl );
76624   }
76625   return SQLITE_OK;
76626 }
76627
76628
76629
76630 /*
76631 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
76632 ** specified by zName and nName is not found and parameter 'create' is
76633 ** true, then create a new entry. Otherwise return NULL.
76634 **
76635 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
76636 ** array of three CollSeq structures. The first is the collation sequence
76637 ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
76638 **
76639 ** Stored immediately after the three collation sequences is a copy of
76640 ** the collation sequence name. A pointer to this string is stored in
76641 ** each collation sequence structure.
76642 */
76643 static CollSeq *findCollSeqEntry(
76644   sqlite3 *db,          /* Database connection */
76645   const char *zName,    /* Name of the collating sequence */
76646   int create            /* Create a new entry if true */
76647 ){
76648   CollSeq *pColl;
76649   int nName = sqlite3Strlen30(zName);
76650   pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
76651
76652   if( 0==pColl && create ){
76653     pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
76654     if( pColl ){
76655       CollSeq *pDel = 0;
76656       pColl[0].zName = (char*)&pColl[3];
76657       pColl[0].enc = SQLITE_UTF8;
76658       pColl[1].zName = (char*)&pColl[3];
76659       pColl[1].enc = SQLITE_UTF16LE;
76660       pColl[2].zName = (char*)&pColl[3];
76661       pColl[2].enc = SQLITE_UTF16BE;
76662       memcpy(pColl[0].zName, zName, nName);
76663       pColl[0].zName[nName] = 0;
76664       pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
76665
76666       /* If a malloc() failure occurred in sqlite3HashInsert(), it will 
76667       ** return the pColl pointer to be deleted (because it wasn't added
76668       ** to the hash table).
76669       */
76670       assert( pDel==0 || pDel==pColl );
76671       if( pDel!=0 ){
76672         db->mallocFailed = 1;
76673         sqlite3DbFree(db, pDel);
76674         pColl = 0;
76675       }
76676     }
76677   }
76678   return pColl;
76679 }
76680
76681 /*
76682 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
76683 ** Return the CollSeq* pointer for the collation sequence named zName
76684 ** for the encoding 'enc' from the database 'db'.
76685 **
76686 ** If the entry specified is not found and 'create' is true, then create a
76687 ** new entry.  Otherwise return NULL.
76688 **
76689 ** A separate function sqlite3LocateCollSeq() is a wrapper around
76690 ** this routine.  sqlite3LocateCollSeq() invokes the collation factory
76691 ** if necessary and generates an error message if the collating sequence
76692 ** cannot be found.
76693 **
76694 ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
76695 */
76696 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
76697   sqlite3 *db,
76698   u8 enc,
76699   const char *zName,
76700   int create
76701 ){
76702   CollSeq *pColl;
76703   if( zName ){
76704     pColl = findCollSeqEntry(db, zName, create);
76705   }else{
76706     pColl = db->pDfltColl;
76707   }
76708   assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
76709   assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
76710   if( pColl ) pColl += enc-1;
76711   return pColl;
76712 }
76713
76714 /* During the search for the best function definition, this procedure
76715 ** is called to test how well the function passed as the first argument
76716 ** matches the request for a function with nArg arguments in a system
76717 ** that uses encoding enc. The value returned indicates how well the
76718 ** request is matched. A higher value indicates a better match.
76719 **
76720 ** The returned value is always between 0 and 6, as follows:
76721 **
76722 ** 0: Not a match, or if nArg<0 and the function is has no implementation.
76723 ** 1: A variable arguments function that prefers UTF-8 when a UTF-16
76724 **    encoding is requested, or vice versa.
76725 ** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
76726 **    requested, or vice versa.
76727 ** 3: A variable arguments function using the same text encoding.
76728 ** 4: A function with the exact number of arguments requested that
76729 **    prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
76730 ** 5: A function with the exact number of arguments requested that
76731 **    prefers UTF-16LE when UTF-16BE is requested, or vice versa.
76732 ** 6: An exact match.
76733 **
76734 */
76735 static int matchQuality(FuncDef *p, int nArg, u8 enc){
76736   int match = 0;
76737   if( p->nArg==-1 || p->nArg==nArg 
76738    || (nArg==-1 && (p->xFunc!=0 || p->xStep!=0))
76739   ){
76740     match = 1;
76741     if( p->nArg==nArg || nArg==-1 ){
76742       match = 4;
76743     }
76744     if( enc==p->iPrefEnc ){
76745       match += 2;
76746     }
76747     else if( (enc==SQLITE_UTF16LE && p->iPrefEnc==SQLITE_UTF16BE) ||
76748              (enc==SQLITE_UTF16BE && p->iPrefEnc==SQLITE_UTF16LE) ){
76749       match += 1;
76750     }
76751   }
76752   return match;
76753 }
76754
76755 /*
76756 ** Search a FuncDefHash for a function with the given name.  Return
76757 ** a pointer to the matching FuncDef if found, or 0 if there is no match.
76758 */
76759 static FuncDef *functionSearch(
76760   FuncDefHash *pHash,  /* Hash table to search */
76761   int h,               /* Hash of the name */
76762   const char *zFunc,   /* Name of function */
76763   int nFunc            /* Number of bytes in zFunc */
76764 ){
76765   FuncDef *p;
76766   for(p=pHash->a[h]; p; p=p->pHash){
76767     if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
76768       return p;
76769     }
76770   }
76771   return 0;
76772 }
76773
76774 /*
76775 ** Insert a new FuncDef into a FuncDefHash hash table.
76776 */
76777 SQLITE_PRIVATE void sqlite3FuncDefInsert(
76778   FuncDefHash *pHash,  /* The hash table into which to insert */
76779   FuncDef *pDef        /* The function definition to insert */
76780 ){
76781   FuncDef *pOther;
76782   int nName = sqlite3Strlen30(pDef->zName);
76783   u8 c1 = (u8)pDef->zName[0];
76784   int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
76785   pOther = functionSearch(pHash, h, pDef->zName, nName);
76786   if( pOther ){
76787     assert( pOther!=pDef && pOther->pNext!=pDef );
76788     pDef->pNext = pOther->pNext;
76789     pOther->pNext = pDef;
76790   }else{
76791     pDef->pNext = 0;
76792     pDef->pHash = pHash->a[h];
76793     pHash->a[h] = pDef;
76794   }
76795 }
76796   
76797   
76798
76799 /*
76800 ** Locate a user function given a name, a number of arguments and a flag
76801 ** indicating whether the function prefers UTF-16 over UTF-8.  Return a
76802 ** pointer to the FuncDef structure that defines that function, or return
76803 ** NULL if the function does not exist.
76804 **
76805 ** If the createFlag argument is true, then a new (blank) FuncDef
76806 ** structure is created and liked into the "db" structure if a
76807 ** no matching function previously existed.  When createFlag is true
76808 ** and the nArg parameter is -1, then only a function that accepts
76809 ** any number of arguments will be returned.
76810 **
76811 ** If createFlag is false and nArg is -1, then the first valid
76812 ** function found is returned.  A function is valid if either xFunc
76813 ** or xStep is non-zero.
76814 **
76815 ** If createFlag is false, then a function with the required name and
76816 ** number of arguments may be returned even if the eTextRep flag does not
76817 ** match that requested.
76818 */
76819 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
76820   sqlite3 *db,       /* An open database */
76821   const char *zName, /* Name of the function.  Not null-terminated */
76822   int nName,         /* Number of characters in the name */
76823   int nArg,          /* Number of arguments.  -1 means any number */
76824   u8 enc,            /* Preferred text encoding */
76825   int createFlag     /* Create new entry if true and does not otherwise exist */
76826 ){
76827   FuncDef *p;         /* Iterator variable */
76828   FuncDef *pBest = 0; /* Best match found so far */
76829   int bestScore = 0;  /* Score of best match */
76830   int h;              /* Hash value */
76831
76832
76833   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
76834   h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
76835
76836   /* First search for a match amongst the application-defined functions.
76837   */
76838   p = functionSearch(&db->aFunc, h, zName, nName);
76839   while( p ){
76840     int score = matchQuality(p, nArg, enc);
76841     if( score>bestScore ){
76842       pBest = p;
76843       bestScore = score;
76844     }
76845     p = p->pNext;
76846   }
76847
76848   /* If no match is found, search the built-in functions.
76849   **
76850   ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
76851   ** functions even if a prior app-defined function was found.  And give
76852   ** priority to built-in functions.
76853   **
76854   ** Except, if createFlag is true, that means that we are trying to
76855   ** install a new function.  Whatever FuncDef structure is returned will
76856   ** have fields overwritten with new information appropriate for the
76857   ** new function.  But the FuncDefs for built-in functions are read-only.
76858   ** So we must not search for built-ins when creating a new function.
76859   */ 
76860   if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
76861     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
76862     bestScore = 0;
76863     p = functionSearch(pHash, h, zName, nName);
76864     while( p ){
76865       int score = matchQuality(p, nArg, enc);
76866       if( score>bestScore ){
76867         pBest = p;
76868         bestScore = score;
76869       }
76870       p = p->pNext;
76871     }
76872   }
76873
76874   /* If the createFlag parameter is true and the search did not reveal an
76875   ** exact match for the name, number of arguments and encoding, then add a
76876   ** new entry to the hash table and return it.
76877   */
76878   if( createFlag && (bestScore<6 || pBest->nArg!=nArg) && 
76879       (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
76880     pBest->zName = (char *)&pBest[1];
76881     pBest->nArg = (u16)nArg;
76882     pBest->iPrefEnc = enc;
76883     memcpy(pBest->zName, zName, nName);
76884     pBest->zName[nName] = 0;
76885     sqlite3FuncDefInsert(&db->aFunc, pBest);
76886   }
76887
76888   if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
76889     return pBest;
76890   }
76891   return 0;
76892 }
76893
76894 /*
76895 ** Free all resources held by the schema structure. The void* argument points
76896 ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the 
76897 ** pointer itself, it just cleans up subsiduary resources (i.e. the contents
76898 ** of the schema hash tables).
76899 **
76900 ** The Schema.cache_size variable is not cleared.
76901 */
76902 SQLITE_PRIVATE void sqlite3SchemaFree(void *p){
76903   Hash temp1;
76904   Hash temp2;
76905   HashElem *pElem;
76906   Schema *pSchema = (Schema *)p;
76907
76908   temp1 = pSchema->tblHash;
76909   temp2 = pSchema->trigHash;
76910   sqlite3HashInit(&pSchema->trigHash);
76911   sqlite3HashClear(&pSchema->idxHash);
76912   for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
76913     sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
76914   }
76915   sqlite3HashClear(&temp2);
76916   sqlite3HashInit(&pSchema->tblHash);
76917   for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
76918     Table *pTab = sqliteHashData(pElem);
76919     assert( pTab->dbMem==0 );
76920     sqlite3DeleteTable(pTab);
76921   }
76922   sqlite3HashClear(&temp1);
76923   sqlite3HashClear(&pSchema->fkeyHash);
76924   pSchema->pSeqTab = 0;
76925   pSchema->flags &= ~DB_SchemaLoaded;
76926 }
76927
76928 /*
76929 ** Find and return the schema associated with a BTree.  Create
76930 ** a new one if necessary.
76931 */
76932 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
76933   Schema * p;
76934   if( pBt ){
76935     p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaFree);
76936   }else{
76937     p = (Schema *)sqlite3MallocZero(sizeof(Schema));
76938   }
76939   if( !p ){
76940     db->mallocFailed = 1;
76941   }else if ( 0==p->file_format ){
76942     sqlite3HashInit(&p->tblHash);
76943     sqlite3HashInit(&p->idxHash);
76944     sqlite3HashInit(&p->trigHash);
76945     sqlite3HashInit(&p->fkeyHash);
76946     p->enc = SQLITE_UTF8;
76947   }
76948   return p;
76949 }
76950
76951 /************** End of callback.c ********************************************/
76952 /************** Begin file delete.c ******************************************/
76953 /*
76954 ** 2001 September 15
76955 **
76956 ** The author disclaims copyright to this source code.  In place of
76957 ** a legal notice, here is a blessing:
76958 **
76959 **    May you do good and not evil.
76960 **    May you find forgiveness for yourself and forgive others.
76961 **    May you share freely, never taking more than you give.
76962 **
76963 *************************************************************************
76964 ** This file contains C code routines that are called by the parser
76965 ** in order to generate code for DELETE FROM statements.
76966 */
76967
76968 /*
76969 ** Look up every table that is named in pSrc.  If any table is not found,
76970 ** add an error message to pParse->zErrMsg and return NULL.  If all tables
76971 ** are found, return a pointer to the last table.
76972 */
76973 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
76974   struct SrcList_item *pItem = pSrc->a;
76975   Table *pTab;
76976   assert( pItem && pSrc->nSrc==1 );
76977   pTab = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
76978   sqlite3DeleteTable(pItem->pTab);
76979   pItem->pTab = pTab;
76980   if( pTab ){
76981     pTab->nRef++;
76982   }
76983   if( sqlite3IndexedByLookup(pParse, pItem) ){
76984     pTab = 0;
76985   }
76986   return pTab;
76987 }
76988
76989 /*
76990 ** Check to make sure the given table is writable.  If it is not
76991 ** writable, generate an error message and return 1.  If it is
76992 ** writable return 0;
76993 */
76994 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
76995   /* A table is not writable under the following circumstances:
76996   **
76997   **   1) It is a virtual table and no implementation of the xUpdate method
76998   **      has been provided, or
76999   **   2) It is a system table (i.e. sqlite_master), this call is not
77000   **      part of a nested parse and writable_schema pragma has not 
77001   **      been specified.
77002   **
77003   ** In either case leave an error message in pParse and return non-zero.
77004   */
77005   if( ( IsVirtual(pTab) 
77006      && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
77007    || ( (pTab->tabFlags & TF_Readonly)!=0
77008      && (pParse->db->flags & SQLITE_WriteSchema)==0
77009      && pParse->nested==0 )
77010   ){
77011     sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
77012     return 1;
77013   }
77014
77015 #ifndef SQLITE_OMIT_VIEW
77016   if( !viewOk && pTab->pSelect ){
77017     sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
77018     return 1;
77019   }
77020 #endif
77021   return 0;
77022 }
77023
77024
77025 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
77026 /*
77027 ** Evaluate a view and store its result in an ephemeral table.  The
77028 ** pWhere argument is an optional WHERE clause that restricts the
77029 ** set of rows in the view that are to be added to the ephemeral table.
77030 */
77031 SQLITE_PRIVATE void sqlite3MaterializeView(
77032   Parse *pParse,       /* Parsing context */
77033   Table *pView,        /* View definition */
77034   Expr *pWhere,        /* Optional WHERE clause to be added */
77035   int iCur             /* Cursor number for ephemerial table */
77036 ){
77037   SelectDest dest;
77038   Select *pDup;
77039   sqlite3 *db = pParse->db;
77040
77041   pDup = sqlite3SelectDup(db, pView->pSelect, 0);
77042   if( pWhere ){
77043     SrcList *pFrom;
77044     
77045     pWhere = sqlite3ExprDup(db, pWhere, 0);
77046     pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
77047     if( pFrom ){
77048       assert( pFrom->nSrc==1 );
77049       pFrom->a[0].zAlias = sqlite3DbStrDup(db, pView->zName);
77050       pFrom->a[0].pSelect = pDup;
77051       assert( pFrom->a[0].pOn==0 );
77052       assert( pFrom->a[0].pUsing==0 );
77053     }else{
77054       sqlite3SelectDelete(db, pDup);
77055     }
77056     pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
77057   }
77058   sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
77059   sqlite3Select(pParse, pDup, &dest);
77060   sqlite3SelectDelete(db, pDup);
77061 }
77062 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
77063
77064 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
77065 /*
77066 ** Generate an expression tree to implement the WHERE, ORDER BY,
77067 ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
77068 **
77069 **     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
77070 **                            \__________________________/
77071 **                               pLimitWhere (pInClause)
77072 */
77073 SQLITE_PRIVATE Expr *sqlite3LimitWhere(
77074   Parse *pParse,               /* The parser context */
77075   SrcList *pSrc,               /* the FROM clause -- which tables to scan */
77076   Expr *pWhere,                /* The WHERE clause.  May be null */
77077   ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
77078   Expr *pLimit,                /* The LIMIT clause.  May be null */
77079   Expr *pOffset,               /* The OFFSET clause.  May be null */
77080   char *zStmtType              /* Either DELETE or UPDATE.  For error messages. */
77081 ){
77082   Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
77083   Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
77084   Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
77085   ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
77086   SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
77087   Select *pSelect = NULL;      /* Complete SELECT tree */
77088
77089   /* Check that there isn't an ORDER BY without a LIMIT clause.
77090   */
77091   if( pOrderBy && (pLimit == 0) ) {
77092     sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
77093     pParse->parseError = 1;
77094     goto limit_where_cleanup_2;
77095   }
77096
77097   /* We only need to generate a select expression if there
77098   ** is a limit/offset term to enforce.
77099   */
77100   if( pLimit == 0 ) {
77101     /* if pLimit is null, pOffset will always be null as well. */
77102     assert( pOffset == 0 );
77103     return pWhere;
77104   }
77105
77106   /* Generate a select expression tree to enforce the limit/offset 
77107   ** term for the DELETE or UPDATE statement.  For example:
77108   **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
77109   ** becomes:
77110   **   DELETE FROM table_a WHERE rowid IN ( 
77111   **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
77112   **   );
77113   */
77114
77115   pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
77116   if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
77117   pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
77118   if( pEList == 0 ) goto limit_where_cleanup_2;
77119
77120   /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
77121   ** and the SELECT subtree. */
77122   pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
77123   if( pSelectSrc == 0 ) {
77124     sqlite3ExprListDelete(pParse->db, pEList);
77125     goto limit_where_cleanup_2;
77126   }
77127
77128   /* generate the SELECT expression tree. */
77129   pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
77130                              pOrderBy,0,pLimit,pOffset);
77131   if( pSelect == 0 ) return 0;
77132
77133   /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
77134   pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
77135   if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
77136   pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
77137   if( pInClause == 0 ) goto limit_where_cleanup_1;
77138
77139   pInClause->x.pSelect = pSelect;
77140   pInClause->flags |= EP_xIsSelect;
77141   sqlite3ExprSetHeight(pParse, pInClause);
77142   return pInClause;
77143
77144   /* something went wrong. clean up anything allocated. */
77145 limit_where_cleanup_1:
77146   sqlite3SelectDelete(pParse->db, pSelect);
77147   return 0;
77148
77149 limit_where_cleanup_2:
77150   sqlite3ExprDelete(pParse->db, pWhere);
77151   sqlite3ExprListDelete(pParse->db, pOrderBy);
77152   sqlite3ExprDelete(pParse->db, pLimit);
77153   sqlite3ExprDelete(pParse->db, pOffset);
77154   return 0;
77155 }
77156 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
77157
77158 /*
77159 ** Generate code for a DELETE FROM statement.
77160 **
77161 **     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
77162 **                 \________/       \________________/
77163 **                  pTabList              pWhere
77164 */
77165 SQLITE_PRIVATE void sqlite3DeleteFrom(
77166   Parse *pParse,         /* The parser context */
77167   SrcList *pTabList,     /* The table from which we should delete things */
77168   Expr *pWhere           /* The WHERE clause.  May be null */
77169 ){
77170   Vdbe *v;               /* The virtual database engine */
77171   Table *pTab;           /* The table from which records will be deleted */
77172   const char *zDb;       /* Name of database holding pTab */
77173   int end, addr = 0;     /* A couple addresses of generated code */
77174   int i;                 /* Loop counter */
77175   WhereInfo *pWInfo;     /* Information about the WHERE clause */
77176   Index *pIdx;           /* For looping over indices of the table */
77177   int iCur;              /* VDBE Cursor number for pTab */
77178   sqlite3 *db;           /* Main database structure */
77179   AuthContext sContext;  /* Authorization context */
77180   NameContext sNC;       /* Name context to resolve expressions in */
77181   int iDb;               /* Database number */
77182   int memCnt = -1;       /* Memory cell used for change counting */
77183   int rcauth;            /* Value returned by authorization callback */
77184
77185 #ifndef SQLITE_OMIT_TRIGGER
77186   int isView;                  /* True if attempting to delete from a view */
77187   Trigger *pTrigger;           /* List of table triggers, if required */
77188 #endif
77189
77190   memset(&sContext, 0, sizeof(sContext));
77191   db = pParse->db;
77192   if( pParse->nErr || db->mallocFailed ){
77193     goto delete_from_cleanup;
77194   }
77195   assert( pTabList->nSrc==1 );
77196
77197   /* Locate the table which we want to delete.  This table has to be
77198   ** put in an SrcList structure because some of the subroutines we
77199   ** will be calling are designed to work with multiple tables and expect
77200   ** an SrcList* parameter instead of just a Table* parameter.
77201   */
77202   pTab = sqlite3SrcListLookup(pParse, pTabList);
77203   if( pTab==0 )  goto delete_from_cleanup;
77204
77205   /* Figure out if we have any triggers and if the table being
77206   ** deleted from is a view
77207   */
77208 #ifndef SQLITE_OMIT_TRIGGER
77209   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
77210   isView = pTab->pSelect!=0;
77211 #else
77212 # define pTrigger 0
77213 # define isView 0
77214 #endif
77215 #ifdef SQLITE_OMIT_VIEW
77216 # undef isView
77217 # define isView 0
77218 #endif
77219
77220   /* If pTab is really a view, make sure it has been initialized.
77221   */
77222   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
77223     goto delete_from_cleanup;
77224   }
77225
77226   if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
77227     goto delete_from_cleanup;
77228   }
77229   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
77230   assert( iDb<db->nDb );
77231   zDb = db->aDb[iDb].zName;
77232   rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
77233   assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
77234   if( rcauth==SQLITE_DENY ){
77235     goto delete_from_cleanup;
77236   }
77237   assert(!isView || pTrigger);
77238
77239   /* Assign  cursor number to the table and all its indices.
77240   */
77241   assert( pTabList->nSrc==1 );
77242   iCur = pTabList->a[0].iCursor = pParse->nTab++;
77243   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
77244     pParse->nTab++;
77245   }
77246
77247   /* Start the view context
77248   */
77249   if( isView ){
77250     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
77251   }
77252
77253   /* Begin generating code.
77254   */
77255   v = sqlite3GetVdbe(pParse);
77256   if( v==0 ){
77257     goto delete_from_cleanup;
77258   }
77259   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
77260   sqlite3BeginWriteOperation(pParse, 1, iDb);
77261
77262   /* If we are trying to delete from a view, realize that view into
77263   ** a ephemeral table.
77264   */
77265 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
77266   if( isView ){
77267     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
77268   }
77269 #endif
77270
77271   /* Resolve the column names in the WHERE clause.
77272   */
77273   memset(&sNC, 0, sizeof(sNC));
77274   sNC.pParse = pParse;
77275   sNC.pSrcList = pTabList;
77276   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
77277     goto delete_from_cleanup;
77278   }
77279
77280   /* Initialize the counter of the number of rows deleted, if
77281   ** we are counting rows.
77282   */
77283   if( db->flags & SQLITE_CountRows ){
77284     memCnt = ++pParse->nMem;
77285     sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
77286   }
77287
77288 #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
77289   /* Special case: A DELETE without a WHERE clause deletes everything.
77290   ** It is easier just to erase the whole table. Prior to version 3.6.5,
77291   ** this optimization caused the row change count (the value returned by 
77292   ** API function sqlite3_count_changes) to be set incorrectly.  */
77293   if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab) 
77294    && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
77295   ){
77296     assert( !isView );
77297     sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
77298                       pTab->zName, P4_STATIC);
77299     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
77300       assert( pIdx->pSchema==pTab->pSchema );
77301       sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
77302     }
77303   }else
77304 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
77305   /* The usual case: There is a WHERE clause so we have to scan through
77306   ** the table and pick which records to delete.
77307   */
77308   {
77309     int iRowSet = ++pParse->nMem;   /* Register for rowset of rows to delete */
77310     int iRowid = ++pParse->nMem;    /* Used for storing rowid values. */
77311     int regRowid;                   /* Actual register containing rowids */
77312
77313     /* Collect rowids of every row to be deleted.
77314     */
77315     sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
77316     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0,WHERE_DUPLICATES_OK);
77317     if( pWInfo==0 ) goto delete_from_cleanup;
77318     regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid);
77319     sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
77320     if( db->flags & SQLITE_CountRows ){
77321       sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
77322     }
77323     sqlite3WhereEnd(pWInfo);
77324
77325     /* Delete every item whose key was written to the list during the
77326     ** database scan.  We have to delete items after the scan is complete
77327     ** because deleting an item can change the scan order.  */
77328     end = sqlite3VdbeMakeLabel(v);
77329
77330     /* Unless this is a view, open cursors for the table we are 
77331     ** deleting from and all its indices. If this is a view, then the
77332     ** only effect this statement has is to fire the INSTEAD OF 
77333     ** triggers.  */
77334     if( !isView ){
77335       sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
77336     }
77337
77338     addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
77339
77340     /* Delete the row */
77341 #ifndef SQLITE_OMIT_VIRTUALTABLE
77342     if( IsVirtual(pTab) ){
77343       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
77344       sqlite3VtabMakeWritable(pParse, pTab);
77345       sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
77346       sqlite3MayAbort(pParse);
77347     }else
77348 #endif
77349     {
77350       int count = (pParse->nested==0);    /* True to count changes */
77351       sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
77352     }
77353
77354     /* End of the delete loop */
77355     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
77356     sqlite3VdbeResolveLabel(v, end);
77357
77358     /* Close the cursors open on the table and its indexes. */
77359     if( !isView && !IsVirtual(pTab) ){
77360       for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
77361         sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
77362       }
77363       sqlite3VdbeAddOp1(v, OP_Close, iCur);
77364     }
77365   }
77366
77367   /* Update the sqlite_sequence table by storing the content of the
77368   ** maximum rowid counter values recorded while inserting into
77369   ** autoincrement tables.
77370   */
77371   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
77372     sqlite3AutoincrementEnd(pParse);
77373   }
77374
77375   /* Return the number of rows that were deleted. If this routine is 
77376   ** generating code because of a call to sqlite3NestedParse(), do not
77377   ** invoke the callback function.
77378   */
77379   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
77380     sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
77381     sqlite3VdbeSetNumCols(v, 1);
77382     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
77383   }
77384
77385 delete_from_cleanup:
77386   sqlite3AuthContextPop(&sContext);
77387   sqlite3SrcListDelete(db, pTabList);
77388   sqlite3ExprDelete(db, pWhere);
77389   return;
77390 }
77391 /* Make sure "isView" and other macros defined above are undefined. Otherwise
77392 ** thely may interfere with compilation of other functions in this file
77393 ** (or in another file, if this file becomes part of the amalgamation).  */
77394 #ifdef isView
77395  #undef isView
77396 #endif
77397 #ifdef pTrigger
77398  #undef pTrigger
77399 #endif
77400
77401 /*
77402 ** This routine generates VDBE code that causes a single row of a
77403 ** single table to be deleted.
77404 **
77405 ** The VDBE must be in a particular state when this routine is called.
77406 ** These are the requirements:
77407 **
77408 **   1.  A read/write cursor pointing to pTab, the table containing the row
77409 **       to be deleted, must be opened as cursor number $iCur.
77410 **
77411 **   2.  Read/write cursors for all indices of pTab must be open as
77412 **       cursor number base+i for the i-th index.
77413 **
77414 **   3.  The record number of the row to be deleted must be stored in
77415 **       memory cell iRowid.
77416 **
77417 ** This routine generates code to remove both the table record and all 
77418 ** index entries that point to that record.
77419 */
77420 SQLITE_PRIVATE void sqlite3GenerateRowDelete(
77421   Parse *pParse,     /* Parsing context */
77422   Table *pTab,       /* Table containing the row to be deleted */
77423   int iCur,          /* Cursor number for the table */
77424   int iRowid,        /* Memory cell that contains the rowid to delete */
77425   int count,         /* If non-zero, increment the row change counter */
77426   Trigger *pTrigger, /* List of triggers to (potentially) fire */
77427   int onconf         /* Default ON CONFLICT policy for triggers */
77428 ){
77429   Vdbe *v = pParse->pVdbe;        /* Vdbe */
77430   int iOld = 0;                   /* First register in OLD.* array */
77431   int iLabel;                     /* Label resolved to end of generated code */
77432
77433   /* Vdbe is guaranteed to have been allocated by this stage. */
77434   assert( v );
77435
77436   /* Seek cursor iCur to the row to delete. If this row no longer exists 
77437   ** (this can happen if a trigger program has already deleted it), do
77438   ** not attempt to delete it or fire any DELETE triggers.  */
77439   iLabel = sqlite3VdbeMakeLabel(v);
77440   sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
77441  
77442   /* If there are any triggers to fire, allocate a range of registers to
77443   ** use for the old.* references in the triggers.  */
77444   if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
77445     u32 mask;                     /* Mask of OLD.* columns in use */
77446     int iCol;                     /* Iterator used while populating OLD.* */
77447
77448     /* TODO: Could use temporary registers here. Also could attempt to
77449     ** avoid copying the contents of the rowid register.  */
77450     mask = sqlite3TriggerColmask(
77451         pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
77452     );
77453     mask |= sqlite3FkOldmask(pParse, pTab);
77454     iOld = pParse->nMem+1;
77455     pParse->nMem += (1 + pTab->nCol);
77456
77457     /* Populate the OLD.* pseudo-table register array. These values will be 
77458     ** used by any BEFORE and AFTER triggers that exist.  */
77459     sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
77460     for(iCol=0; iCol<pTab->nCol; iCol++){
77461       if( mask==0xffffffff || mask&(1<<iCol) ){
77462         sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, iOld+iCol+1);
77463       }
77464     }
77465
77466     /* Invoke BEFORE DELETE trigger programs. */
77467     sqlite3CodeRowTrigger(pParse, pTrigger, 
77468         TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
77469     );
77470
77471     /* Seek the cursor to the row to be deleted again. It may be that
77472     ** the BEFORE triggers coded above have already removed the row
77473     ** being deleted. Do not attempt to delete the row a second time, and 
77474     ** do not fire AFTER triggers.  */
77475     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
77476
77477     /* Do FK processing. This call checks that any FK constraints that
77478     ** refer to this table (i.e. constraints attached to other tables) 
77479     ** are not violated by deleting this row.  */
77480     sqlite3FkCheck(pParse, pTab, iOld, 0);
77481   }
77482
77483   /* Delete the index and table entries. Skip this step if pTab is really
77484   ** a view (in which case the only effect of the DELETE statement is to
77485   ** fire the INSTEAD OF triggers).  */ 
77486   if( pTab->pSelect==0 ){
77487     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
77488     sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
77489     if( count ){
77490       sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
77491     }
77492   }
77493
77494   /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
77495   ** handle rows (possibly in other tables) that refer via a foreign key
77496   ** to the row just deleted. */ 
77497   sqlite3FkActions(pParse, pTab, 0, iOld);
77498
77499   /* Invoke AFTER DELETE trigger programs. */
77500   sqlite3CodeRowTrigger(pParse, pTrigger, 
77501       TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
77502   );
77503
77504   /* Jump here if the row had already been deleted before any BEFORE
77505   ** trigger programs were invoked. Or if a trigger program throws a 
77506   ** RAISE(IGNORE) exception.  */
77507   sqlite3VdbeResolveLabel(v, iLabel);
77508 }
77509
77510 /*
77511 ** This routine generates VDBE code that causes the deletion of all
77512 ** index entries associated with a single row of a single table.
77513 **
77514 ** The VDBE must be in a particular state when this routine is called.
77515 ** These are the requirements:
77516 **
77517 **   1.  A read/write cursor pointing to pTab, the table containing the row
77518 **       to be deleted, must be opened as cursor number "iCur".
77519 **
77520 **   2.  Read/write cursors for all indices of pTab must be open as
77521 **       cursor number iCur+i for the i-th index.
77522 **
77523 **   3.  The "iCur" cursor must be pointing to the row that is to be
77524 **       deleted.
77525 */
77526 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
77527   Parse *pParse,     /* Parsing and code generating context */
77528   Table *pTab,       /* Table containing the row to be deleted */
77529   int iCur,          /* Cursor number for the table */
77530   int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
77531 ){
77532   int i;
77533   Index *pIdx;
77534   int r1;
77535
77536   for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
77537     if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
77538     r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
77539     sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
77540   }
77541 }
77542
77543 /*
77544 ** Generate code that will assemble an index key and put it in register
77545 ** regOut.  The key with be for index pIdx which is an index on pTab.
77546 ** iCur is the index of a cursor open on the pTab table and pointing to
77547 ** the entry that needs indexing.
77548 **
77549 ** Return a register number which is the first in a block of
77550 ** registers that holds the elements of the index key.  The
77551 ** block of registers has already been deallocated by the time
77552 ** this routine returns.
77553 */
77554 SQLITE_PRIVATE int sqlite3GenerateIndexKey(
77555   Parse *pParse,     /* Parsing context */
77556   Index *pIdx,       /* The index for which to generate a key */
77557   int iCur,          /* Cursor number for the pIdx->pTable table */
77558   int regOut,        /* Write the new index key to this register */
77559   int doMakeRec      /* Run the OP_MakeRecord instruction if true */
77560 ){
77561   Vdbe *v = pParse->pVdbe;
77562   int j;
77563   Table *pTab = pIdx->pTable;
77564   int regBase;
77565   int nCol;
77566
77567   nCol = pIdx->nColumn;
77568   regBase = sqlite3GetTempRange(pParse, nCol+1);
77569   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
77570   for(j=0; j<nCol; j++){
77571     int idx = pIdx->aiColumn[j];
77572     if( idx==pTab->iPKey ){
77573       sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
77574     }else{
77575       sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
77576       sqlite3ColumnDefault(v, pTab, idx, -1);
77577     }
77578   }
77579   if( doMakeRec ){
77580     sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
77581     sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
77582   }
77583   sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
77584   return regBase;
77585 }
77586
77587 /************** End of delete.c **********************************************/
77588 /************** Begin file func.c ********************************************/
77589 /*
77590 ** 2002 February 23
77591 **
77592 ** The author disclaims copyright to this source code.  In place of
77593 ** a legal notice, here is a blessing:
77594 **
77595 **    May you do good and not evil.
77596 **    May you find forgiveness for yourself and forgive others.
77597 **    May you share freely, never taking more than you give.
77598 **
77599 *************************************************************************
77600 ** This file contains the C functions that implement various SQL
77601 ** functions of SQLite.  
77602 **
77603 ** There is only one exported symbol in this file - the function
77604 ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
77605 ** All other code has file scope.
77606 */
77607
77608 /*
77609 ** Return the collating function associated with a function.
77610 */
77611 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
77612   return context->pColl;
77613 }
77614
77615 /*
77616 ** Implementation of the non-aggregate min() and max() functions
77617 */
77618 static void minmaxFunc(
77619   sqlite3_context *context,
77620   int argc,
77621   sqlite3_value **argv
77622 ){
77623   int i;
77624   int mask;    /* 0 for min() or 0xffffffff for max() */
77625   int iBest;
77626   CollSeq *pColl;
77627
77628   assert( argc>1 );
77629   mask = sqlite3_user_data(context)==0 ? 0 : -1;
77630   pColl = sqlite3GetFuncCollSeq(context);
77631   assert( pColl );
77632   assert( mask==-1 || mask==0 );
77633   iBest = 0;
77634   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
77635   for(i=1; i<argc; i++){
77636     if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
77637     if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
77638       testcase( mask==0 );
77639       iBest = i;
77640     }
77641   }
77642   sqlite3_result_value(context, argv[iBest]);
77643 }
77644
77645 /*
77646 ** Return the type of the argument.
77647 */
77648 static void typeofFunc(
77649   sqlite3_context *context,
77650   int NotUsed,
77651   sqlite3_value **argv
77652 ){
77653   const char *z = 0;
77654   UNUSED_PARAMETER(NotUsed);
77655   switch( sqlite3_value_type(argv[0]) ){
77656     case SQLITE_INTEGER: z = "integer"; break;
77657     case SQLITE_TEXT:    z = "text";    break;
77658     case SQLITE_FLOAT:   z = "real";    break;
77659     case SQLITE_BLOB:    z = "blob";    break;
77660     default:             z = "null";    break;
77661   }
77662   sqlite3_result_text(context, z, -1, SQLITE_STATIC);
77663 }
77664
77665
77666 /*
77667 ** Implementation of the length() function
77668 */
77669 static void lengthFunc(
77670   sqlite3_context *context,
77671   int argc,
77672   sqlite3_value **argv
77673 ){
77674   int len;
77675
77676   assert( argc==1 );
77677   UNUSED_PARAMETER(argc);
77678   switch( sqlite3_value_type(argv[0]) ){
77679     case SQLITE_BLOB:
77680     case SQLITE_INTEGER:
77681     case SQLITE_FLOAT: {
77682       sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
77683       break;
77684     }
77685     case SQLITE_TEXT: {
77686       const unsigned char *z = sqlite3_value_text(argv[0]);
77687       if( z==0 ) return;
77688       len = 0;
77689       while( *z ){
77690         len++;
77691         SQLITE_SKIP_UTF8(z);
77692       }
77693       sqlite3_result_int(context, len);
77694       break;
77695     }
77696     default: {
77697       sqlite3_result_null(context);
77698       break;
77699     }
77700   }
77701 }
77702
77703 /*
77704 ** Implementation of the abs() function.
77705 **
77706 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
77707 ** the numeric argument X. 
77708 */
77709 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
77710   assert( argc==1 );
77711   UNUSED_PARAMETER(argc);
77712   switch( sqlite3_value_type(argv[0]) ){
77713     case SQLITE_INTEGER: {
77714       i64 iVal = sqlite3_value_int64(argv[0]);
77715       if( iVal<0 ){
77716         if( (iVal<<1)==0 ){
77717           /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then
77718           ** abs(X) throws an integer overflow error since there is no
77719           ** equivalent positive 64-bit two complement value. */
77720           sqlite3_result_error(context, "integer overflow", -1);
77721           return;
77722         }
77723         iVal = -iVal;
77724       } 
77725       sqlite3_result_int64(context, iVal);
77726       break;
77727     }
77728     case SQLITE_NULL: {
77729       /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
77730       sqlite3_result_null(context);
77731       break;
77732     }
77733     default: {
77734       /* Because sqlite3_value_double() returns 0.0 if the argument is not
77735       ** something that can be converted into a number, we have:
77736       ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
77737       ** cannot be converted to a numeric value. 
77738       */
77739       double rVal = sqlite3_value_double(argv[0]);
77740       if( rVal<0 ) rVal = -rVal;
77741       sqlite3_result_double(context, rVal);
77742       break;
77743     }
77744   }
77745 }
77746
77747 /*
77748 ** Implementation of the substr() function.
77749 **
77750 ** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
77751 ** p1 is 1-indexed.  So substr(x,1,1) returns the first character
77752 ** of x.  If x is text, then we actually count UTF-8 characters.
77753 ** If x is a blob, then we count bytes.
77754 **
77755 ** If p1 is negative, then we begin abs(p1) from the end of x[].
77756 **
77757 ** If p2 is negative, return the p2 characters preceeding p1.
77758 */
77759 static void substrFunc(
77760   sqlite3_context *context,
77761   int argc,
77762   sqlite3_value **argv
77763 ){
77764   const unsigned char *z;
77765   const unsigned char *z2;
77766   int len;
77767   int p0type;
77768   i64 p1, p2;
77769   int negP2 = 0;
77770
77771   assert( argc==3 || argc==2 );
77772   if( sqlite3_value_type(argv[1])==SQLITE_NULL
77773    || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
77774   ){
77775     return;
77776   }
77777   p0type = sqlite3_value_type(argv[0]);
77778   p1 = sqlite3_value_int(argv[1]);
77779   if( p0type==SQLITE_BLOB ){
77780     len = sqlite3_value_bytes(argv[0]);
77781     z = sqlite3_value_blob(argv[0]);
77782     if( z==0 ) return;
77783     assert( len==sqlite3_value_bytes(argv[0]) );
77784   }else{
77785     z = sqlite3_value_text(argv[0]);
77786     if( z==0 ) return;
77787     len = 0;
77788     if( p1<0 ){
77789       for(z2=z; *z2; len++){
77790         SQLITE_SKIP_UTF8(z2);
77791       }
77792     }
77793   }
77794   if( argc==3 ){
77795     p2 = sqlite3_value_int(argv[2]);
77796     if( p2<0 ){
77797       p2 = -p2;
77798       negP2 = 1;
77799     }
77800   }else{
77801     p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
77802   }
77803   if( p1<0 ){
77804     p1 += len;
77805     if( p1<0 ){
77806       p2 += p1;
77807       if( p2<0 ) p2 = 0;
77808       p1 = 0;
77809     }
77810   }else if( p1>0 ){
77811     p1--;
77812   }else if( p2>0 ){
77813     p2--;
77814   }
77815   if( negP2 ){
77816     p1 -= p2;
77817     if( p1<0 ){
77818       p2 += p1;
77819       p1 = 0;
77820     }
77821   }
77822   assert( p1>=0 && p2>=0 );
77823   if( p0type!=SQLITE_BLOB ){
77824     while( *z && p1 ){
77825       SQLITE_SKIP_UTF8(z);
77826       p1--;
77827     }
77828     for(z2=z; *z2 && p2; p2--){
77829       SQLITE_SKIP_UTF8(z2);
77830     }
77831     sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
77832   }else{
77833     if( p1+p2>len ){
77834       p2 = len-p1;
77835       if( p2<0 ) p2 = 0;
77836     }
77837     sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
77838   }
77839 }
77840
77841 /*
77842 ** Implementation of the round() function
77843 */
77844 #ifndef SQLITE_OMIT_FLOATING_POINT
77845 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
77846   int n = 0;
77847   double r;
77848   char *zBuf;
77849   assert( argc==1 || argc==2 );
77850   if( argc==2 ){
77851     if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
77852     n = sqlite3_value_int(argv[1]);
77853     if( n>30 ) n = 30;
77854     if( n<0 ) n = 0;
77855   }
77856   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
77857   r = sqlite3_value_double(argv[0]);
77858   /* If Y==0 and X will fit in a 64-bit int,
77859   ** handle the rounding directly,
77860   ** otherwise use printf.
77861   */
77862   if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
77863     r = (double)((sqlite_int64)(r+0.5));
77864   }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
77865     r = -(double)((sqlite_int64)((-r)+0.5));
77866   }else{
77867     zBuf = sqlite3_mprintf("%.*f",n,r);
77868     if( zBuf==0 ){
77869       sqlite3_result_error_nomem(context);
77870       return;
77871     }
77872     sqlite3AtoF(zBuf, &r);
77873     sqlite3_free(zBuf);
77874   }
77875   sqlite3_result_double(context, r);
77876 }
77877 #endif
77878
77879 /*
77880 ** Allocate nByte bytes of space using sqlite3_malloc(). If the
77881 ** allocation fails, call sqlite3_result_error_nomem() to notify
77882 ** the database handle that malloc() has failed and return NULL.
77883 ** If nByte is larger than the maximum string or blob length, then
77884 ** raise an SQLITE_TOOBIG exception and return NULL.
77885 */
77886 static void *contextMalloc(sqlite3_context *context, i64 nByte){
77887   char *z;
77888   sqlite3 *db = sqlite3_context_db_handle(context);
77889   assert( nByte>0 );
77890   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
77891   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
77892   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
77893     sqlite3_result_error_toobig(context);
77894     z = 0;
77895   }else{
77896     z = sqlite3Malloc((int)nByte);
77897     if( !z ){
77898       sqlite3_result_error_nomem(context);
77899     }
77900   }
77901   return z;
77902 }
77903
77904 /*
77905 ** Implementation of the upper() and lower() SQL functions.
77906 */
77907 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
77908   char *z1;
77909   const char *z2;
77910   int i, n;
77911   UNUSED_PARAMETER(argc);
77912   z2 = (char*)sqlite3_value_text(argv[0]);
77913   n = sqlite3_value_bytes(argv[0]);
77914   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
77915   assert( z2==(char*)sqlite3_value_text(argv[0]) );
77916   if( z2 ){
77917     z1 = contextMalloc(context, ((i64)n)+1);
77918     if( z1 ){
77919       memcpy(z1, z2, n+1);
77920       for(i=0; z1[i]; i++){
77921         z1[i] = (char)sqlite3Toupper(z1[i]);
77922       }
77923       sqlite3_result_text(context, z1, -1, sqlite3_free);
77924     }
77925   }
77926 }
77927 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
77928   u8 *z1;
77929   const char *z2;
77930   int i, n;
77931   UNUSED_PARAMETER(argc);
77932   z2 = (char*)sqlite3_value_text(argv[0]);
77933   n = sqlite3_value_bytes(argv[0]);
77934   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
77935   assert( z2==(char*)sqlite3_value_text(argv[0]) );
77936   if( z2 ){
77937     z1 = contextMalloc(context, ((i64)n)+1);
77938     if( z1 ){
77939       memcpy(z1, z2, n+1);
77940       for(i=0; z1[i]; i++){
77941         z1[i] = sqlite3Tolower(z1[i]);
77942       }
77943       sqlite3_result_text(context, (char *)z1, -1, sqlite3_free);
77944     }
77945   }
77946 }
77947
77948
77949 #if 0  /* This function is never used. */
77950 /*
77951 ** The COALESCE() and IFNULL() functions used to be implemented as shown
77952 ** here.  But now they are implemented as VDBE code so that unused arguments
77953 ** do not have to be computed.  This legacy implementation is retained as
77954 ** comment.
77955 */
77956 /*
77957 ** Implementation of the IFNULL(), NVL(), and COALESCE() functions.  
77958 ** All three do the same thing.  They return the first non-NULL
77959 ** argument.
77960 */
77961 static void ifnullFunc(
77962   sqlite3_context *context,
77963   int argc,
77964   sqlite3_value **argv
77965 ){
77966   int i;
77967   for(i=0; i<argc; i++){
77968     if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
77969       sqlite3_result_value(context, argv[i]);
77970       break;
77971     }
77972   }
77973 }
77974 #endif /* NOT USED */
77975 #define ifnullFunc versionFunc   /* Substitute function - never called */
77976
77977 /*
77978 ** Implementation of random().  Return a random integer.  
77979 */
77980 static void randomFunc(
77981   sqlite3_context *context,
77982   int NotUsed,
77983   sqlite3_value **NotUsed2
77984 ){
77985   sqlite_int64 r;
77986   UNUSED_PARAMETER2(NotUsed, NotUsed2);
77987   sqlite3_randomness(sizeof(r), &r);
77988   if( r<0 ){
77989     /* We need to prevent a random number of 0x8000000000000000 
77990     ** (or -9223372036854775808) since when you do abs() of that
77991     ** number of you get the same value back again.  To do this
77992     ** in a way that is testable, mask the sign bit off of negative
77993     ** values, resulting in a positive value.  Then take the 
77994     ** 2s complement of that positive value.  The end result can
77995     ** therefore be no less than -9223372036854775807.
77996     */
77997     r = -(r ^ (((sqlite3_int64)1)<<63));
77998   }
77999   sqlite3_result_int64(context, r);
78000 }
78001
78002 /*
78003 ** Implementation of randomblob(N).  Return a random blob
78004 ** that is N bytes long.
78005 */
78006 static void randomBlob(
78007   sqlite3_context *context,
78008   int argc,
78009   sqlite3_value **argv
78010 ){
78011   int n;
78012   unsigned char *p;
78013   assert( argc==1 );
78014   UNUSED_PARAMETER(argc);
78015   n = sqlite3_value_int(argv[0]);
78016   if( n<1 ){
78017     n = 1;
78018   }
78019   p = contextMalloc(context, n);
78020   if( p ){
78021     sqlite3_randomness(n, p);
78022     sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
78023   }
78024 }
78025
78026 /*
78027 ** Implementation of the last_insert_rowid() SQL function.  The return
78028 ** value is the same as the sqlite3_last_insert_rowid() API function.
78029 */
78030 static void last_insert_rowid(
78031   sqlite3_context *context, 
78032   int NotUsed, 
78033   sqlite3_value **NotUsed2
78034 ){
78035   sqlite3 *db = sqlite3_context_db_handle(context);
78036   UNUSED_PARAMETER2(NotUsed, NotUsed2);
78037   /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
78038   ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
78039   ** function. */
78040   sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
78041 }
78042
78043 /*
78044 ** Implementation of the changes() SQL function.
78045 **
78046 ** IMP: R-62073-11209 The changes() SQL function is a wrapper
78047 ** around the sqlite3_changes() C/C++ function and hence follows the same
78048 ** rules for counting changes.
78049 */
78050 static void changes(
78051   sqlite3_context *context,
78052   int NotUsed,
78053   sqlite3_value **NotUsed2
78054 ){
78055   sqlite3 *db = sqlite3_context_db_handle(context);
78056   UNUSED_PARAMETER2(NotUsed, NotUsed2);
78057   sqlite3_result_int(context, sqlite3_changes(db));
78058 }
78059
78060 /*
78061 ** Implementation of the total_changes() SQL function.  The return value is
78062 ** the same as the sqlite3_total_changes() API function.
78063 */
78064 static void total_changes(
78065   sqlite3_context *context,
78066   int NotUsed,
78067   sqlite3_value **NotUsed2
78068 ){
78069   sqlite3 *db = sqlite3_context_db_handle(context);
78070   UNUSED_PARAMETER2(NotUsed, NotUsed2);
78071   /* IMP: R-52756-41993 This function is a wrapper around the
78072   ** sqlite3_total_changes() C/C++ interface. */
78073   sqlite3_result_int(context, sqlite3_total_changes(db));
78074 }
78075
78076 /*
78077 ** A structure defining how to do GLOB-style comparisons.
78078 */
78079 struct compareInfo {
78080   u8 matchAll;
78081   u8 matchOne;
78082   u8 matchSet;
78083   u8 noCase;
78084 };
78085
78086 /*
78087 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
78088 ** character is exactly one byte in size.  Also, all characters are
78089 ** able to participate in upper-case-to-lower-case mappings in EBCDIC
78090 ** whereas only characters less than 0x80 do in ASCII.
78091 */
78092 #if defined(SQLITE_EBCDIC)
78093 # define sqlite3Utf8Read(A,C)    (*(A++))
78094 # define GlogUpperToLower(A)     A = sqlite3UpperToLower[A]
78095 #else
78096 # define GlogUpperToLower(A)     if( A<0x80 ){ A = sqlite3UpperToLower[A]; }
78097 #endif
78098
78099 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
78100 /* The correct SQL-92 behavior is for the LIKE operator to ignore
78101 ** case.  Thus  'a' LIKE 'A' would be true. */
78102 static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
78103 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
78104 ** is case sensitive causing 'a' LIKE 'A' to be false */
78105 static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
78106
78107 /*
78108 ** Compare two UTF-8 strings for equality where the first string can
78109 ** potentially be a "glob" expression.  Return true (1) if they
78110 ** are the same and false (0) if they are different.
78111 **
78112 ** Globbing rules:
78113 **
78114 **      '*'       Matches any sequence of zero or more characters.
78115 **
78116 **      '?'       Matches exactly one character.
78117 **
78118 **     [...]      Matches one character from the enclosed list of
78119 **                characters.
78120 **
78121 **     [^...]     Matches one character not in the enclosed list.
78122 **
78123 ** With the [...] and [^...] matching, a ']' character can be included
78124 ** in the list by making it the first character after '[' or '^'.  A
78125 ** range of characters can be specified using '-'.  Example:
78126 ** "[a-z]" matches any single lower-case letter.  To match a '-', make
78127 ** it the last character in the list.
78128 **
78129 ** This routine is usually quick, but can be N**2 in the worst case.
78130 **
78131 ** Hints: to match '*' or '?', put them in "[]".  Like this:
78132 **
78133 **         abc[*]xyz        Matches "abc*xyz" only
78134 */
78135 static int patternCompare(
78136   const u8 *zPattern,              /* The glob pattern */
78137   const u8 *zString,               /* The string to compare against the glob */
78138   const struct compareInfo *pInfo, /* Information about how to do the compare */
78139   const int esc                    /* The escape character */
78140 ){
78141   int c, c2;
78142   int invert;
78143   int seen;
78144   u8 matchOne = pInfo->matchOne;
78145   u8 matchAll = pInfo->matchAll;
78146   u8 matchSet = pInfo->matchSet;
78147   u8 noCase = pInfo->noCase; 
78148   int prevEscape = 0;     /* True if the previous character was 'escape' */
78149
78150   while( (c = sqlite3Utf8Read(zPattern,&zPattern))!=0 ){
78151     if( !prevEscape && c==matchAll ){
78152       while( (c=sqlite3Utf8Read(zPattern,&zPattern)) == matchAll
78153                || c == matchOne ){
78154         if( c==matchOne && sqlite3Utf8Read(zString, &zString)==0 ){
78155           return 0;
78156         }
78157       }
78158       if( c==0 ){
78159         return 1;
78160       }else if( c==esc ){
78161         c = sqlite3Utf8Read(zPattern, &zPattern);
78162         if( c==0 ){
78163           return 0;
78164         }
78165       }else if( c==matchSet ){
78166         assert( esc==0 );         /* This is GLOB, not LIKE */
78167         assert( matchSet<0x80 );  /* '[' is a single-byte character */
78168         while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
78169           SQLITE_SKIP_UTF8(zString);
78170         }
78171         return *zString!=0;
78172       }
78173       while( (c2 = sqlite3Utf8Read(zString,&zString))!=0 ){
78174         if( noCase ){
78175           GlogUpperToLower(c2);
78176           GlogUpperToLower(c);
78177           while( c2 != 0 && c2 != c ){
78178             c2 = sqlite3Utf8Read(zString, &zString);
78179             GlogUpperToLower(c2);
78180           }
78181         }else{
78182           while( c2 != 0 && c2 != c ){
78183             c2 = sqlite3Utf8Read(zString, &zString);
78184           }
78185         }
78186         if( c2==0 ) return 0;
78187         if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
78188       }
78189       return 0;
78190     }else if( !prevEscape && c==matchOne ){
78191       if( sqlite3Utf8Read(zString, &zString)==0 ){
78192         return 0;
78193       }
78194     }else if( c==matchSet ){
78195       int prior_c = 0;
78196       assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
78197       seen = 0;
78198       invert = 0;
78199       c = sqlite3Utf8Read(zString, &zString);
78200       if( c==0 ) return 0;
78201       c2 = sqlite3Utf8Read(zPattern, &zPattern);
78202       if( c2=='^' ){
78203         invert = 1;
78204         c2 = sqlite3Utf8Read(zPattern, &zPattern);
78205       }
78206       if( c2==']' ){
78207         if( c==']' ) seen = 1;
78208         c2 = sqlite3Utf8Read(zPattern, &zPattern);
78209       }
78210       while( c2 && c2!=']' ){
78211         if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
78212           c2 = sqlite3Utf8Read(zPattern, &zPattern);
78213           if( c>=prior_c && c<=c2 ) seen = 1;
78214           prior_c = 0;
78215         }else{
78216           if( c==c2 ){
78217             seen = 1;
78218           }
78219           prior_c = c2;
78220         }
78221         c2 = sqlite3Utf8Read(zPattern, &zPattern);
78222       }
78223       if( c2==0 || (seen ^ invert)==0 ){
78224         return 0;
78225       }
78226     }else if( esc==c && !prevEscape ){
78227       prevEscape = 1;
78228     }else{
78229       c2 = sqlite3Utf8Read(zString, &zString);
78230       if( noCase ){
78231         GlogUpperToLower(c);
78232         GlogUpperToLower(c2);
78233       }
78234       if( c!=c2 ){
78235         return 0;
78236       }
78237       prevEscape = 0;
78238     }
78239   }
78240   return *zString==0;
78241 }
78242
78243 /*
78244 ** Count the number of times that the LIKE operator (or GLOB which is
78245 ** just a variation of LIKE) gets called.  This is used for testing
78246 ** only.
78247 */
78248 #ifdef SQLITE_TEST
78249 SQLITE_API int sqlite3_like_count = 0;
78250 #endif
78251
78252
78253 /*
78254 ** Implementation of the like() SQL function.  This function implements
78255 ** the build-in LIKE operator.  The first argument to the function is the
78256 ** pattern and the second argument is the string.  So, the SQL statements:
78257 **
78258 **       A LIKE B
78259 **
78260 ** is implemented as like(B,A).
78261 **
78262 ** This same function (with a different compareInfo structure) computes
78263 ** the GLOB operator.
78264 */
78265 static void likeFunc(
78266   sqlite3_context *context, 
78267   int argc, 
78268   sqlite3_value **argv
78269 ){
78270   const unsigned char *zA, *zB;
78271   int escape = 0;
78272   int nPat;
78273   sqlite3 *db = sqlite3_context_db_handle(context);
78274
78275   zB = sqlite3_value_text(argv[0]);
78276   zA = sqlite3_value_text(argv[1]);
78277
78278   /* Limit the length of the LIKE or GLOB pattern to avoid problems
78279   ** of deep recursion and N*N behavior in patternCompare().
78280   */
78281   nPat = sqlite3_value_bytes(argv[0]);
78282   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
78283   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
78284   if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
78285     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
78286     return;
78287   }
78288   assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
78289
78290   if( argc==3 ){
78291     /* The escape character string must consist of a single UTF-8 character.
78292     ** Otherwise, return an error.
78293     */
78294     const unsigned char *zEsc = sqlite3_value_text(argv[2]);
78295     if( zEsc==0 ) return;
78296     if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
78297       sqlite3_result_error(context, 
78298           "ESCAPE expression must be a single character", -1);
78299       return;
78300     }
78301     escape = sqlite3Utf8Read(zEsc, &zEsc);
78302   }
78303   if( zA && zB ){
78304     struct compareInfo *pInfo = sqlite3_user_data(context);
78305 #ifdef SQLITE_TEST
78306     sqlite3_like_count++;
78307 #endif
78308     
78309     sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
78310   }
78311 }
78312
78313 /*
78314 ** Implementation of the NULLIF(x,y) function.  The result is the first
78315 ** argument if the arguments are different.  The result is NULL if the
78316 ** arguments are equal to each other.
78317 */
78318 static void nullifFunc(
78319   sqlite3_context *context,
78320   int NotUsed,
78321   sqlite3_value **argv
78322 ){
78323   CollSeq *pColl = sqlite3GetFuncCollSeq(context);
78324   UNUSED_PARAMETER(NotUsed);
78325   if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
78326     sqlite3_result_value(context, argv[0]);
78327   }
78328 }
78329
78330 /*
78331 ** Implementation of the sqlite_version() function.  The result is the version
78332 ** of the SQLite library that is running.
78333 */
78334 static void versionFunc(
78335   sqlite3_context *context,
78336   int NotUsed,
78337   sqlite3_value **NotUsed2
78338 ){
78339   UNUSED_PARAMETER2(NotUsed, NotUsed2);
78340   /* IMP: R-48699-48617 This function is an SQL wrapper around the
78341   ** sqlite3_libversion() C-interface. */
78342   sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
78343 }
78344
78345 /*
78346 ** Implementation of the sqlite_source_id() function. The result is a string
78347 ** that identifies the particular version of the source code used to build
78348 ** SQLite.
78349 */
78350 static void sourceidFunc(
78351   sqlite3_context *context,
78352   int NotUsed,
78353   sqlite3_value **NotUsed2
78354 ){
78355   UNUSED_PARAMETER2(NotUsed, NotUsed2);
78356   /* IMP: R-24470-31136 This function is an SQL wrapper around the
78357   ** sqlite3_sourceid() C interface. */
78358   sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
78359 }
78360
78361 /*
78362 ** Implementation of the sqlite_compileoption_used() function.
78363 ** The result is an integer that identifies if the compiler option
78364 ** was used to build SQLite.
78365 */
78366 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
78367 static void compileoptionusedFunc(
78368   sqlite3_context *context,
78369   int argc,
78370   sqlite3_value **argv
78371 ){
78372   const char *zOptName;
78373   assert( argc==1 );
78374   UNUSED_PARAMETER(argc);
78375   /* IMP: R-xxxx This function is an SQL wrapper around the
78376   ** sqlite3_compileoption_used() C interface. */
78377   if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
78378     sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
78379   }
78380 }
78381 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
78382
78383 /*
78384 ** Implementation of the sqlite_compileoption_get() function. 
78385 ** The result is a string that identifies the compiler options 
78386 ** used to build SQLite.
78387 */
78388 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
78389 static void compileoptiongetFunc(
78390   sqlite3_context *context,
78391   int argc,
78392   sqlite3_value **argv
78393 ){
78394   int n;
78395   assert( argc==1 );
78396   UNUSED_PARAMETER(argc);
78397   /* IMP: R-xxxx This function is an SQL wrapper around the
78398   ** sqlite3_compileoption_get() C interface. */
78399   n = sqlite3_value_int(argv[0]);
78400   sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
78401 }
78402 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
78403
78404 /* Array for converting from half-bytes (nybbles) into ASCII hex
78405 ** digits. */
78406 static const char hexdigits[] = {
78407   '0', '1', '2', '3', '4', '5', '6', '7',
78408   '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' 
78409 };
78410
78411 /*
78412 ** EXPERIMENTAL - This is not an official function.  The interface may
78413 ** change.  This function may disappear.  Do not write code that depends
78414 ** on this function.
78415 **
78416 ** Implementation of the QUOTE() function.  This function takes a single
78417 ** argument.  If the argument is numeric, the return value is the same as
78418 ** the argument.  If the argument is NULL, the return value is the string
78419 ** "NULL".  Otherwise, the argument is enclosed in single quotes with
78420 ** single-quote escapes.
78421 */
78422 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
78423   assert( argc==1 );
78424   UNUSED_PARAMETER(argc);
78425   switch( sqlite3_value_type(argv[0]) ){
78426     case SQLITE_INTEGER:
78427     case SQLITE_FLOAT: {
78428       sqlite3_result_value(context, argv[0]);
78429       break;
78430     }
78431     case SQLITE_BLOB: {
78432       char *zText = 0;
78433       char const *zBlob = sqlite3_value_blob(argv[0]);
78434       int nBlob = sqlite3_value_bytes(argv[0]);
78435       assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
78436       zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4); 
78437       if( zText ){
78438         int i;
78439         for(i=0; i<nBlob; i++){
78440           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
78441           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
78442         }
78443         zText[(nBlob*2)+2] = '\'';
78444         zText[(nBlob*2)+3] = '\0';
78445         zText[0] = 'X';
78446         zText[1] = '\'';
78447         sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
78448         sqlite3_free(zText);
78449       }
78450       break;
78451     }
78452     case SQLITE_TEXT: {
78453       int i,j;
78454       u64 n;
78455       const unsigned char *zArg = sqlite3_value_text(argv[0]);
78456       char *z;
78457
78458       if( zArg==0 ) return;
78459       for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
78460       z = contextMalloc(context, ((i64)i)+((i64)n)+3);
78461       if( z ){
78462         z[0] = '\'';
78463         for(i=0, j=1; zArg[i]; i++){
78464           z[j++] = zArg[i];
78465           if( zArg[i]=='\'' ){
78466             z[j++] = '\'';
78467           }
78468         }
78469         z[j++] = '\'';
78470         z[j] = 0;
78471         sqlite3_result_text(context, z, j, sqlite3_free);
78472       }
78473       break;
78474     }
78475     default: {
78476       assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
78477       sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
78478       break;
78479     }
78480   }
78481 }
78482
78483 /*
78484 ** The hex() function.  Interpret the argument as a blob.  Return
78485 ** a hexadecimal rendering as text.
78486 */
78487 static void hexFunc(
78488   sqlite3_context *context,
78489   int argc,
78490   sqlite3_value **argv
78491 ){
78492   int i, n;
78493   const unsigned char *pBlob;
78494   char *zHex, *z;
78495   assert( argc==1 );
78496   UNUSED_PARAMETER(argc);
78497   pBlob = sqlite3_value_blob(argv[0]);
78498   n = sqlite3_value_bytes(argv[0]);
78499   assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
78500   z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
78501   if( zHex ){
78502     for(i=0; i<n; i++, pBlob++){
78503       unsigned char c = *pBlob;
78504       *(z++) = hexdigits[(c>>4)&0xf];
78505       *(z++) = hexdigits[c&0xf];
78506     }
78507     *z = 0;
78508     sqlite3_result_text(context, zHex, n*2, sqlite3_free);
78509   }
78510 }
78511
78512 /*
78513 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
78514 */
78515 static void zeroblobFunc(
78516   sqlite3_context *context,
78517   int argc,
78518   sqlite3_value **argv
78519 ){
78520   i64 n;
78521   sqlite3 *db = sqlite3_context_db_handle(context);
78522   assert( argc==1 );
78523   UNUSED_PARAMETER(argc);
78524   n = sqlite3_value_int64(argv[0]);
78525   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
78526   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
78527   if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
78528     sqlite3_result_error_toobig(context);
78529   }else{
78530     sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
78531   }
78532 }
78533
78534 /*
78535 ** The replace() function.  Three arguments are all strings: call
78536 ** them A, B, and C. The result is also a string which is derived
78537 ** from A by replacing every occurance of B with C.  The match
78538 ** must be exact.  Collating sequences are not used.
78539 */
78540 static void replaceFunc(
78541   sqlite3_context *context,
78542   int argc,
78543   sqlite3_value **argv
78544 ){
78545   const unsigned char *zStr;        /* The input string A */
78546   const unsigned char *zPattern;    /* The pattern string B */
78547   const unsigned char *zRep;        /* The replacement string C */
78548   unsigned char *zOut;              /* The output */
78549   int nStr;                /* Size of zStr */
78550   int nPattern;            /* Size of zPattern */
78551   int nRep;                /* Size of zRep */
78552   i64 nOut;                /* Maximum size of zOut */
78553   int loopLimit;           /* Last zStr[] that might match zPattern[] */
78554   int i, j;                /* Loop counters */
78555
78556   assert( argc==3 );
78557   UNUSED_PARAMETER(argc);
78558   zStr = sqlite3_value_text(argv[0]);
78559   if( zStr==0 ) return;
78560   nStr = sqlite3_value_bytes(argv[0]);
78561   assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
78562   zPattern = sqlite3_value_text(argv[1]);
78563   if( zPattern==0 ){
78564     assert( sqlite3_value_type(argv[1])==SQLITE_NULL
78565             || sqlite3_context_db_handle(context)->mallocFailed );
78566     return;
78567   }
78568   if( zPattern[0]==0 ){
78569     assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
78570     sqlite3_result_value(context, argv[0]);
78571     return;
78572   }
78573   nPattern = sqlite3_value_bytes(argv[1]);
78574   assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
78575   zRep = sqlite3_value_text(argv[2]);
78576   if( zRep==0 ) return;
78577   nRep = sqlite3_value_bytes(argv[2]);
78578   assert( zRep==sqlite3_value_text(argv[2]) );
78579   nOut = nStr + 1;
78580   assert( nOut<SQLITE_MAX_LENGTH );
78581   zOut = contextMalloc(context, (i64)nOut);
78582   if( zOut==0 ){
78583     return;
78584   }
78585   loopLimit = nStr - nPattern;  
78586   for(i=j=0; i<=loopLimit; i++){
78587     if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
78588       zOut[j++] = zStr[i];
78589     }else{
78590       u8 *zOld;
78591       sqlite3 *db = sqlite3_context_db_handle(context);
78592       nOut += nRep - nPattern;
78593       testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
78594       testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
78595       if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
78596         sqlite3_result_error_toobig(context);
78597         sqlite3DbFree(db, zOut);
78598         return;
78599       }
78600       zOld = zOut;
78601       zOut = sqlite3_realloc(zOut, (int)nOut);
78602       if( zOut==0 ){
78603         sqlite3_result_error_nomem(context);
78604         sqlite3DbFree(db, zOld);
78605         return;
78606       }
78607       memcpy(&zOut[j], zRep, nRep);
78608       j += nRep;
78609       i += nPattern-1;
78610     }
78611   }
78612   assert( j+nStr-i+1==nOut );
78613   memcpy(&zOut[j], &zStr[i], nStr-i);
78614   j += nStr - i;
78615   assert( j<=nOut );
78616   zOut[j] = 0;
78617   sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
78618 }
78619
78620 /*
78621 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
78622 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
78623 */
78624 static void trimFunc(
78625   sqlite3_context *context,
78626   int argc,
78627   sqlite3_value **argv
78628 ){
78629   const unsigned char *zIn;         /* Input string */
78630   const unsigned char *zCharSet;    /* Set of characters to trim */
78631   int nIn;                          /* Number of bytes in input */
78632   int flags;                        /* 1: trimleft  2: trimright  3: trim */
78633   int i;                            /* Loop counter */
78634   unsigned char *aLen = 0;          /* Length of each character in zCharSet */
78635   unsigned char **azChar = 0;       /* Individual characters in zCharSet */
78636   int nChar;                        /* Number of characters in zCharSet */
78637
78638   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
78639     return;
78640   }
78641   zIn = sqlite3_value_text(argv[0]);
78642   if( zIn==0 ) return;
78643   nIn = sqlite3_value_bytes(argv[0]);
78644   assert( zIn==sqlite3_value_text(argv[0]) );
78645   if( argc==1 ){
78646     static const unsigned char lenOne[] = { 1 };
78647     static unsigned char * const azOne[] = { (u8*)" " };
78648     nChar = 1;
78649     aLen = (u8*)lenOne;
78650     azChar = (unsigned char **)azOne;
78651     zCharSet = 0;
78652   }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
78653     return;
78654   }else{
78655     const unsigned char *z;
78656     for(z=zCharSet, nChar=0; *z; nChar++){
78657       SQLITE_SKIP_UTF8(z);
78658     }
78659     if( nChar>0 ){
78660       azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
78661       if( azChar==0 ){
78662         return;
78663       }
78664       aLen = (unsigned char*)&azChar[nChar];
78665       for(z=zCharSet, nChar=0; *z; nChar++){
78666         azChar[nChar] = (unsigned char *)z;
78667         SQLITE_SKIP_UTF8(z);
78668         aLen[nChar] = (u8)(z - azChar[nChar]);
78669       }
78670     }
78671   }
78672   if( nChar>0 ){
78673     flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
78674     if( flags & 1 ){
78675       while( nIn>0 ){
78676         int len = 0;
78677         for(i=0; i<nChar; i++){
78678           len = aLen[i];
78679           if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
78680         }
78681         if( i>=nChar ) break;
78682         zIn += len;
78683         nIn -= len;
78684       }
78685     }
78686     if( flags & 2 ){
78687       while( nIn>0 ){
78688         int len = 0;
78689         for(i=0; i<nChar; i++){
78690           len = aLen[i];
78691           if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
78692         }
78693         if( i>=nChar ) break;
78694         nIn -= len;
78695       }
78696     }
78697     if( zCharSet ){
78698       sqlite3_free(azChar);
78699     }
78700   }
78701   sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
78702 }
78703
78704
78705 /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
78706 ** is only available if the SQLITE_SOUNDEX compile-time option is used
78707 ** when SQLite is built.
78708 */
78709 #ifdef SQLITE_SOUNDEX
78710 /*
78711 ** Compute the soundex encoding of a word.
78712 **
78713 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
78714 ** soundex encoding of the string X. 
78715 */
78716 static void soundexFunc(
78717   sqlite3_context *context,
78718   int argc,
78719   sqlite3_value **argv
78720 ){
78721   char zResult[8];
78722   const u8 *zIn;
78723   int i, j;
78724   static const unsigned char iCode[] = {
78725     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
78726     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
78727     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
78728     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
78729     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
78730     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
78731     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
78732     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
78733   };
78734   assert( argc==1 );
78735   zIn = (u8*)sqlite3_value_text(argv[0]);
78736   if( zIn==0 ) zIn = (u8*)"";
78737   for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
78738   if( zIn[i] ){
78739     u8 prevcode = iCode[zIn[i]&0x7f];
78740     zResult[0] = sqlite3Toupper(zIn[i]);
78741     for(j=1; j<4 && zIn[i]; i++){
78742       int code = iCode[zIn[i]&0x7f];
78743       if( code>0 ){
78744         if( code!=prevcode ){
78745           prevcode = code;
78746           zResult[j++] = code + '0';
78747         }
78748       }else{
78749         prevcode = 0;
78750       }
78751     }
78752     while( j<4 ){
78753       zResult[j++] = '0';
78754     }
78755     zResult[j] = 0;
78756     sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
78757   }else{
78758     /* IMP: R-64894-50321 The string "?000" is returned if the argument
78759     ** is NULL or contains no ASCII alphabetic characters. */
78760     sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
78761   }
78762 }
78763 #endif /* SQLITE_SOUNDEX */
78764
78765 #ifndef SQLITE_OMIT_LOAD_EXTENSION
78766 /*
78767 ** A function that loads a shared-library extension then returns NULL.
78768 */
78769 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
78770   const char *zFile = (const char *)sqlite3_value_text(argv[0]);
78771   const char *zProc;
78772   sqlite3 *db = sqlite3_context_db_handle(context);
78773   char *zErrMsg = 0;
78774
78775   if( argc==2 ){
78776     zProc = (const char *)sqlite3_value_text(argv[1]);
78777   }else{
78778     zProc = 0;
78779   }
78780   if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
78781     sqlite3_result_error(context, zErrMsg, -1);
78782     sqlite3_free(zErrMsg);
78783   }
78784 }
78785 #endif
78786
78787
78788 /*
78789 ** An instance of the following structure holds the context of a
78790 ** sum() or avg() aggregate computation.
78791 */
78792 typedef struct SumCtx SumCtx;
78793 struct SumCtx {
78794   double rSum;      /* Floating point sum */
78795   i64 iSum;         /* Integer sum */   
78796   i64 cnt;          /* Number of elements summed */
78797   u8 overflow;      /* True if integer overflow seen */
78798   u8 approx;        /* True if non-integer value was input to the sum */
78799 };
78800
78801 /*
78802 ** Routines used to compute the sum, average, and total.
78803 **
78804 ** The SUM() function follows the (broken) SQL standard which means
78805 ** that it returns NULL if it sums over no inputs.  TOTAL returns
78806 ** 0.0 in that case.  In addition, TOTAL always returns a float where
78807 ** SUM might return an integer if it never encounters a floating point
78808 ** value.  TOTAL never fails, but SUM might through an exception if
78809 ** it overflows an integer.
78810 */
78811 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
78812   SumCtx *p;
78813   int type;
78814   assert( argc==1 );
78815   UNUSED_PARAMETER(argc);
78816   p = sqlite3_aggregate_context(context, sizeof(*p));
78817   type = sqlite3_value_numeric_type(argv[0]);
78818   if( p && type!=SQLITE_NULL ){
78819     p->cnt++;
78820     if( type==SQLITE_INTEGER ){
78821       i64 v = sqlite3_value_int64(argv[0]);
78822       p->rSum += v;
78823       if( (p->approx|p->overflow)==0 ){
78824         i64 iNewSum = p->iSum + v;
78825         int s1 = (int)(p->iSum >> (sizeof(i64)*8-1));
78826         int s2 = (int)(v       >> (sizeof(i64)*8-1));
78827         int s3 = (int)(iNewSum >> (sizeof(i64)*8-1));
78828         p->overflow = ((s1&s2&~s3) | (~s1&~s2&s3))?1:0;
78829         p->iSum = iNewSum;
78830       }
78831     }else{
78832       p->rSum += sqlite3_value_double(argv[0]);
78833       p->approx = 1;
78834     }
78835   }
78836 }
78837 static void sumFinalize(sqlite3_context *context){
78838   SumCtx *p;
78839   p = sqlite3_aggregate_context(context, 0);
78840   if( p && p->cnt>0 ){
78841     if( p->overflow ){
78842       sqlite3_result_error(context,"integer overflow",-1);
78843     }else if( p->approx ){
78844       sqlite3_result_double(context, p->rSum);
78845     }else{
78846       sqlite3_result_int64(context, p->iSum);
78847     }
78848   }
78849 }
78850 static void avgFinalize(sqlite3_context *context){
78851   SumCtx *p;
78852   p = sqlite3_aggregate_context(context, 0);
78853   if( p && p->cnt>0 ){
78854     sqlite3_result_double(context, p->rSum/(double)p->cnt);
78855   }
78856 }
78857 static void totalFinalize(sqlite3_context *context){
78858   SumCtx *p;
78859   p = sqlite3_aggregate_context(context, 0);
78860   /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
78861   sqlite3_result_double(context, p ? p->rSum : (double)0);
78862 }
78863
78864 /*
78865 ** The following structure keeps track of state information for the
78866 ** count() aggregate function.
78867 */
78868 typedef struct CountCtx CountCtx;
78869 struct CountCtx {
78870   i64 n;
78871 };
78872
78873 /*
78874 ** Routines to implement the count() aggregate function.
78875 */
78876 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
78877   CountCtx *p;
78878   p = sqlite3_aggregate_context(context, sizeof(*p));
78879   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
78880     p->n++;
78881   }
78882
78883 #ifndef SQLITE_OMIT_DEPRECATED
78884   /* The sqlite3_aggregate_count() function is deprecated.  But just to make
78885   ** sure it still operates correctly, verify that its count agrees with our 
78886   ** internal count when using count(*) and when the total count can be
78887   ** expressed as a 32-bit integer. */
78888   assert( argc==1 || p==0 || p->n>0x7fffffff
78889           || p->n==sqlite3_aggregate_count(context) );
78890 #endif
78891 }   
78892 static void countFinalize(sqlite3_context *context){
78893   CountCtx *p;
78894   p = sqlite3_aggregate_context(context, 0);
78895   sqlite3_result_int64(context, p ? p->n : 0);
78896 }
78897
78898 /*
78899 ** Routines to implement min() and max() aggregate functions.
78900 */
78901 static void minmaxStep(
78902   sqlite3_context *context, 
78903   int NotUsed, 
78904   sqlite3_value **argv
78905 ){
78906   Mem *pArg  = (Mem *)argv[0];
78907   Mem *pBest;
78908   UNUSED_PARAMETER(NotUsed);
78909
78910   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
78911   pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
78912   if( !pBest ) return;
78913
78914   if( pBest->flags ){
78915     int max;
78916     int cmp;
78917     CollSeq *pColl = sqlite3GetFuncCollSeq(context);
78918     /* This step function is used for both the min() and max() aggregates,
78919     ** the only difference between the two being that the sense of the
78920     ** comparison is inverted. For the max() aggregate, the
78921     ** sqlite3_user_data() function returns (void *)-1. For min() it
78922     ** returns (void *)db, where db is the sqlite3* database pointer.
78923     ** Therefore the next statement sets variable 'max' to 1 for the max()
78924     ** aggregate, or 0 for min().
78925     */
78926     max = sqlite3_user_data(context)!=0;
78927     cmp = sqlite3MemCompare(pBest, pArg, pColl);
78928     if( (max && cmp<0) || (!max && cmp>0) ){
78929       sqlite3VdbeMemCopy(pBest, pArg);
78930     }
78931   }else{
78932     sqlite3VdbeMemCopy(pBest, pArg);
78933   }
78934 }
78935 static void minMaxFinalize(sqlite3_context *context){
78936   sqlite3_value *pRes;
78937   pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
78938   if( pRes ){
78939     if( ALWAYS(pRes->flags) ){
78940       sqlite3_result_value(context, pRes);
78941     }
78942     sqlite3VdbeMemRelease(pRes);
78943   }
78944 }
78945
78946 /*
78947 ** group_concat(EXPR, ?SEPARATOR?)
78948 */
78949 static void groupConcatStep(
78950   sqlite3_context *context,
78951   int argc,
78952   sqlite3_value **argv
78953 ){
78954   const char *zVal;
78955   StrAccum *pAccum;
78956   const char *zSep;
78957   int nVal, nSep;
78958   assert( argc==1 || argc==2 );
78959   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
78960   pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
78961
78962   if( pAccum ){
78963     sqlite3 *db = sqlite3_context_db_handle(context);
78964     int firstTerm = pAccum->useMalloc==0;
78965     pAccum->useMalloc = 1;
78966     pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
78967     if( !firstTerm ){
78968       if( argc==2 ){
78969         zSep = (char*)sqlite3_value_text(argv[1]);
78970         nSep = sqlite3_value_bytes(argv[1]);
78971       }else{
78972         zSep = ",";
78973         nSep = 1;
78974       }
78975       sqlite3StrAccumAppend(pAccum, zSep, nSep);
78976     }
78977     zVal = (char*)sqlite3_value_text(argv[0]);
78978     nVal = sqlite3_value_bytes(argv[0]);
78979     sqlite3StrAccumAppend(pAccum, zVal, nVal);
78980   }
78981 }
78982 static void groupConcatFinalize(sqlite3_context *context){
78983   StrAccum *pAccum;
78984   pAccum = sqlite3_aggregate_context(context, 0);
78985   if( pAccum ){
78986     if( pAccum->tooBig ){
78987       sqlite3_result_error_toobig(context);
78988     }else if( pAccum->mallocFailed ){
78989       sqlite3_result_error_nomem(context);
78990     }else{    
78991       sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1, 
78992                           sqlite3_free);
78993     }
78994   }
78995 }
78996
78997 /*
78998 ** This routine does per-connection function registration.  Most
78999 ** of the built-in functions above are part of the global function set.
79000 ** This routine only deals with those that are not global.
79001 */
79002 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
79003   int rc = sqlite3_overload_function(db, "MATCH", 2);
79004   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
79005   if( rc==SQLITE_NOMEM ){
79006     db->mallocFailed = 1;
79007   }
79008 }
79009
79010 /*
79011 ** Set the LIKEOPT flag on the 2-argument function with the given name.
79012 */
79013 static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
79014   FuncDef *pDef;
79015   pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
79016                              2, SQLITE_UTF8, 0);
79017   if( ALWAYS(pDef) ){
79018     pDef->flags = flagVal;
79019   }
79020 }
79021
79022 /*
79023 ** Register the built-in LIKE and GLOB functions.  The caseSensitive
79024 ** parameter determines whether or not the LIKE operator is case
79025 ** sensitive.  GLOB is always case sensitive.
79026 */
79027 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
79028   struct compareInfo *pInfo;
79029   if( caseSensitive ){
79030     pInfo = (struct compareInfo*)&likeInfoAlt;
79031   }else{
79032     pInfo = (struct compareInfo*)&likeInfoNorm;
79033   }
79034   sqlite3CreateFunc(db, "like", 2, SQLITE_ANY, pInfo, likeFunc, 0, 0);
79035   sqlite3CreateFunc(db, "like", 3, SQLITE_ANY, pInfo, likeFunc, 0, 0);
79036   sqlite3CreateFunc(db, "glob", 2, SQLITE_ANY, 
79037       (struct compareInfo*)&globInfo, likeFunc, 0,0);
79038   setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
79039   setLikeOptFlag(db, "like", 
79040       caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
79041 }
79042
79043 /*
79044 ** pExpr points to an expression which implements a function.  If
79045 ** it is appropriate to apply the LIKE optimization to that function
79046 ** then set aWc[0] through aWc[2] to the wildcard characters and
79047 ** return TRUE.  If the function is not a LIKE-style function then
79048 ** return FALSE.
79049 */
79050 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
79051   FuncDef *pDef;
79052   if( pExpr->op!=TK_FUNCTION 
79053    || !pExpr->x.pList 
79054    || pExpr->x.pList->nExpr!=2
79055   ){
79056     return 0;
79057   }
79058   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
79059   pDef = sqlite3FindFunction(db, pExpr->u.zToken, 
79060                              sqlite3Strlen30(pExpr->u.zToken),
79061                              2, SQLITE_UTF8, 0);
79062   if( NEVER(pDef==0) || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
79063     return 0;
79064   }
79065
79066   /* The memcpy() statement assumes that the wildcard characters are
79067   ** the first three statements in the compareInfo structure.  The
79068   ** asserts() that follow verify that assumption
79069   */
79070   memcpy(aWc, pDef->pUserData, 3);
79071   assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
79072   assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
79073   assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
79074   *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
79075   return 1;
79076 }
79077
79078 /*
79079 ** All all of the FuncDef structures in the aBuiltinFunc[] array above
79080 ** to the global function hash table.  This occurs at start-time (as
79081 ** a consequence of calling sqlite3_initialize()).
79082 **
79083 ** After this routine runs
79084 */
79085 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
79086   /*
79087   ** The following array holds FuncDef structures for all of the functions
79088   ** defined in this file.
79089   **
79090   ** The array cannot be constant since changes are made to the
79091   ** FuncDef.pHash elements at start-time.  The elements of this array
79092   ** are read-only after initialization is complete.
79093   */
79094   static SQLITE_WSD FuncDef aBuiltinFunc[] = {
79095     FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
79096     FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
79097     FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
79098     FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
79099     FUNCTION(trim,               1, 3, 0, trimFunc         ),
79100     FUNCTION(trim,               2, 3, 0, trimFunc         ),
79101     FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
79102     FUNCTION(min,                0, 0, 1, 0                ),
79103     AGGREGATE(min,               1, 0, 1, minmaxStep,      minMaxFinalize ),
79104     FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
79105     FUNCTION(max,                0, 1, 1, 0                ),
79106     AGGREGATE(max,               1, 1, 1, minmaxStep,      minMaxFinalize ),
79107     FUNCTION(typeof,             1, 0, 0, typeofFunc       ),
79108     FUNCTION(length,             1, 0, 0, lengthFunc       ),
79109     FUNCTION(substr,             2, 0, 0, substrFunc       ),
79110     FUNCTION(substr,             3, 0, 0, substrFunc       ),
79111     FUNCTION(abs,                1, 0, 0, absFunc          ),
79112 #ifndef SQLITE_OMIT_FLOATING_POINT
79113     FUNCTION(round,              1, 0, 0, roundFunc        ),
79114     FUNCTION(round,              2, 0, 0, roundFunc        ),
79115 #endif
79116     FUNCTION(upper,              1, 0, 0, upperFunc        ),
79117     FUNCTION(lower,              1, 0, 0, lowerFunc        ),
79118     FUNCTION(coalesce,           1, 0, 0, 0                ),
79119     FUNCTION(coalesce,           0, 0, 0, 0                ),
79120 /*  FUNCTION(coalesce,          -1, 0, 0, ifnullFunc       ), */
79121     {-1,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"coalesce",0},
79122     FUNCTION(hex,                1, 0, 0, hexFunc          ),
79123 /*  FUNCTION(ifnull,             2, 0, 0, ifnullFunc       ), */
79124     {2,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"ifnull",0},
79125     FUNCTION(random,             0, 0, 0, randomFunc       ),
79126     FUNCTION(randomblob,         1, 0, 0, randomBlob       ),
79127     FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
79128     FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),
79129     FUNCTION(sqlite_source_id,   0, 0, 0, sourceidFunc     ),
79130 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
79131     FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
79132     FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
79133 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
79134     FUNCTION(quote,              1, 0, 0, quoteFunc        ),
79135     FUNCTION(last_insert_rowid,  0, 0, 0, last_insert_rowid),
79136     FUNCTION(changes,            0, 0, 0, changes          ),
79137     FUNCTION(total_changes,      0, 0, 0, total_changes    ),
79138     FUNCTION(replace,            3, 0, 0, replaceFunc      ),
79139     FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
79140   #ifdef SQLITE_SOUNDEX
79141     FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
79142   #endif
79143   #ifndef SQLITE_OMIT_LOAD_EXTENSION
79144     FUNCTION(load_extension,     1, 0, 0, loadExt          ),
79145     FUNCTION(load_extension,     2, 0, 0, loadExt          ),
79146   #endif
79147     AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
79148     AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
79149     AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
79150  /* AGGREGATE(count,             0, 0, 0, countStep,       countFinalize  ), */
79151     {0,SQLITE_UTF8,SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0},
79152     AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
79153     AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
79154     AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
79155   
79156     LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
79157   #ifdef SQLITE_CASE_SENSITIVE_LIKE
79158     LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
79159     LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
79160   #else
79161     LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
79162     LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
79163   #endif
79164   };
79165
79166   int i;
79167   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
79168   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
79169
79170   for(i=0; i<ArraySize(aBuiltinFunc); i++){
79171     sqlite3FuncDefInsert(pHash, &aFunc[i]);
79172   }
79173   sqlite3RegisterDateTimeFunctions();
79174 #ifndef SQLITE_OMIT_ALTERTABLE
79175   sqlite3AlterFunctions();
79176 #endif
79177 }
79178
79179 /************** End of func.c ************************************************/
79180 /************** Begin file fkey.c ********************************************/
79181 /*
79182 **
79183 ** The author disclaims copyright to this source code.  In place of
79184 ** a legal notice, here is a blessing:
79185 **
79186 **    May you do good and not evil.
79187 **    May you find forgiveness for yourself and forgive others.
79188 **    May you share freely, never taking more than you give.
79189 **
79190 *************************************************************************
79191 ** This file contains code used by the compiler to add foreign key
79192 ** support to compiled SQL statements.
79193 */
79194
79195 #ifndef SQLITE_OMIT_FOREIGN_KEY
79196 #ifndef SQLITE_OMIT_TRIGGER
79197
79198 /*
79199 ** Deferred and Immediate FKs
79200 ** --------------------------
79201 **
79202 ** Foreign keys in SQLite come in two flavours: deferred and immediate.
79203 ** If an immediate foreign key constraint is violated, SQLITE_CONSTRAINT
79204 ** is returned and the current statement transaction rolled back. If a 
79205 ** deferred foreign key constraint is violated, no action is taken 
79206 ** immediately. However if the application attempts to commit the 
79207 ** transaction before fixing the constraint violation, the attempt fails.
79208 **
79209 ** Deferred constraints are implemented using a simple counter associated
79210 ** with the database handle. The counter is set to zero each time a 
79211 ** database transaction is opened. Each time a statement is executed 
79212 ** that causes a foreign key violation, the counter is incremented. Each
79213 ** time a statement is executed that removes an existing violation from
79214 ** the database, the counter is decremented. When the transaction is
79215 ** committed, the commit fails if the current value of the counter is
79216 ** greater than zero. This scheme has two big drawbacks:
79217 **
79218 **   * When a commit fails due to a deferred foreign key constraint, 
79219 **     there is no way to tell which foreign constraint is not satisfied,
79220 **     or which row it is not satisfied for.
79221 **
79222 **   * If the database contains foreign key violations when the 
79223 **     transaction is opened, this may cause the mechanism to malfunction.
79224 **
79225 ** Despite these problems, this approach is adopted as it seems simpler
79226 ** than the alternatives.
79227 **
79228 ** INSERT operations:
79229 **
79230 **   I.1) For each FK for which the table is the child table, search
79231 **        the parent table for a match. If none is found increment the
79232 **        constraint counter.
79233 **
79234 **   I.2) For each FK for which the table is the parent table, 
79235 **        search the child table for rows that correspond to the new
79236 **        row in the parent table. Decrement the counter for each row
79237 **        found (as the constraint is now satisfied).
79238 **
79239 ** DELETE operations:
79240 **
79241 **   D.1) For each FK for which the table is the child table, 
79242 **        search the parent table for a row that corresponds to the 
79243 **        deleted row in the child table. If such a row is not found, 
79244 **        decrement the counter.
79245 **
79246 **   D.2) For each FK for which the table is the parent table, search 
79247 **        the child table for rows that correspond to the deleted row 
79248 **        in the parent table. For each found increment the counter.
79249 **
79250 ** UPDATE operations:
79251 **
79252 **   An UPDATE command requires that all 4 steps above are taken, but only
79253 **   for FK constraints for which the affected columns are actually 
79254 **   modified (values must be compared at runtime).
79255 **
79256 ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
79257 ** This simplifies the implementation a bit.
79258 **
79259 ** For the purposes of immediate FK constraints, the OR REPLACE conflict
79260 ** resolution is considered to delete rows before the new row is inserted.
79261 ** If a delete caused by OR REPLACE violates an FK constraint, an exception
79262 ** is thrown, even if the FK constraint would be satisfied after the new 
79263 ** row is inserted.
79264 **
79265 ** Immediate constraints are usually handled similarly. The only difference 
79266 ** is that the counter used is stored as part of each individual statement
79267 ** object (struct Vdbe). If, after the statement has run, its immediate
79268 ** constraint counter is greater than zero, it returns SQLITE_CONSTRAINT
79269 ** and the statement transaction is rolled back. An exception is an INSERT
79270 ** statement that inserts a single row only (no triggers). In this case,
79271 ** instead of using a counter, an exception is thrown immediately if the
79272 ** INSERT violates a foreign key constraint. This is necessary as such
79273 ** an INSERT does not open a statement transaction.
79274 **
79275 ** TODO: How should dropping a table be handled? How should renaming a 
79276 ** table be handled?
79277 **
79278 **
79279 ** Query API Notes
79280 ** ---------------
79281 **
79282 ** Before coding an UPDATE or DELETE row operation, the code-generator
79283 ** for those two operations needs to know whether or not the operation
79284 ** requires any FK processing and, if so, which columns of the original
79285 ** row are required by the FK processing VDBE code (i.e. if FKs were
79286 ** implemented using triggers, which of the old.* columns would be 
79287 ** accessed). No information is required by the code-generator before
79288 ** coding an INSERT operation. The functions used by the UPDATE/DELETE
79289 ** generation code to query for this information are:
79290 **
79291 **   sqlite3FkRequired() - Test to see if FK processing is required.
79292 **   sqlite3FkOldmask()  - Query for the set of required old.* columns.
79293 **
79294 **
79295 ** Externally accessible module functions
79296 ** --------------------------------------
79297 **
79298 **   sqlite3FkCheck()    - Check for foreign key violations.
79299 **   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
79300 **   sqlite3FkDelete()   - Delete an FKey structure.
79301 */
79302
79303 /*
79304 ** VDBE Calling Convention
79305 ** -----------------------
79306 **
79307 ** Example:
79308 **
79309 **   For the following INSERT statement:
79310 **
79311 **     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
79312 **     INSERT INTO t1 VALUES(1, 2, 3.1);
79313 **
79314 **   Register (x):        2    (type integer)
79315 **   Register (x+1):      1    (type integer)
79316 **   Register (x+2):      NULL (type NULL)
79317 **   Register (x+3):      3.1  (type real)
79318 */
79319
79320 /*
79321 ** A foreign key constraint requires that the key columns in the parent
79322 ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
79323 ** Given that pParent is the parent table for foreign key constraint pFKey, 
79324 ** search the schema a unique index on the parent key columns. 
79325 **
79326 ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY 
79327 ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx 
79328 ** is set to point to the unique index. 
79329 ** 
79330 ** If the parent key consists of a single column (the foreign key constraint
79331 ** is not a composite foreign key), output variable *paiCol is set to NULL.
79332 ** Otherwise, it is set to point to an allocated array of size N, where
79333 ** N is the number of columns in the parent key. The first element of the
79334 ** array is the index of the child table column that is mapped by the FK
79335 ** constraint to the parent table column stored in the left-most column
79336 ** of index *ppIdx. The second element of the array is the index of the
79337 ** child table column that corresponds to the second left-most column of
79338 ** *ppIdx, and so on.
79339 **
79340 ** If the required index cannot be found, either because:
79341 **
79342 **   1) The named parent key columns do not exist, or
79343 **
79344 **   2) The named parent key columns do exist, but are not subject to a
79345 **      UNIQUE or PRIMARY KEY constraint, or
79346 **
79347 **   3) No parent key columns were provided explicitly as part of the
79348 **      foreign key definition, and the parent table does not have a
79349 **      PRIMARY KEY, or
79350 **
79351 **   4) No parent key columns were provided explicitly as part of the
79352 **      foreign key definition, and the PRIMARY KEY of the parent table 
79353 **      consists of a a different number of columns to the child key in 
79354 **      the child table.
79355 **
79356 ** then non-zero is returned, and a "foreign key mismatch" error loaded
79357 ** into pParse. If an OOM error occurs, non-zero is returned and the
79358 ** pParse->db->mallocFailed flag is set.
79359 */
79360 static int locateFkeyIndex(
79361   Parse *pParse,                  /* Parse context to store any error in */
79362   Table *pParent,                 /* Parent table of FK constraint pFKey */
79363   FKey *pFKey,                    /* Foreign key to find index for */
79364   Index **ppIdx,                  /* OUT: Unique index on parent table */
79365   int **paiCol                    /* OUT: Map of index columns in pFKey */
79366 ){
79367   Index *pIdx = 0;                    /* Value to return via *ppIdx */
79368   int *aiCol = 0;                     /* Value to return via *paiCol */
79369   int nCol = pFKey->nCol;             /* Number of columns in parent key */
79370   char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
79371
79372   /* The caller is responsible for zeroing output parameters. */
79373   assert( ppIdx && *ppIdx==0 );
79374   assert( !paiCol || *paiCol==0 );
79375   assert( pParse );
79376
79377   /* If this is a non-composite (single column) foreign key, check if it 
79378   ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx 
79379   ** and *paiCol set to zero and return early. 
79380   **
79381   ** Otherwise, for a composite foreign key (more than one column), allocate
79382   ** space for the aiCol array (returned via output parameter *paiCol).
79383   ** Non-composite foreign keys do not require the aiCol array.
79384   */
79385   if( nCol==1 ){
79386     /* The FK maps to the IPK if any of the following are true:
79387     **
79388     **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly 
79389     **      mapped to the primary key of table pParent, or
79390     **   2) The FK is explicitly mapped to a column declared as INTEGER
79391     **      PRIMARY KEY.
79392     */
79393     if( pParent->iPKey>=0 ){
79394       if( !zKey ) return 0;
79395       if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
79396     }
79397   }else if( paiCol ){
79398     assert( nCol>1 );
79399     aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
79400     if( !aiCol ) return 1;
79401     *paiCol = aiCol;
79402   }
79403
79404   for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
79405     if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){ 
79406       /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
79407       ** of columns. If each indexed column corresponds to a foreign key
79408       ** column of pFKey, then this index is a winner.  */
79409
79410       if( zKey==0 ){
79411         /* If zKey is NULL, then this foreign key is implicitly mapped to 
79412         ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be 
79413         ** identified by the test (Index.autoIndex==2).  */
79414         if( pIdx->autoIndex==2 ){
79415           if( aiCol ){
79416             int i;
79417             for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
79418           }
79419           break;
79420         }
79421       }else{
79422         /* If zKey is non-NULL, then this foreign key was declared to
79423         ** map to an explicit list of columns in table pParent. Check if this
79424         ** index matches those columns. Also, check that the index uses
79425         ** the default collation sequences for each column. */
79426         int i, j;
79427         for(i=0; i<nCol; i++){
79428           int iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
79429           char *zDfltColl;                  /* Def. collation for column */
79430           char *zIdxCol;                    /* Name of indexed column */
79431
79432           /* If the index uses a collation sequence that is different from
79433           ** the default collation sequence for the column, this index is
79434           ** unusable. Bail out early in this case.  */
79435           zDfltColl = pParent->aCol[iCol].zColl;
79436           if( !zDfltColl ){
79437             zDfltColl = "BINARY";
79438           }
79439           if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
79440
79441           zIdxCol = pParent->aCol[iCol].zName;
79442           for(j=0; j<nCol; j++){
79443             if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
79444               if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
79445               break;
79446             }
79447           }
79448           if( j==nCol ) break;
79449         }
79450         if( i==nCol ) break;      /* pIdx is usable */
79451       }
79452     }
79453   }
79454
79455   if( !pIdx ){
79456     if( !pParse->disableTriggers ){
79457       sqlite3ErrorMsg(pParse, "foreign key mismatch");
79458     }
79459     sqlite3DbFree(pParse->db, aiCol);
79460     return 1;
79461   }
79462
79463   *ppIdx = pIdx;
79464   return 0;
79465 }
79466
79467 /*
79468 ** This function is called when a row is inserted into or deleted from the 
79469 ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed 
79470 ** on the child table of pFKey, this function is invoked twice for each row
79471 ** affected - once to "delete" the old row, and then again to "insert" the
79472 ** new row.
79473 **
79474 ** Each time it is called, this function generates VDBE code to locate the
79475 ** row in the parent table that corresponds to the row being inserted into 
79476 ** or deleted from the child table. If the parent row can be found, no 
79477 ** special action is taken. Otherwise, if the parent row can *not* be
79478 ** found in the parent table:
79479 **
79480 **   Operation | FK type   | Action taken
79481 **   --------------------------------------------------------------------------
79482 **   INSERT      immediate   Increment the "immediate constraint counter".
79483 **
79484 **   DELETE      immediate   Decrement the "immediate constraint counter".
79485 **
79486 **   INSERT      deferred    Increment the "deferred constraint counter".
79487 **
79488 **   DELETE      deferred    Decrement the "deferred constraint counter".
79489 **
79490 ** These operations are identified in the comment at the top of this file 
79491 ** (fkey.c) as "I.1" and "D.1".
79492 */
79493 static void fkLookupParent(
79494   Parse *pParse,        /* Parse context */
79495   int iDb,              /* Index of database housing pTab */
79496   Table *pTab,          /* Parent table of FK pFKey */
79497   Index *pIdx,          /* Unique index on parent key columns in pTab */
79498   FKey *pFKey,          /* Foreign key constraint */
79499   int *aiCol,           /* Map from parent key columns to child table columns */
79500   int regData,          /* Address of array containing child table row */
79501   int nIncr,            /* Increment constraint counter by this */
79502   int isIgnore          /* If true, pretend pTab contains all NULL values */
79503 ){
79504   int i;                                    /* Iterator variable */
79505   Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
79506   int iCur = pParse->nTab - 1;              /* Cursor number to use */
79507   int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */
79508
79509   /* If nIncr is less than zero, then check at runtime if there are any
79510   ** outstanding constraints to resolve. If there are not, there is no need
79511   ** to check if deleting this row resolves any outstanding violations.
79512   **
79513   ** Check if any of the key columns in the child table row are NULL. If 
79514   ** any are, then the constraint is considered satisfied. No need to 
79515   ** search for a matching row in the parent table.  */
79516   if( nIncr<0 ){
79517     sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
79518   }
79519   for(i=0; i<pFKey->nCol; i++){
79520     int iReg = aiCol[i] + regData + 1;
79521     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
79522   }
79523
79524   if( isIgnore==0 ){
79525     if( pIdx==0 ){
79526       /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
79527       ** column of the parent table (table pTab).  */
79528       int iMustBeInt;               /* Address of MustBeInt instruction */
79529       int regTemp = sqlite3GetTempReg(pParse);
79530   
79531       /* Invoke MustBeInt to coerce the child key value to an integer (i.e. 
79532       ** apply the affinity of the parent key). If this fails, then there
79533       ** is no matching parent key. Before using MustBeInt, make a copy of
79534       ** the value. Otherwise, the value inserted into the child key column
79535       ** will have INTEGER affinity applied to it, which may not be correct.  */
79536       sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
79537       iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
79538   
79539       /* If the parent table is the same as the child table, and we are about
79540       ** to increment the constraint-counter (i.e. this is an INSERT operation),
79541       ** then check if the row being inserted matches itself. If so, do not
79542       ** increment the constraint-counter.  */
79543       if( pTab==pFKey->pFrom && nIncr==1 ){
79544         sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
79545       }
79546   
79547       sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
79548       sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
79549       sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
79550       sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
79551       sqlite3VdbeJumpHere(v, iMustBeInt);
79552       sqlite3ReleaseTempReg(pParse, regTemp);
79553     }else{
79554       int nCol = pFKey->nCol;
79555       int regTemp = sqlite3GetTempRange(pParse, nCol);
79556       int regRec = sqlite3GetTempReg(pParse);
79557       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
79558   
79559       sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
79560       sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
79561       for(i=0; i<nCol; i++){
79562         sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[i]+1+regData, regTemp+i);
79563       }
79564   
79565       /* If the parent table is the same as the child table, and we are about
79566       ** to increment the constraint-counter (i.e. this is an INSERT operation),
79567       ** then check if the row being inserted matches itself. If so, do not
79568       ** increment the constraint-counter.  */
79569       if( pTab==pFKey->pFrom && nIncr==1 ){
79570         int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
79571         for(i=0; i<nCol; i++){
79572           int iChild = aiCol[i]+1+regData;
79573           int iParent = pIdx->aiColumn[i]+1+regData;
79574           sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
79575         }
79576         sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
79577       }
79578   
79579       sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
79580       sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
79581       sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);
79582   
79583       sqlite3ReleaseTempReg(pParse, regRec);
79584       sqlite3ReleaseTempRange(pParse, regTemp, nCol);
79585     }
79586   }
79587
79588   if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
79589     /* Special case: If this is an INSERT statement that will insert exactly
79590     ** one row into the table, raise a constraint immediately instead of
79591     ** incrementing a counter. This is necessary as the VM code is being
79592     ** generated for will not open a statement transaction.  */
79593     assert( nIncr==1 );
79594     sqlite3HaltConstraint(
79595         pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
79596     );
79597   }else{
79598     if( nIncr>0 && pFKey->isDeferred==0 ){
79599       sqlite3ParseToplevel(pParse)->mayAbort = 1;
79600     }
79601     sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
79602   }
79603
79604   sqlite3VdbeResolveLabel(v, iOk);
79605   sqlite3VdbeAddOp1(v, OP_Close, iCur);
79606 }
79607
79608 /*
79609 ** This function is called to generate code executed when a row is deleted
79610 ** from the parent table of foreign key constraint pFKey and, if pFKey is 
79611 ** deferred, when a row is inserted into the same table. When generating
79612 ** code for an SQL UPDATE operation, this function may be called twice -
79613 ** once to "delete" the old row and once to "insert" the new row.
79614 **
79615 ** The code generated by this function scans through the rows in the child
79616 ** table that correspond to the parent table row being deleted or inserted.
79617 ** For each child row found, one of the following actions is taken:
79618 **
79619 **   Operation | FK type   | Action taken
79620 **   --------------------------------------------------------------------------
79621 **   DELETE      immediate   Increment the "immediate constraint counter".
79622 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
79623 **                           throw a "foreign key constraint failed" exception.
79624 **
79625 **   INSERT      immediate   Decrement the "immediate constraint counter".
79626 **
79627 **   DELETE      deferred    Increment the "deferred constraint counter".
79628 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
79629 **                           throw a "foreign key constraint failed" exception.
79630 **
79631 **   INSERT      deferred    Decrement the "deferred constraint counter".
79632 **
79633 ** These operations are identified in the comment at the top of this file 
79634 ** (fkey.c) as "I.2" and "D.2".
79635 */
79636 static void fkScanChildren(
79637   Parse *pParse,                  /* Parse context */
79638   SrcList *pSrc,                  /* SrcList containing the table to scan */
79639   Table *pTab,
79640   Index *pIdx,                    /* Foreign key index */
79641   FKey *pFKey,                    /* Foreign key relationship */
79642   int *aiCol,                     /* Map from pIdx cols to child table cols */
79643   int regData,                    /* Referenced table data starts here */
79644   int nIncr                       /* Amount to increment deferred counter by */
79645 ){
79646   sqlite3 *db = pParse->db;       /* Database handle */
79647   int i;                          /* Iterator variable */
79648   Expr *pWhere = 0;               /* WHERE clause to scan with */
79649   NameContext sNameContext;       /* Context used to resolve WHERE clause */
79650   WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
79651   int iFkIfZero = 0;              /* Address of OP_FkIfZero */
79652   Vdbe *v = sqlite3GetVdbe(pParse);
79653
79654   assert( !pIdx || pIdx->pTable==pTab );
79655
79656   if( nIncr<0 ){
79657     iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
79658   }
79659
79660   /* Create an Expr object representing an SQL expression like:
79661   **
79662   **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
79663   **
79664   ** The collation sequence used for the comparison should be that of
79665   ** the parent key columns. The affinity of the parent key column should
79666   ** be applied to each child key value before the comparison takes place.
79667   */
79668   for(i=0; i<pFKey->nCol; i++){
79669     Expr *pLeft;                  /* Value from parent table row */
79670     Expr *pRight;                 /* Column ref to child table */
79671     Expr *pEq;                    /* Expression (pLeft = pRight) */
79672     int iCol;                     /* Index of column in child table */ 
79673     const char *zCol;             /* Name of column in child table */
79674
79675     pLeft = sqlite3Expr(db, TK_REGISTER, 0);
79676     if( pLeft ){
79677       /* Set the collation sequence and affinity of the LHS of each TK_EQ
79678       ** expression to the parent key column defaults.  */
79679       if( pIdx ){
79680         Column *pCol;
79681         iCol = pIdx->aiColumn[i];
79682         pCol = &pIdx->pTable->aCol[iCol];
79683         pLeft->iTable = regData+iCol+1;
79684         pLeft->affinity = pCol->affinity;
79685         pLeft->pColl = sqlite3LocateCollSeq(pParse, pCol->zColl);
79686       }else{
79687         pLeft->iTable = regData;
79688         pLeft->affinity = SQLITE_AFF_INTEGER;
79689       }
79690     }
79691     iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
79692     assert( iCol>=0 );
79693     zCol = pFKey->pFrom->aCol[iCol].zName;
79694     pRight = sqlite3Expr(db, TK_ID, zCol);
79695     pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
79696     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
79697   }
79698
79699   /* If the child table is the same as the parent table, and this scan
79700   ** is taking place as part of a DELETE operation (operation D.2), omit the
79701   ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE 
79702   ** clause, where $rowid is the rowid of the row being deleted.  */
79703   if( pTab==pFKey->pFrom && nIncr>0 ){
79704     Expr *pEq;                    /* Expression (pLeft = pRight) */
79705     Expr *pLeft;                  /* Value from parent table row */
79706     Expr *pRight;                 /* Column ref to child table */
79707     pLeft = sqlite3Expr(db, TK_REGISTER, 0);
79708     pRight = sqlite3Expr(db, TK_COLUMN, 0);
79709     if( pLeft && pRight ){
79710       pLeft->iTable = regData;
79711       pLeft->affinity = SQLITE_AFF_INTEGER;
79712       pRight->iTable = pSrc->a[0].iCursor;
79713       pRight->iColumn = -1;
79714     }
79715     pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
79716     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
79717   }
79718
79719   /* Resolve the references in the WHERE clause. */
79720   memset(&sNameContext, 0, sizeof(NameContext));
79721   sNameContext.pSrcList = pSrc;
79722   sNameContext.pParse = pParse;
79723   sqlite3ResolveExprNames(&sNameContext, pWhere);
79724
79725   /* Create VDBE to loop through the entries in pSrc that match the WHERE
79726   ** clause. If the constraint is not deferred, throw an exception for
79727   ** each row found. Otherwise, for deferred constraints, increment the
79728   ** deferred constraint counter by nIncr for each row selected.  */
79729   pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0);
79730   if( nIncr>0 && pFKey->isDeferred==0 ){
79731     sqlite3ParseToplevel(pParse)->mayAbort = 1;
79732   }
79733   sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
79734   if( pWInfo ){
79735     sqlite3WhereEnd(pWInfo);
79736   }
79737
79738   /* Clean up the WHERE clause constructed above. */
79739   sqlite3ExprDelete(db, pWhere);
79740   if( iFkIfZero ){
79741     sqlite3VdbeJumpHere(v, iFkIfZero);
79742   }
79743 }
79744
79745 /*
79746 ** This function returns a pointer to the head of a linked list of FK
79747 ** constraints for which table pTab is the parent table. For example,
79748 ** given the following schema:
79749 **
79750 **   CREATE TABLE t1(a PRIMARY KEY);
79751 **   CREATE TABLE t2(b REFERENCES t1(a);
79752 **
79753 ** Calling this function with table "t1" as an argument returns a pointer
79754 ** to the FKey structure representing the foreign key constraint on table
79755 ** "t2". Calling this function with "t2" as the argument would return a
79756 ** NULL pointer (as there are no FK constraints for which t2 is the parent
79757 ** table).
79758 */
79759 SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
79760   int nName = sqlite3Strlen30(pTab->zName);
79761   return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
79762 }
79763
79764 /*
79765 ** The second argument is a Trigger structure allocated by the 
79766 ** fkActionTrigger() routine. This function deletes the Trigger structure
79767 ** and all of its sub-components.
79768 **
79769 ** The Trigger structure or any of its sub-components may be allocated from
79770 ** the lookaside buffer belonging to database handle dbMem.
79771 */
79772 static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
79773   if( p ){
79774     TriggerStep *pStep = p->step_list;
79775     sqlite3ExprDelete(dbMem, pStep->pWhere);
79776     sqlite3ExprListDelete(dbMem, pStep->pExprList);
79777     sqlite3SelectDelete(dbMem, pStep->pSelect);
79778     sqlite3ExprDelete(dbMem, p->pWhen);
79779     sqlite3DbFree(dbMem, p);
79780   }
79781 }
79782
79783 /*
79784 ** This function is called to generate code that runs when table pTab is
79785 ** being dropped from the database. The SrcList passed as the second argument
79786 ** to this function contains a single entry guaranteed to resolve to
79787 ** table pTab.
79788 **
79789 ** Normally, no code is required. However, if either
79790 **
79791 **   (a) The table is the parent table of a FK constraint, or
79792 **   (b) The table is the child table of a deferred FK constraint and it is
79793 **       determined at runtime that there are outstanding deferred FK 
79794 **       constraint violations in the database,
79795 **
79796 ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
79797 ** the table from the database. Triggers are disabled while running this
79798 ** DELETE, but foreign key actions are not.
79799 */
79800 SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
79801   sqlite3 *db = pParse->db;
79802   if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
79803     int iSkip = 0;
79804     Vdbe *v = sqlite3GetVdbe(pParse);
79805
79806     assert( v );                  /* VDBE has already been allocated */
79807     if( sqlite3FkReferences(pTab)==0 ){
79808       /* Search for a deferred foreign key constraint for which this table
79809       ** is the child table. If one cannot be found, return without 
79810       ** generating any VDBE code. If one can be found, then jump over
79811       ** the entire DELETE if there are no outstanding deferred constraints
79812       ** when this statement is run.  */
79813       FKey *p;
79814       for(p=pTab->pFKey; p; p=p->pNextFrom){
79815         if( p->isDeferred ) break;
79816       }
79817       if( !p ) return;
79818       iSkip = sqlite3VdbeMakeLabel(v);
79819       sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
79820     }
79821
79822     pParse->disableTriggers = 1;
79823     sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
79824     pParse->disableTriggers = 0;
79825
79826     /* If the DELETE has generated immediate foreign key constraint 
79827     ** violations, halt the VDBE and return an error at this point, before
79828     ** any modifications to the schema are made. This is because statement
79829     ** transactions are not able to rollback schema changes.  */
79830     sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
79831     sqlite3HaltConstraint(
79832         pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
79833     );
79834
79835     if( iSkip ){
79836       sqlite3VdbeResolveLabel(v, iSkip);
79837     }
79838   }
79839 }
79840
79841 /*
79842 ** This function is called when inserting, deleting or updating a row of
79843 ** table pTab to generate VDBE code to perform foreign key constraint 
79844 ** processing for the operation.
79845 **
79846 ** For a DELETE operation, parameter regOld is passed the index of the
79847 ** first register in an array of (pTab->nCol+1) registers containing the
79848 ** rowid of the row being deleted, followed by each of the column values
79849 ** of the row being deleted, from left to right. Parameter regNew is passed
79850 ** zero in this case.
79851 **
79852 ** For an INSERT operation, regOld is passed zero and regNew is passed the
79853 ** first register of an array of (pTab->nCol+1) registers containing the new
79854 ** row data.
79855 **
79856 ** For an UPDATE operation, this function is called twice. Once before
79857 ** the original record is deleted from the table using the calling convention
79858 ** described for DELETE. Then again after the original record is deleted
79859 ** but before the new record is inserted using the INSERT convention. 
79860 */
79861 SQLITE_PRIVATE void sqlite3FkCheck(
79862   Parse *pParse,                  /* Parse context */
79863   Table *pTab,                    /* Row is being deleted from this table */ 
79864   int regOld,                     /* Previous row data is stored here */
79865   int regNew                      /* New row data is stored here */
79866 ){
79867   sqlite3 *db = pParse->db;       /* Database handle */
79868   Vdbe *v;                        /* VM to write code to */
79869   FKey *pFKey;                    /* Used to iterate through FKs */
79870   int iDb;                        /* Index of database containing pTab */
79871   const char *zDb;                /* Name of database containing pTab */
79872   int isIgnoreErrors = pParse->disableTriggers;
79873
79874   /* Exactly one of regOld and regNew should be non-zero. */
79875   assert( (regOld==0)!=(regNew==0) );
79876
79877   /* If foreign-keys are disabled, this function is a no-op. */
79878   if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
79879
79880   v = sqlite3GetVdbe(pParse);
79881   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
79882   zDb = db->aDb[iDb].zName;
79883
79884   /* Loop through all the foreign key constraints for which pTab is the
79885   ** child table (the table that the foreign key definition is part of).  */
79886   for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
79887     Table *pTo;                   /* Parent table of foreign key pFKey */
79888     Index *pIdx = 0;              /* Index on key columns in pTo */
79889     int *aiFree = 0;
79890     int *aiCol;
79891     int iCol;
79892     int i;
79893     int isIgnore = 0;
79894
79895     /* Find the parent table of this foreign key. Also find a unique index 
79896     ** on the parent key columns in the parent table. If either of these 
79897     ** schema items cannot be located, set an error in pParse and return 
79898     ** early.  */
79899     if( pParse->disableTriggers ){
79900       pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
79901     }else{
79902       pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
79903     }
79904     if( !pTo || locateFkeyIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
79905       if( !isIgnoreErrors || db->mallocFailed ) return;
79906       continue;
79907     }
79908     assert( pFKey->nCol==1 || (aiFree && pIdx) );
79909
79910     if( aiFree ){
79911       aiCol = aiFree;
79912     }else{
79913       iCol = pFKey->aCol[0].iFrom;
79914       aiCol = &iCol;
79915     }
79916     for(i=0; i<pFKey->nCol; i++){
79917       if( aiCol[i]==pTab->iPKey ){
79918         aiCol[i] = -1;
79919       }
79920 #ifndef SQLITE_OMIT_AUTHORIZATION
79921       /* Request permission to read the parent key columns. If the 
79922       ** authorization callback returns SQLITE_IGNORE, behave as if any
79923       ** values read from the parent table are NULL. */
79924       if( db->xAuth ){
79925         int rcauth;
79926         char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
79927         rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
79928         isIgnore = (rcauth==SQLITE_IGNORE);
79929       }
79930 #endif
79931     }
79932
79933     /* Take a shared-cache advisory read-lock on the parent table. Allocate 
79934     ** a cursor to use to search the unique index on the parent key columns 
79935     ** in the parent table.  */
79936     sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
79937     pParse->nTab++;
79938
79939     if( regOld!=0 ){
79940       /* A row is being removed from the child table. Search for the parent.
79941       ** If the parent does not exist, removing the child row resolves an 
79942       ** outstanding foreign key constraint violation. */
79943       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
79944     }
79945     if( regNew!=0 ){
79946       /* A row is being added to the child table. If a parent row cannot
79947       ** be found, adding the child row has violated the FK constraint. */ 
79948       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
79949     }
79950
79951     sqlite3DbFree(db, aiFree);
79952   }
79953
79954   /* Loop through all the foreign key constraints that refer to this table */
79955   for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
79956     Index *pIdx = 0;              /* Foreign key index for pFKey */
79957     SrcList *pSrc;
79958     int *aiCol = 0;
79959
79960     if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
79961       assert( regOld==0 && regNew!=0 );
79962       /* Inserting a single row into a parent table cannot cause an immediate
79963       ** foreign key violation. So do nothing in this case.  */
79964       continue;
79965     }
79966
79967     if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
79968       if( !isIgnoreErrors || db->mallocFailed ) return;
79969       continue;
79970     }
79971     assert( aiCol || pFKey->nCol==1 );
79972
79973     /* Create a SrcList structure containing a single table (the table 
79974     ** the foreign key that refers to this table is attached to). This
79975     ** is required for the sqlite3WhereXXX() interface.  */
79976     pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
79977     if( pSrc ){
79978       struct SrcList_item *pItem = pSrc->a;
79979       pItem->pTab = pFKey->pFrom;
79980       pItem->zName = pFKey->pFrom->zName;
79981       pItem->pTab->nRef++;
79982       pItem->iCursor = pParse->nTab++;
79983   
79984       if( regNew!=0 ){
79985         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
79986       }
79987       if( regOld!=0 ){
79988         /* If there is a RESTRICT action configured for the current operation
79989         ** on the parent table of this FK, then throw an exception 
79990         ** immediately if the FK constraint is violated, even if this is a
79991         ** deferred trigger. That's what RESTRICT means. To defer checking
79992         ** the constraint, the FK should specify NO ACTION (represented
79993         ** using OE_None). NO ACTION is the default.  */
79994         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
79995       }
79996       pItem->zName = 0;
79997       sqlite3SrcListDelete(db, pSrc);
79998     }
79999     sqlite3DbFree(db, aiCol);
80000   }
80001 }
80002
80003 #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
80004
80005 /*
80006 ** This function is called before generating code to update or delete a 
80007 ** row contained in table pTab.
80008 */
80009 SQLITE_PRIVATE u32 sqlite3FkOldmask(
80010   Parse *pParse,                  /* Parse context */
80011   Table *pTab                     /* Table being modified */
80012 ){
80013   u32 mask = 0;
80014   if( pParse->db->flags&SQLITE_ForeignKeys ){
80015     FKey *p;
80016     int i;
80017     for(p=pTab->pFKey; p; p=p->pNextFrom){
80018       for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
80019     }
80020     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
80021       Index *pIdx = 0;
80022       locateFkeyIndex(pParse, pTab, p, &pIdx, 0);
80023       if( pIdx ){
80024         for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
80025       }
80026     }
80027   }
80028   return mask;
80029 }
80030
80031 /*
80032 ** This function is called before generating code to update or delete a 
80033 ** row contained in table pTab. If the operation is a DELETE, then
80034 ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
80035 ** to an array of size N, where N is the number of columns in table pTab.
80036 ** If the i'th column is not modified by the UPDATE, then the corresponding 
80037 ** entry in the aChange[] array is set to -1. If the column is modified,
80038 ** the value is 0 or greater. Parameter chngRowid is set to true if the
80039 ** UPDATE statement modifies the rowid fields of the table.
80040 **
80041 ** If any foreign key processing will be required, this function returns
80042 ** true. If there is no foreign key related processing, this function 
80043 ** returns false.
80044 */
80045 SQLITE_PRIVATE int sqlite3FkRequired(
80046   Parse *pParse,                  /* Parse context */
80047   Table *pTab,                    /* Table being modified */
80048   int *aChange,                   /* Non-NULL for UPDATE operations */
80049   int chngRowid                   /* True for UPDATE that affects rowid */
80050 ){
80051   if( pParse->db->flags&SQLITE_ForeignKeys ){
80052     if( !aChange ){
80053       /* A DELETE operation. Foreign key processing is required if the 
80054       ** table in question is either the child or parent table for any 
80055       ** foreign key constraint.  */
80056       return (sqlite3FkReferences(pTab) || pTab->pFKey);
80057     }else{
80058       /* This is an UPDATE. Foreign key processing is only required if the
80059       ** operation modifies one or more child or parent key columns. */
80060       int i;
80061       FKey *p;
80062
80063       /* Check if any child key columns are being modified. */
80064       for(p=pTab->pFKey; p; p=p->pNextFrom){
80065         for(i=0; i<p->nCol; i++){
80066           int iChildKey = p->aCol[i].iFrom;
80067           if( aChange[iChildKey]>=0 ) return 1;
80068           if( iChildKey==pTab->iPKey && chngRowid ) return 1;
80069         }
80070       }
80071
80072       /* Check if any parent key columns are being modified. */
80073       for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
80074         for(i=0; i<p->nCol; i++){
80075           char *zKey = p->aCol[i].zCol;
80076           int iKey;
80077           for(iKey=0; iKey<pTab->nCol; iKey++){
80078             Column *pCol = &pTab->aCol[iKey];
80079             if( (zKey ? !sqlite3StrICmp(pCol->zName, zKey) : pCol->isPrimKey) ){
80080               if( aChange[iKey]>=0 ) return 1;
80081               if( iKey==pTab->iPKey && chngRowid ) return 1;
80082             }
80083           }
80084         }
80085       }
80086     }
80087   }
80088   return 0;
80089 }
80090
80091 /*
80092 ** This function is called when an UPDATE or DELETE operation is being 
80093 ** compiled on table pTab, which is the parent table of foreign-key pFKey.
80094 ** If the current operation is an UPDATE, then the pChanges parameter is
80095 ** passed a pointer to the list of columns being modified. If it is a
80096 ** DELETE, pChanges is passed a NULL pointer.
80097 **
80098 ** It returns a pointer to a Trigger structure containing a trigger
80099 ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
80100 ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
80101 ** returned (these actions require no special handling by the triggers
80102 ** sub-system, code for them is created by fkScanChildren()).
80103 **
80104 ** For example, if pFKey is the foreign key and pTab is table "p" in 
80105 ** the following schema:
80106 **
80107 **   CREATE TABLE p(pk PRIMARY KEY);
80108 **   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
80109 **
80110 ** then the returned trigger structure is equivalent to:
80111 **
80112 **   CREATE TRIGGER ... DELETE ON p BEGIN
80113 **     DELETE FROM c WHERE ck = old.pk;
80114 **   END;
80115 **
80116 ** The returned pointer is cached as part of the foreign key object. It
80117 ** is eventually freed along with the rest of the foreign key object by 
80118 ** sqlite3FkDelete().
80119 */
80120 static Trigger *fkActionTrigger(
80121   Parse *pParse,                  /* Parse context */
80122   Table *pTab,                    /* Table being updated or deleted from */
80123   FKey *pFKey,                    /* Foreign key to get action for */
80124   ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
80125 ){
80126   sqlite3 *db = pParse->db;       /* Database handle */
80127   int action;                     /* One of OE_None, OE_Cascade etc. */
80128   Trigger *pTrigger;              /* Trigger definition to return */
80129   int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
80130
80131   action = pFKey->aAction[iAction];
80132   pTrigger = pFKey->apTrigger[iAction];
80133
80134   if( action!=OE_None && !pTrigger ){
80135     u8 enableLookaside;           /* Copy of db->lookaside.bEnabled */
80136     char const *zFrom;            /* Name of child table */
80137     int nFrom;                    /* Length in bytes of zFrom */
80138     Index *pIdx = 0;              /* Parent key index for this FK */
80139     int *aiCol = 0;               /* child table cols -> parent key cols */
80140     TriggerStep *pStep = 0;        /* First (only) step of trigger program */
80141     Expr *pWhere = 0;             /* WHERE clause of trigger step */
80142     ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
80143     Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
80144     int i;                        /* Iterator variable */
80145     Expr *pWhen = 0;              /* WHEN clause for the trigger */
80146
80147     if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
80148     assert( aiCol || pFKey->nCol==1 );
80149
80150     for(i=0; i<pFKey->nCol; i++){
80151       Token tOld = { "old", 3 };  /* Literal "old" token */
80152       Token tNew = { "new", 3 };  /* Literal "new" token */
80153       Token tFromCol;             /* Name of column in child table */
80154       Token tToCol;               /* Name of column in parent table */
80155       int iFromCol;               /* Idx of column in child table */
80156       Expr *pEq;                  /* tFromCol = OLD.tToCol */
80157
80158       iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
80159       assert( iFromCol>=0 );
80160       tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
80161       tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
80162
80163       tToCol.n = sqlite3Strlen30(tToCol.z);
80164       tFromCol.n = sqlite3Strlen30(tFromCol.z);
80165
80166       /* Create the expression "OLD.zToCol = zFromCol". It is important
80167       ** that the "OLD.zToCol" term is on the LHS of the = operator, so
80168       ** that the affinity and collation sequence associated with the
80169       ** parent table are used for the comparison. */
80170       pEq = sqlite3PExpr(pParse, TK_EQ,
80171           sqlite3PExpr(pParse, TK_DOT, 
80172             sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
80173             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
80174           , 0),
80175           sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
80176       , 0);
80177       pWhere = sqlite3ExprAnd(db, pWhere, pEq);
80178
80179       /* For ON UPDATE, construct the next term of the WHEN clause.
80180       ** The final WHEN clause will be like this:
80181       **
80182       **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
80183       */
80184       if( pChanges ){
80185         pEq = sqlite3PExpr(pParse, TK_IS,
80186             sqlite3PExpr(pParse, TK_DOT, 
80187               sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
80188               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
80189               0),
80190             sqlite3PExpr(pParse, TK_DOT, 
80191               sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
80192               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
80193               0),
80194             0);
80195         pWhen = sqlite3ExprAnd(db, pWhen, pEq);
80196       }
80197   
80198       if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
80199         Expr *pNew;
80200         if( action==OE_Cascade ){
80201           pNew = sqlite3PExpr(pParse, TK_DOT, 
80202             sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
80203             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
80204           , 0);
80205         }else if( action==OE_SetDflt ){
80206           Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
80207           if( pDflt ){
80208             pNew = sqlite3ExprDup(db, pDflt, 0);
80209           }else{
80210             pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
80211           }
80212         }else{
80213           pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
80214         }
80215         pList = sqlite3ExprListAppend(pParse, pList, pNew);
80216         sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
80217       }
80218     }
80219     sqlite3DbFree(db, aiCol);
80220
80221     zFrom = pFKey->pFrom->zName;
80222     nFrom = sqlite3Strlen30(zFrom);
80223
80224     if( action==OE_Restrict ){
80225       Token tFrom;
80226       Expr *pRaise; 
80227
80228       tFrom.z = zFrom;
80229       tFrom.n = nFrom;
80230       pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed");
80231       if( pRaise ){
80232         pRaise->affinity = OE_Abort;
80233       }
80234       pSelect = sqlite3SelectNew(pParse, 
80235           sqlite3ExprListAppend(pParse, 0, pRaise),
80236           sqlite3SrcListAppend(db, 0, &tFrom, 0),
80237           pWhere,
80238           0, 0, 0, 0, 0, 0
80239       );
80240       pWhere = 0;
80241     }
80242
80243     /* In the current implementation, pTab->dbMem==0 for all tables except
80244     ** for temporary tables used to describe subqueries.  And temporary
80245     ** tables do not have foreign key constraints.  Hence, pTab->dbMem
80246     ** should always be 0 there.
80247     */
80248     enableLookaside = db->lookaside.bEnabled;
80249     db->lookaside.bEnabled = 0;
80250
80251     pTrigger = (Trigger *)sqlite3DbMallocZero(db, 
80252         sizeof(Trigger) +         /* struct Trigger */
80253         sizeof(TriggerStep) +     /* Single step in trigger program */
80254         nFrom + 1                 /* Space for pStep->target.z */
80255     );
80256     if( pTrigger ){
80257       pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
80258       pStep->target.z = (char *)&pStep[1];
80259       pStep->target.n = nFrom;
80260       memcpy((char *)pStep->target.z, zFrom, nFrom);
80261   
80262       pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
80263       pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
80264       pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
80265       if( pWhen ){
80266         pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
80267         pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
80268       }
80269     }
80270
80271     /* Re-enable the lookaside buffer, if it was disabled earlier. */
80272     db->lookaside.bEnabled = enableLookaside;
80273
80274     sqlite3ExprDelete(db, pWhere);
80275     sqlite3ExprDelete(db, pWhen);
80276     sqlite3ExprListDelete(db, pList);
80277     sqlite3SelectDelete(db, pSelect);
80278     if( db->mallocFailed==1 ){
80279       fkTriggerDelete(db, pTrigger);
80280       return 0;
80281     }
80282
80283     switch( action ){
80284       case OE_Restrict:
80285         pStep->op = TK_SELECT; 
80286         break;
80287       case OE_Cascade: 
80288         if( !pChanges ){ 
80289           pStep->op = TK_DELETE; 
80290           break; 
80291         }
80292       default:
80293         pStep->op = TK_UPDATE;
80294     }
80295     pStep->pTrig = pTrigger;
80296     pTrigger->pSchema = pTab->pSchema;
80297     pTrigger->pTabSchema = pTab->pSchema;
80298     pFKey->apTrigger[iAction] = pTrigger;
80299     pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
80300   }
80301
80302   return pTrigger;
80303 }
80304
80305 /*
80306 ** This function is called when deleting or updating a row to implement
80307 ** any required CASCADE, SET NULL or SET DEFAULT actions.
80308 */
80309 SQLITE_PRIVATE void sqlite3FkActions(
80310   Parse *pParse,                  /* Parse context */
80311   Table *pTab,                    /* Table being updated or deleted from */
80312   ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
80313   int regOld                      /* Address of array containing old row */
80314 ){
80315   /* If foreign-key support is enabled, iterate through all FKs that 
80316   ** refer to table pTab. If there is an action associated with the FK 
80317   ** for this operation (either update or delete), invoke the associated 
80318   ** trigger sub-program.  */
80319   if( pParse->db->flags&SQLITE_ForeignKeys ){
80320     FKey *pFKey;                  /* Iterator variable */
80321     for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
80322       Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);
80323       if( pAction ){
80324         sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);
80325       }
80326     }
80327   }
80328 }
80329
80330 #endif /* ifndef SQLITE_OMIT_TRIGGER */
80331
80332 /*
80333 ** Free all memory associated with foreign key definitions attached to
80334 ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
80335 ** hash table.
80336 */
80337 SQLITE_PRIVATE void sqlite3FkDelete(Table *pTab){
80338   FKey *pFKey;                    /* Iterator variable */
80339   FKey *pNext;                    /* Copy of pFKey->pNextFrom */
80340
80341   for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
80342
80343     /* Remove the FK from the fkeyHash hash table. */
80344     if( pFKey->pPrevTo ){
80345       pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
80346     }else{
80347       void *data = (void *)pFKey->pNextTo;
80348       const char *z = (data ? pFKey->pNextTo->zTo : pFKey->zTo);
80349       sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), data);
80350     }
80351     if( pFKey->pNextTo ){
80352       pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
80353     }
80354
80355     /* Delete any triggers created to implement actions for this FK. */
80356 #ifndef SQLITE_OMIT_TRIGGER
80357     fkTriggerDelete(pTab->dbMem, pFKey->apTrigger[0]);
80358     fkTriggerDelete(pTab->dbMem, pFKey->apTrigger[1]);
80359 #endif
80360
80361     /* EV: R-30323-21917 Each foreign key constraint in SQLite is
80362     ** classified as either immediate or deferred.
80363     */
80364     assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
80365
80366     pNext = pFKey->pNextFrom;
80367     sqlite3DbFree(pTab->dbMem, pFKey);
80368   }
80369 }
80370 #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
80371
80372 /************** End of fkey.c ************************************************/
80373 /************** Begin file insert.c ******************************************/
80374 /*
80375 ** 2001 September 15
80376 **
80377 ** The author disclaims copyright to this source code.  In place of
80378 ** a legal notice, here is a blessing:
80379 **
80380 **    May you do good and not evil.
80381 **    May you find forgiveness for yourself and forgive others.
80382 **    May you share freely, never taking more than you give.
80383 **
80384 *************************************************************************
80385 ** This file contains C code routines that are called by the parser
80386 ** to handle INSERT statements in SQLite.
80387 */
80388
80389 /*
80390 ** Generate code that will open a table for reading.
80391 */
80392 SQLITE_PRIVATE void sqlite3OpenTable(
80393   Parse *p,       /* Generate code into this VDBE */
80394   int iCur,       /* The cursor number of the table */
80395   int iDb,        /* The database index in sqlite3.aDb[] */
80396   Table *pTab,    /* The table to be opened */
80397   int opcode      /* OP_OpenRead or OP_OpenWrite */
80398 ){
80399   Vdbe *v;
80400   if( IsVirtual(pTab) ) return;
80401   v = sqlite3GetVdbe(p);
80402   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
80403   sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
80404   sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
80405   sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
80406   VdbeComment((v, "%s", pTab->zName));
80407 }
80408
80409 /*
80410 ** Return a pointer to the column affinity string associated with index
80411 ** pIdx. A column affinity string has one character for each column in 
80412 ** the table, according to the affinity of the column:
80413 **
80414 **  Character      Column affinity
80415 **  ------------------------------
80416 **  'a'            TEXT
80417 **  'b'            NONE
80418 **  'c'            NUMERIC
80419 **  'd'            INTEGER
80420 **  'e'            REAL
80421 **
80422 ** An extra 'b' is appended to the end of the string to cover the
80423 ** rowid that appears as the last column in every index.
80424 **
80425 ** Memory for the buffer containing the column index affinity string
80426 ** is managed along with the rest of the Index structure. It will be
80427 ** released when sqlite3DeleteIndex() is called.
80428 */
80429 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
80430   if( !pIdx->zColAff ){
80431     /* The first time a column affinity string for a particular index is
80432     ** required, it is allocated and populated here. It is then stored as
80433     ** a member of the Index structure for subsequent use.
80434     **
80435     ** The column affinity string will eventually be deleted by
80436     ** sqliteDeleteIndex() when the Index structure itself is cleaned
80437     ** up.
80438     */
80439     int n;
80440     Table *pTab = pIdx->pTable;
80441     sqlite3 *db = sqlite3VdbeDb(v);
80442     pIdx->zColAff = (char *)sqlite3Malloc(pIdx->nColumn+2);
80443     if( !pIdx->zColAff ){
80444       db->mallocFailed = 1;
80445       return 0;
80446     }
80447     for(n=0; n<pIdx->nColumn; n++){
80448       pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
80449     }
80450     pIdx->zColAff[n++] = SQLITE_AFF_NONE;
80451     pIdx->zColAff[n] = 0;
80452   }
80453  
80454   return pIdx->zColAff;
80455 }
80456
80457 /*
80458 ** Set P4 of the most recently inserted opcode to a column affinity
80459 ** string for table pTab. A column affinity string has one character
80460 ** for each column indexed by the index, according to the affinity of the
80461 ** column:
80462 **
80463 **  Character      Column affinity
80464 **  ------------------------------
80465 **  'a'            TEXT
80466 **  'b'            NONE
80467 **  'c'            NUMERIC
80468 **  'd'            INTEGER
80469 **  'e'            REAL
80470 */
80471 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
80472   /* The first time a column affinity string for a particular table
80473   ** is required, it is allocated and populated here. It is then 
80474   ** stored as a member of the Table structure for subsequent use.
80475   **
80476   ** The column affinity string will eventually be deleted by
80477   ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
80478   */
80479   if( !pTab->zColAff ){
80480     char *zColAff;
80481     int i;
80482     sqlite3 *db = sqlite3VdbeDb(v);
80483
80484     zColAff = (char *)sqlite3Malloc(pTab->nCol+1);
80485     if( !zColAff ){
80486       db->mallocFailed = 1;
80487       return;
80488     }
80489
80490     for(i=0; i<pTab->nCol; i++){
80491       zColAff[i] = pTab->aCol[i].affinity;
80492     }
80493     zColAff[pTab->nCol] = '\0';
80494
80495     pTab->zColAff = zColAff;
80496   }
80497
80498   sqlite3VdbeChangeP4(v, -1, pTab->zColAff, 0);
80499 }
80500
80501 /*
80502 ** Return non-zero if the table pTab in database iDb or any of its indices
80503 ** have been opened at any point in the VDBE program beginning at location
80504 ** iStartAddr throught the end of the program.  This is used to see if 
80505 ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can 
80506 ** run without using temporary table for the results of the SELECT. 
80507 */
80508 static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
80509   Vdbe *v = sqlite3GetVdbe(p);
80510   int i;
80511   int iEnd = sqlite3VdbeCurrentAddr(v);
80512 #ifndef SQLITE_OMIT_VIRTUALTABLE
80513   VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
80514 #endif
80515
80516   for(i=iStartAddr; i<iEnd; i++){
80517     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
80518     assert( pOp!=0 );
80519     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
80520       Index *pIndex;
80521       int tnum = pOp->p2;
80522       if( tnum==pTab->tnum ){
80523         return 1;
80524       }
80525       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
80526         if( tnum==pIndex->tnum ){
80527           return 1;
80528         }
80529       }
80530     }
80531 #ifndef SQLITE_OMIT_VIRTUALTABLE
80532     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
80533       assert( pOp->p4.pVtab!=0 );
80534       assert( pOp->p4type==P4_VTAB );
80535       return 1;
80536     }
80537 #endif
80538   }
80539   return 0;
80540 }
80541
80542 #ifndef SQLITE_OMIT_AUTOINCREMENT
80543 /*
80544 ** Locate or create an AutoincInfo structure associated with table pTab
80545 ** which is in database iDb.  Return the register number for the register
80546 ** that holds the maximum rowid.
80547 **
80548 ** There is at most one AutoincInfo structure per table even if the
80549 ** same table is autoincremented multiple times due to inserts within
80550 ** triggers.  A new AutoincInfo structure is created if this is the
80551 ** first use of table pTab.  On 2nd and subsequent uses, the original
80552 ** AutoincInfo structure is used.
80553 **
80554 ** Three memory locations are allocated:
80555 **
80556 **   (1)  Register to hold the name of the pTab table.
80557 **   (2)  Register to hold the maximum ROWID of pTab.
80558 **   (3)  Register to hold the rowid in sqlite_sequence of pTab
80559 **
80560 ** The 2nd register is the one that is returned.  That is all the
80561 ** insert routine needs to know about.
80562 */
80563 static int autoIncBegin(
80564   Parse *pParse,      /* Parsing context */
80565   int iDb,            /* Index of the database holding pTab */
80566   Table *pTab         /* The table we are writing to */
80567 ){
80568   int memId = 0;      /* Register holding maximum rowid */
80569   if( pTab->tabFlags & TF_Autoincrement ){
80570     Parse *pToplevel = sqlite3ParseToplevel(pParse);
80571     AutoincInfo *pInfo;
80572
80573     pInfo = pToplevel->pAinc;
80574     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
80575     if( pInfo==0 ){
80576       pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
80577       if( pInfo==0 ) return 0;
80578       pInfo->pNext = pToplevel->pAinc;
80579       pToplevel->pAinc = pInfo;
80580       pInfo->pTab = pTab;
80581       pInfo->iDb = iDb;
80582       pToplevel->nMem++;                  /* Register to hold name of table */
80583       pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
80584       pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
80585     }
80586     memId = pInfo->regCtr;
80587   }
80588   return memId;
80589 }
80590
80591 /*
80592 ** This routine generates code that will initialize all of the
80593 ** register used by the autoincrement tracker.  
80594 */
80595 SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
80596   AutoincInfo *p;            /* Information about an AUTOINCREMENT */
80597   sqlite3 *db = pParse->db;  /* The database connection */
80598   Db *pDb;                   /* Database only autoinc table */
80599   int memId;                 /* Register holding max rowid */
80600   int addr;                  /* A VDBE address */
80601   Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
80602
80603   /* This routine is never called during trigger-generation.  It is
80604   ** only called from the top-level */
80605   assert( pParse->pTriggerTab==0 );
80606   assert( pParse==sqlite3ParseToplevel(pParse) );
80607
80608   assert( v );   /* We failed long ago if this is not so */
80609   for(p = pParse->pAinc; p; p = p->pNext){
80610     pDb = &db->aDb[p->iDb];
80611     memId = p->regCtr;
80612     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
80613     addr = sqlite3VdbeCurrentAddr(v);
80614     sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
80615     sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
80616     sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
80617     sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
80618     sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
80619     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
80620     sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
80621     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
80622     sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
80623     sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
80624     sqlite3VdbeAddOp0(v, OP_Close);
80625   }
80626 }
80627
80628 /*
80629 ** Update the maximum rowid for an autoincrement calculation.
80630 **
80631 ** This routine should be called when the top of the stack holds a
80632 ** new rowid that is about to be inserted.  If that new rowid is
80633 ** larger than the maximum rowid in the memId memory cell, then the
80634 ** memory cell is updated.  The stack is unchanged.
80635 */
80636 static void autoIncStep(Parse *pParse, int memId, int regRowid){
80637   if( memId>0 ){
80638     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
80639   }
80640 }
80641
80642 /*
80643 ** This routine generates the code needed to write autoincrement
80644 ** maximum rowid values back into the sqlite_sequence register.
80645 ** Every statement that might do an INSERT into an autoincrement
80646 ** table (either directly or through triggers) needs to call this
80647 ** routine just before the "exit" code.
80648 */
80649 SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
80650   AutoincInfo *p;
80651   Vdbe *v = pParse->pVdbe;
80652   sqlite3 *db = pParse->db;
80653
80654   assert( v );
80655   for(p = pParse->pAinc; p; p = p->pNext){
80656     Db *pDb = &db->aDb[p->iDb];
80657     int j1, j2, j3, j4, j5;
80658     int iRec;
80659     int memId = p->regCtr;
80660
80661     iRec = sqlite3GetTempReg(pParse);
80662     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
80663     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
80664     j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
80665     j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
80666     j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
80667     sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
80668     sqlite3VdbeJumpHere(v, j2);
80669     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
80670     j5 = sqlite3VdbeAddOp0(v, OP_Goto);
80671     sqlite3VdbeJumpHere(v, j4);
80672     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
80673     sqlite3VdbeJumpHere(v, j1);
80674     sqlite3VdbeJumpHere(v, j5);
80675     sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
80676     sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
80677     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
80678     sqlite3VdbeAddOp0(v, OP_Close);
80679     sqlite3ReleaseTempReg(pParse, iRec);
80680   }
80681 }
80682 #else
80683 /*
80684 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
80685 ** above are all no-ops
80686 */
80687 # define autoIncBegin(A,B,C) (0)
80688 # define autoIncStep(A,B,C)
80689 #endif /* SQLITE_OMIT_AUTOINCREMENT */
80690
80691
80692 /* Forward declaration */
80693 static int xferOptimization(
80694   Parse *pParse,        /* Parser context */
80695   Table *pDest,         /* The table we are inserting into */
80696   Select *pSelect,      /* A SELECT statement to use as the data source */
80697   int onError,          /* How to handle constraint errors */
80698   int iDbDest           /* The database of pDest */
80699 );
80700
80701 /*
80702 ** This routine is call to handle SQL of the following forms:
80703 **
80704 **    insert into TABLE (IDLIST) values(EXPRLIST)
80705 **    insert into TABLE (IDLIST) select
80706 **
80707 ** The IDLIST following the table name is always optional.  If omitted,
80708 ** then a list of all columns for the table is substituted.  The IDLIST
80709 ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
80710 **
80711 ** The pList parameter holds EXPRLIST in the first form of the INSERT
80712 ** statement above, and pSelect is NULL.  For the second form, pList is
80713 ** NULL and pSelect is a pointer to the select statement used to generate
80714 ** data for the insert.
80715 **
80716 ** The code generated follows one of four templates.  For a simple
80717 ** select with data coming from a VALUES clause, the code executes
80718 ** once straight down through.  Pseudo-code follows (we call this
80719 ** the "1st template"):
80720 **
80721 **         open write cursor to <table> and its indices
80722 **         puts VALUES clause expressions onto the stack
80723 **         write the resulting record into <table>
80724 **         cleanup
80725 **
80726 ** The three remaining templates assume the statement is of the form
80727 **
80728 **   INSERT INTO <table> SELECT ...
80729 **
80730 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
80731 ** in other words if the SELECT pulls all columns from a single table
80732 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
80733 ** if <table2> and <table1> are distinct tables but have identical
80734 ** schemas, including all the same indices, then a special optimization
80735 ** is invoked that copies raw records from <table2> over to <table1>.
80736 ** See the xferOptimization() function for the implementation of this
80737 ** template.  This is the 2nd template.
80738 **
80739 **         open a write cursor to <table>
80740 **         open read cursor on <table2>
80741 **         transfer all records in <table2> over to <table>
80742 **         close cursors
80743 **         foreach index on <table>
80744 **           open a write cursor on the <table> index
80745 **           open a read cursor on the corresponding <table2> index
80746 **           transfer all records from the read to the write cursors
80747 **           close cursors
80748 **         end foreach
80749 **
80750 ** The 3rd template is for when the second template does not apply
80751 ** and the SELECT clause does not read from <table> at any time.
80752 ** The generated code follows this template:
80753 **
80754 **         EOF <- 0
80755 **         X <- A
80756 **         goto B
80757 **      A: setup for the SELECT
80758 **         loop over the rows in the SELECT
80759 **           load values into registers R..R+n
80760 **           yield X
80761 **         end loop
80762 **         cleanup after the SELECT
80763 **         EOF <- 1
80764 **         yield X
80765 **         goto A
80766 **      B: open write cursor to <table> and its indices
80767 **      C: yield X
80768 **         if EOF goto D
80769 **         insert the select result into <table> from R..R+n
80770 **         goto C
80771 **      D: cleanup
80772 **
80773 ** The 4th template is used if the insert statement takes its
80774 ** values from a SELECT but the data is being inserted into a table
80775 ** that is also read as part of the SELECT.  In the third form,
80776 ** we have to use a intermediate table to store the results of
80777 ** the select.  The template is like this:
80778 **
80779 **         EOF <- 0
80780 **         X <- A
80781 **         goto B
80782 **      A: setup for the SELECT
80783 **         loop over the tables in the SELECT
80784 **           load value into register R..R+n
80785 **           yield X
80786 **         end loop
80787 **         cleanup after the SELECT
80788 **         EOF <- 1
80789 **         yield X
80790 **         halt-error
80791 **      B: open temp table
80792 **      L: yield X
80793 **         if EOF goto M
80794 **         insert row from R..R+n into temp table
80795 **         goto L
80796 **      M: open write cursor to <table> and its indices
80797 **         rewind temp table
80798 **      C: loop over rows of intermediate table
80799 **           transfer values form intermediate table into <table>
80800 **         end loop
80801 **      D: cleanup
80802 */
80803 SQLITE_PRIVATE void sqlite3Insert(
80804   Parse *pParse,        /* Parser context */
80805   SrcList *pTabList,    /* Name of table into which we are inserting */
80806   ExprList *pList,      /* List of values to be inserted */
80807   Select *pSelect,      /* A SELECT statement to use as the data source */
80808   IdList *pColumn,      /* Column names corresponding to IDLIST. */
80809   int onError           /* How to handle constraint errors */
80810 ){
80811   sqlite3 *db;          /* The main database structure */
80812   Table *pTab;          /* The table to insert into.  aka TABLE */
80813   char *zTab;           /* Name of the table into which we are inserting */
80814   const char *zDb;      /* Name of the database holding this table */
80815   int i, j, idx;        /* Loop counters */
80816   Vdbe *v;              /* Generate code into this virtual machine */
80817   Index *pIdx;          /* For looping over indices of the table */
80818   int nColumn;          /* Number of columns in the data */
80819   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
80820   int baseCur = 0;      /* VDBE Cursor number for pTab */
80821   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
80822   int endOfLoop;        /* Label for the end of the insertion loop */
80823   int useTempTable = 0; /* Store SELECT results in intermediate table */
80824   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
80825   int addrInsTop = 0;   /* Jump to label "D" */
80826   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
80827   int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
80828   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
80829   int iDb;              /* Index of database holding TABLE */
80830   Db *pDb;              /* The database containing table being inserted into */
80831   int appendFlag = 0;   /* True if the insert is likely to be an append */
80832
80833   /* Register allocations */
80834   int regFromSelect = 0;/* Base register for data coming from SELECT */
80835   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
80836   int regRowCount = 0;  /* Memory cell used for the row counter */
80837   int regIns;           /* Block of regs holding rowid+data being inserted */
80838   int regRowid;         /* registers holding insert rowid */
80839   int regData;          /* register holding first column to insert */
80840   int regRecord;        /* Holds the assemblied row record */
80841   int regEof = 0;       /* Register recording end of SELECT data */
80842   int *aRegIdx = 0;     /* One register allocated to each index */
80843
80844 #ifndef SQLITE_OMIT_TRIGGER
80845   int isView;                 /* True if attempting to insert into a view */
80846   Trigger *pTrigger;          /* List of triggers on pTab, if required */
80847   int tmask;                  /* Mask of trigger times */
80848 #endif
80849
80850   db = pParse->db;
80851   memset(&dest, 0, sizeof(dest));
80852   if( pParse->nErr || db->mallocFailed ){
80853     goto insert_cleanup;
80854   }
80855
80856   /* Locate the table into which we will be inserting new information.
80857   */
80858   assert( pTabList->nSrc==1 );
80859   zTab = pTabList->a[0].zName;
80860   if( NEVER(zTab==0) ) goto insert_cleanup;
80861   pTab = sqlite3SrcListLookup(pParse, pTabList);
80862   if( pTab==0 ){
80863     goto insert_cleanup;
80864   }
80865   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
80866   assert( iDb<db->nDb );
80867   pDb = &db->aDb[iDb];
80868   zDb = pDb->zName;
80869   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
80870     goto insert_cleanup;
80871   }
80872
80873   /* Figure out if we have any triggers and if the table being
80874   ** inserted into is a view
80875   */
80876 #ifndef SQLITE_OMIT_TRIGGER
80877   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
80878   isView = pTab->pSelect!=0;
80879 #else
80880 # define pTrigger 0
80881 # define tmask 0
80882 # define isView 0
80883 #endif
80884 #ifdef SQLITE_OMIT_VIEW
80885 # undef isView
80886 # define isView 0
80887 #endif
80888   assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
80889
80890   /* If pTab is really a view, make sure it has been initialized.
80891   ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual 
80892   ** module table).
80893   */
80894   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
80895     goto insert_cleanup;
80896   }
80897
80898   /* Ensure that:
80899   *  (a) the table is not read-only, 
80900   *  (b) that if it is a view then ON INSERT triggers exist
80901   */
80902   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
80903     goto insert_cleanup;
80904   }
80905
80906   /* Allocate a VDBE
80907   */
80908   v = sqlite3GetVdbe(pParse);
80909   if( v==0 ) goto insert_cleanup;
80910   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
80911   sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
80912
80913 #ifndef SQLITE_OMIT_XFER_OPT
80914   /* If the statement is of the form
80915   **
80916   **       INSERT INTO <table1> SELECT * FROM <table2>;
80917   **
80918   ** Then special optimizations can be applied that make the transfer
80919   ** very fast and which reduce fragmentation of indices.
80920   **
80921   ** This is the 2nd template.
80922   */
80923   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
80924     assert( !pTrigger );
80925     assert( pList==0 );
80926     goto insert_end;
80927   }
80928 #endif /* SQLITE_OMIT_XFER_OPT */
80929
80930   /* If this is an AUTOINCREMENT table, look up the sequence number in the
80931   ** sqlite_sequence table and store it in memory cell regAutoinc.
80932   */
80933   regAutoinc = autoIncBegin(pParse, iDb, pTab);
80934
80935   /* Figure out how many columns of data are supplied.  If the data
80936   ** is coming from a SELECT statement, then generate a co-routine that
80937   ** produces a single row of the SELECT on each invocation.  The
80938   ** co-routine is the common header to the 3rd and 4th templates.
80939   */
80940   if( pSelect ){
80941     /* Data is coming from a SELECT.  Generate code to implement that SELECT
80942     ** as a co-routine.  The code is common to both the 3rd and 4th
80943     ** templates:
80944     **
80945     **         EOF <- 0
80946     **         X <- A
80947     **         goto B
80948     **      A: setup for the SELECT
80949     **         loop over the tables in the SELECT
80950     **           load value into register R..R+n
80951     **           yield X
80952     **         end loop
80953     **         cleanup after the SELECT
80954     **         EOF <- 1
80955     **         yield X
80956     **         halt-error
80957     **
80958     ** On each invocation of the co-routine, it puts a single row of the
80959     ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
80960     ** (These output registers are allocated by sqlite3Select().)  When
80961     ** the SELECT completes, it sets the EOF flag stored in regEof.
80962     */
80963     int rc, j1;
80964
80965     regEof = ++pParse->nMem;
80966     sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);      /* EOF <- 0 */
80967     VdbeComment((v, "SELECT eof flag"));
80968     sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
80969     addrSelect = sqlite3VdbeCurrentAddr(v)+2;
80970     sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm);
80971     j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
80972     VdbeComment((v, "Jump over SELECT coroutine"));
80973
80974     /* Resolve the expressions in the SELECT statement and execute it. */
80975     rc = sqlite3Select(pParse, pSelect, &dest);
80976     assert( pParse->nErr==0 || rc );
80977     if( rc || NEVER(pParse->nErr) || db->mallocFailed ){
80978       goto insert_cleanup;
80979     }
80980     sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);         /* EOF <- 1 */
80981     sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);   /* yield X */
80982     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
80983     VdbeComment((v, "End of SELECT coroutine"));
80984     sqlite3VdbeJumpHere(v, j1);                          /* label B: */
80985
80986     regFromSelect = dest.iMem;
80987     assert( pSelect->pEList );
80988     nColumn = pSelect->pEList->nExpr;
80989     assert( dest.nMem==nColumn );
80990
80991     /* Set useTempTable to TRUE if the result of the SELECT statement
80992     ** should be written into a temporary table (template 4).  Set to
80993     ** FALSE if each* row of the SELECT can be written directly into
80994     ** the destination table (template 3).
80995     **
80996     ** A temp table must be used if the table being updated is also one
80997     ** of the tables being read by the SELECT statement.  Also use a 
80998     ** temp table in the case of row triggers.
80999     */
81000     if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
81001       useTempTable = 1;
81002     }
81003
81004     if( useTempTable ){
81005       /* Invoke the coroutine to extract information from the SELECT
81006       ** and add it to a transient table srcTab.  The code generated
81007       ** here is from the 4th template:
81008       **
81009       **      B: open temp table
81010       **      L: yield X
81011       **         if EOF goto M
81012       **         insert row from R..R+n into temp table
81013       **         goto L
81014       **      M: ...
81015       */
81016       int regRec;          /* Register to hold packed record */
81017       int regTempRowid;    /* Register to hold temp table ROWID */
81018       int addrTop;         /* Label "L" */
81019       int addrIf;          /* Address of jump to M */
81020
81021       srcTab = pParse->nTab++;
81022       regRec = sqlite3GetTempReg(pParse);
81023       regTempRowid = sqlite3GetTempReg(pParse);
81024       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
81025       addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
81026       addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
81027       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
81028       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
81029       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
81030       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
81031       sqlite3VdbeJumpHere(v, addrIf);
81032       sqlite3ReleaseTempReg(pParse, regRec);
81033       sqlite3ReleaseTempReg(pParse, regTempRowid);
81034     }
81035   }else{
81036     /* This is the case if the data for the INSERT is coming from a VALUES
81037     ** clause
81038     */
81039     NameContext sNC;
81040     memset(&sNC, 0, sizeof(sNC));
81041     sNC.pParse = pParse;
81042     srcTab = -1;
81043     assert( useTempTable==0 );
81044     nColumn = pList ? pList->nExpr : 0;
81045     for(i=0; i<nColumn; i++){
81046       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
81047         goto insert_cleanup;
81048       }
81049     }
81050   }
81051
81052   /* Make sure the number of columns in the source data matches the number
81053   ** of columns to be inserted into the table.
81054   */
81055   if( IsVirtual(pTab) ){
81056     for(i=0; i<pTab->nCol; i++){
81057       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
81058     }
81059   }
81060   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
81061     sqlite3ErrorMsg(pParse, 
81062        "table %S has %d columns but %d values were supplied",
81063        pTabList, 0, pTab->nCol-nHidden, nColumn);
81064     goto insert_cleanup;
81065   }
81066   if( pColumn!=0 && nColumn!=pColumn->nId ){
81067     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
81068     goto insert_cleanup;
81069   }
81070
81071   /* If the INSERT statement included an IDLIST term, then make sure
81072   ** all elements of the IDLIST really are columns of the table and 
81073   ** remember the column indices.
81074   **
81075   ** If the table has an INTEGER PRIMARY KEY column and that column
81076   ** is named in the IDLIST, then record in the keyColumn variable
81077   ** the index into IDLIST of the primary key column.  keyColumn is
81078   ** the index of the primary key as it appears in IDLIST, not as
81079   ** is appears in the original table.  (The index of the primary
81080   ** key in the original table is pTab->iPKey.)
81081   */
81082   if( pColumn ){
81083     for(i=0; i<pColumn->nId; i++){
81084       pColumn->a[i].idx = -1;
81085     }
81086     for(i=0; i<pColumn->nId; i++){
81087       for(j=0; j<pTab->nCol; j++){
81088         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
81089           pColumn->a[i].idx = j;
81090           if( j==pTab->iPKey ){
81091             keyColumn = i;
81092           }
81093           break;
81094         }
81095       }
81096       if( j>=pTab->nCol ){
81097         if( sqlite3IsRowid(pColumn->a[i].zName) ){
81098           keyColumn = i;
81099         }else{
81100           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
81101               pTabList, 0, pColumn->a[i].zName);
81102           pParse->checkSchema = 1;
81103           goto insert_cleanup;
81104         }
81105       }
81106     }
81107   }
81108
81109   /* If there is no IDLIST term but the table has an integer primary
81110   ** key, the set the keyColumn variable to the primary key column index
81111   ** in the original table definition.
81112   */
81113   if( pColumn==0 && nColumn>0 ){
81114     keyColumn = pTab->iPKey;
81115   }
81116     
81117   /* Initialize the count of rows to be inserted
81118   */
81119   if( db->flags & SQLITE_CountRows ){
81120     regRowCount = ++pParse->nMem;
81121     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
81122   }
81123
81124   /* If this is not a view, open the table and and all indices */
81125   if( !isView ){
81126     int nIdx;
81127
81128     baseCur = pParse->nTab;
81129     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
81130     aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
81131     if( aRegIdx==0 ){
81132       goto insert_cleanup;
81133     }
81134     for(i=0; i<nIdx; i++){
81135       aRegIdx[i] = ++pParse->nMem;
81136     }
81137   }
81138
81139   /* This is the top of the main insertion loop */
81140   if( useTempTable ){
81141     /* This block codes the top of loop only.  The complete loop is the
81142     ** following pseudocode (template 4):
81143     **
81144     **         rewind temp table
81145     **      C: loop over rows of intermediate table
81146     **           transfer values form intermediate table into <table>
81147     **         end loop
81148     **      D: ...
81149     */
81150     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
81151     addrCont = sqlite3VdbeCurrentAddr(v);
81152   }else if( pSelect ){
81153     /* This block codes the top of loop only.  The complete loop is the
81154     ** following pseudocode (template 3):
81155     **
81156     **      C: yield X
81157     **         if EOF goto D
81158     **         insert the select result into <table> from R..R+n
81159     **         goto C
81160     **      D: ...
81161     */
81162     addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
81163     addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
81164   }
81165
81166   /* Allocate registers for holding the rowid of the new row,
81167   ** the content of the new row, and the assemblied row record.
81168   */
81169   regRecord = ++pParse->nMem;
81170   regRowid = regIns = pParse->nMem+1;
81171   pParse->nMem += pTab->nCol + 1;
81172   if( IsVirtual(pTab) ){
81173     regRowid++;
81174     pParse->nMem++;
81175   }
81176   regData = regRowid+1;
81177
81178   /* Run the BEFORE and INSTEAD OF triggers, if there are any
81179   */
81180   endOfLoop = sqlite3VdbeMakeLabel(v);
81181   if( tmask & TRIGGER_BEFORE ){
81182     int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
81183
81184     /* build the NEW.* reference row.  Note that if there is an INTEGER
81185     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
81186     ** translated into a unique ID for the row.  But on a BEFORE trigger,
81187     ** we do not know what the unique ID will be (because the insert has
81188     ** not happened yet) so we substitute a rowid of -1
81189     */
81190     if( keyColumn<0 ){
81191       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
81192     }else{
81193       int j1;
81194       if( useTempTable ){
81195         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
81196       }else{
81197         assert( pSelect==0 );  /* Otherwise useTempTable is true */
81198         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
81199       }
81200       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
81201       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
81202       sqlite3VdbeJumpHere(v, j1);
81203       sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
81204     }
81205
81206     /* Cannot have triggers on a virtual table. If it were possible,
81207     ** this block would have to account for hidden column.
81208     */
81209     assert( !IsVirtual(pTab) );
81210
81211     /* Create the new column data
81212     */
81213     for(i=0; i<pTab->nCol; i++){
81214       if( pColumn==0 ){
81215         j = i;
81216       }else{
81217         for(j=0; j<pColumn->nId; j++){
81218           if( pColumn->a[j].idx==i ) break;
81219         }
81220       }
81221       if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
81222         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
81223       }else if( useTempTable ){
81224         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1); 
81225       }else{
81226         assert( pSelect==0 ); /* Otherwise useTempTable is true */
81227         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
81228       }
81229     }
81230
81231     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
81232     ** do not attempt any conversions before assembling the record.
81233     ** If this is a real table, attempt conversions as required by the
81234     ** table column affinities.
81235     */
81236     if( !isView ){
81237       sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
81238       sqlite3TableAffinityStr(v, pTab);
81239     }
81240
81241     /* Fire BEFORE or INSTEAD OF triggers */
81242     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE, 
81243         pTab, regCols-pTab->nCol-1, onError, endOfLoop);
81244
81245     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
81246   }
81247
81248   /* Push the record number for the new entry onto the stack.  The
81249   ** record number is a randomly generate integer created by NewRowid
81250   ** except when the table has an INTEGER PRIMARY KEY column, in which
81251   ** case the record number is the same as that column. 
81252   */
81253   if( !isView ){
81254     if( IsVirtual(pTab) ){
81255       /* The row that the VUpdate opcode will delete: none */
81256       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
81257     }
81258     if( keyColumn>=0 ){
81259       if( useTempTable ){
81260         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
81261       }else if( pSelect ){
81262         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
81263       }else{
81264         VdbeOp *pOp;
81265         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
81266         pOp = sqlite3VdbeGetOp(v, -1);
81267         if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
81268           appendFlag = 1;
81269           pOp->opcode = OP_NewRowid;
81270           pOp->p1 = baseCur;
81271           pOp->p2 = regRowid;
81272           pOp->p3 = regAutoinc;
81273         }
81274       }
81275       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
81276       ** to generate a unique primary key value.
81277       */
81278       if( !appendFlag ){
81279         int j1;
81280         if( !IsVirtual(pTab) ){
81281           j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
81282           sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
81283           sqlite3VdbeJumpHere(v, j1);
81284         }else{
81285           j1 = sqlite3VdbeCurrentAddr(v);
81286           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
81287         }
81288         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
81289       }
81290     }else if( IsVirtual(pTab) ){
81291       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
81292     }else{
81293       sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
81294       appendFlag = 1;
81295     }
81296     autoIncStep(pParse, regAutoinc, regRowid);
81297
81298     /* Push onto the stack, data for all columns of the new entry, beginning
81299     ** with the first column.
81300     */
81301     nHidden = 0;
81302     for(i=0; i<pTab->nCol; i++){
81303       int iRegStore = regRowid+1+i;
81304       if( i==pTab->iPKey ){
81305         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
81306         ** Whenever this column is read, the record number will be substituted
81307         ** in its place.  So will fill this column with a NULL to avoid
81308         ** taking up data space with information that will never be used. */
81309         sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
81310         continue;
81311       }
81312       if( pColumn==0 ){
81313         if( IsHiddenColumn(&pTab->aCol[i]) ){
81314           assert( IsVirtual(pTab) );
81315           j = -1;
81316           nHidden++;
81317         }else{
81318           j = i - nHidden;
81319         }
81320       }else{
81321         for(j=0; j<pColumn->nId; j++){
81322           if( pColumn->a[j].idx==i ) break;
81323         }
81324       }
81325       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
81326         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
81327       }else if( useTempTable ){
81328         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); 
81329       }else if( pSelect ){
81330         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
81331       }else{
81332         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
81333       }
81334     }
81335
81336     /* Generate code to check constraints and generate index keys and
81337     ** do the insertion.
81338     */
81339 #ifndef SQLITE_OMIT_VIRTUALTABLE
81340     if( IsVirtual(pTab) ){
81341       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
81342       sqlite3VtabMakeWritable(pParse, pTab);
81343       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
81344       sqlite3MayAbort(pParse);
81345     }else
81346 #endif
81347     {
81348       int isReplace;    /* Set to true if constraints may cause a replace */
81349       sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
81350           keyColumn>=0, 0, onError, endOfLoop, &isReplace
81351       );
81352       sqlite3FkCheck(pParse, pTab, 0, regIns);
81353       sqlite3CompleteInsertion(
81354           pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
81355       );
81356     }
81357   }
81358
81359   /* Update the count of rows that are inserted
81360   */
81361   if( (db->flags & SQLITE_CountRows)!=0 ){
81362     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
81363   }
81364
81365   if( pTrigger ){
81366     /* Code AFTER triggers */
81367     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER, 
81368         pTab, regData-2-pTab->nCol, onError, endOfLoop);
81369   }
81370
81371   /* The bottom of the main insertion loop, if the data source
81372   ** is a SELECT statement.
81373   */
81374   sqlite3VdbeResolveLabel(v, endOfLoop);
81375   if( useTempTable ){
81376     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
81377     sqlite3VdbeJumpHere(v, addrInsTop);
81378     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
81379   }else if( pSelect ){
81380     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
81381     sqlite3VdbeJumpHere(v, addrInsTop);
81382   }
81383
81384   if( !IsVirtual(pTab) && !isView ){
81385     /* Close all tables opened */
81386     sqlite3VdbeAddOp1(v, OP_Close, baseCur);
81387     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
81388       sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
81389     }
81390   }
81391
81392 insert_end:
81393   /* Update the sqlite_sequence table by storing the content of the
81394   ** maximum rowid counter values recorded while inserting into
81395   ** autoincrement tables.
81396   */
81397   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
81398     sqlite3AutoincrementEnd(pParse);
81399   }
81400
81401   /*
81402   ** Return the number of rows inserted. If this routine is 
81403   ** generating code because of a call to sqlite3NestedParse(), do not
81404   ** invoke the callback function.
81405   */
81406   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
81407     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
81408     sqlite3VdbeSetNumCols(v, 1);
81409     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
81410   }
81411
81412 insert_cleanup:
81413   sqlite3SrcListDelete(db, pTabList);
81414   sqlite3ExprListDelete(db, pList);
81415   sqlite3SelectDelete(db, pSelect);
81416   sqlite3IdListDelete(db, pColumn);
81417   sqlite3DbFree(db, aRegIdx);
81418 }
81419
81420 /* Make sure "isView" and other macros defined above are undefined. Otherwise
81421 ** thely may interfere with compilation of other functions in this file
81422 ** (or in another file, if this file becomes part of the amalgamation).  */
81423 #ifdef isView
81424  #undef isView
81425 #endif
81426 #ifdef pTrigger
81427  #undef pTrigger
81428 #endif
81429 #ifdef tmask
81430  #undef tmask
81431 #endif
81432
81433
81434 /*
81435 ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
81436 **
81437 ** The input is a range of consecutive registers as follows:
81438 **
81439 **    1.  The rowid of the row after the update.
81440 **
81441 **    2.  The data in the first column of the entry after the update.
81442 **
81443 **    i.  Data from middle columns...
81444 **
81445 **    N.  The data in the last column of the entry after the update.
81446 **
81447 ** The regRowid parameter is the index of the register containing (1).
81448 **
81449 ** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
81450 ** the address of a register containing the rowid before the update takes
81451 ** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
81452 ** is false, indicating an INSERT statement, then a non-zero rowidChng 
81453 ** indicates that the rowid was explicitly specified as part of the
81454 ** INSERT statement. If rowidChng is false, it means that  the rowid is
81455 ** computed automatically in an insert or that the rowid value is not 
81456 ** modified by an update.
81457 **
81458 ** The code generated by this routine store new index entries into
81459 ** registers identified by aRegIdx[].  No index entry is created for
81460 ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
81461 ** the same as the order of indices on the linked list of indices
81462 ** attached to the table.
81463 **
81464 ** This routine also generates code to check constraints.  NOT NULL,
81465 ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
81466 ** then the appropriate action is performed.  There are five possible
81467 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
81468 **
81469 **  Constraint type  Action       What Happens
81470 **  ---------------  ----------   ----------------------------------------
81471 **  any              ROLLBACK     The current transaction is rolled back and
81472 **                                sqlite3_exec() returns immediately with a
81473 **                                return code of SQLITE_CONSTRAINT.
81474 **
81475 **  any              ABORT        Back out changes from the current command
81476 **                                only (do not do a complete rollback) then
81477 **                                cause sqlite3_exec() to return immediately
81478 **                                with SQLITE_CONSTRAINT.
81479 **
81480 **  any              FAIL         Sqlite_exec() returns immediately with a
81481 **                                return code of SQLITE_CONSTRAINT.  The
81482 **                                transaction is not rolled back and any
81483 **                                prior changes are retained.
81484 **
81485 **  any              IGNORE       The record number and data is popped from
81486 **                                the stack and there is an immediate jump
81487 **                                to label ignoreDest.
81488 **
81489 **  NOT NULL         REPLACE      The NULL value is replace by the default
81490 **                                value for that column.  If the default value
81491 **                                is NULL, the action is the same as ABORT.
81492 **
81493 **  UNIQUE           REPLACE      The other row that conflicts with the row
81494 **                                being inserted is removed.
81495 **
81496 **  CHECK            REPLACE      Illegal.  The results in an exception.
81497 **
81498 ** Which action to take is determined by the overrideError parameter.
81499 ** Or if overrideError==OE_Default, then the pParse->onError parameter
81500 ** is used.  Or if pParse->onError==OE_Default then the onError value
81501 ** for the constraint is used.
81502 **
81503 ** The calling routine must open a read/write cursor for pTab with
81504 ** cursor number "baseCur".  All indices of pTab must also have open
81505 ** read/write cursors with cursor number baseCur+i for the i-th cursor.
81506 ** Except, if there is no possibility of a REPLACE action then
81507 ** cursors do not need to be open for indices where aRegIdx[i]==0.
81508 */
81509 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
81510   Parse *pParse,      /* The parser context */
81511   Table *pTab,        /* the table into which we are inserting */
81512   int baseCur,        /* Index of a read/write cursor pointing at pTab */
81513   int regRowid,       /* Index of the range of input registers */
81514   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
81515   int rowidChng,      /* True if the rowid might collide with existing entry */
81516   int isUpdate,       /* True for UPDATE, False for INSERT */
81517   int overrideError,  /* Override onError to this if not OE_Default */
81518   int ignoreDest,     /* Jump to this label on an OE_Ignore resolution */
81519   int *pbMayReplace   /* OUT: Set to true if constraint may cause a replace */
81520 ){
81521   int i;              /* loop counter */
81522   Vdbe *v;            /* VDBE under constrution */
81523   int nCol;           /* Number of columns */
81524   int onError;        /* Conflict resolution strategy */
81525   int j1;             /* Addresss of jump instruction */
81526   int j2 = 0, j3;     /* Addresses of jump instructions */
81527   int regData;        /* Register containing first data column */
81528   int iCur;           /* Table cursor number */
81529   Index *pIdx;         /* Pointer to one of the indices */
81530   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
81531   int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
81532
81533   v = sqlite3GetVdbe(pParse);
81534   assert( v!=0 );
81535   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
81536   nCol = pTab->nCol;
81537   regData = regRowid + 1;
81538
81539   /* Test all NOT NULL constraints.
81540   */
81541   for(i=0; i<nCol; i++){
81542     if( i==pTab->iPKey ){
81543       continue;
81544     }
81545     onError = pTab->aCol[i].notNull;
81546     if( onError==OE_None ) continue;
81547     if( overrideError!=OE_Default ){
81548       onError = overrideError;
81549     }else if( onError==OE_Default ){
81550       onError = OE_Abort;
81551     }
81552     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
81553       onError = OE_Abort;
81554     }
81555     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
81556         || onError==OE_Ignore || onError==OE_Replace );
81557     switch( onError ){
81558       case OE_Abort:
81559         sqlite3MayAbort(pParse);
81560       case OE_Rollback:
81561       case OE_Fail: {
81562         char *zMsg;
81563         j1 = sqlite3VdbeAddOp3(v, OP_HaltIfNull,
81564                                   SQLITE_CONSTRAINT, onError, regData+i);
81565         zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL",
81566                               pTab->zName, pTab->aCol[i].zName);
81567         sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
81568         break;
81569       }
81570       case OE_Ignore: {
81571         sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
81572         break;
81573       }
81574       default: {
81575         assert( onError==OE_Replace );
81576         j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
81577         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
81578         sqlite3VdbeJumpHere(v, j1);
81579         break;
81580       }
81581     }
81582   }
81583
81584   /* Test all CHECK constraints
81585   */
81586 #ifndef SQLITE_OMIT_CHECK
81587   if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
81588     int allOk = sqlite3VdbeMakeLabel(v);
81589     pParse->ckBase = regData;
81590     sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
81591     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
81592     if( onError==OE_Ignore ){
81593       sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
81594     }else{
81595       sqlite3HaltConstraint(pParse, onError, 0, 0);
81596     }
81597     sqlite3VdbeResolveLabel(v, allOk);
81598   }
81599 #endif /* !defined(SQLITE_OMIT_CHECK) */
81600
81601   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
81602   ** of the new record does not previously exist.  Except, if this
81603   ** is an UPDATE and the primary key is not changing, that is OK.
81604   */
81605   if( rowidChng ){
81606     onError = pTab->keyConf;
81607     if( overrideError!=OE_Default ){
81608       onError = overrideError;
81609     }else if( onError==OE_Default ){
81610       onError = OE_Abort;
81611     }
81612     
81613     if( isUpdate ){
81614       j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
81615     }
81616     j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
81617     switch( onError ){
81618       default: {
81619         onError = OE_Abort;
81620         /* Fall thru into the next case */
81621       }
81622       case OE_Rollback:
81623       case OE_Abort:
81624       case OE_Fail: {
81625         sqlite3HaltConstraint(
81626           pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
81627         break;
81628       }
81629       case OE_Replace: {
81630         /* If there are DELETE triggers on this table and the
81631         ** recursive-triggers flag is set, call GenerateRowDelete() to
81632         ** remove the conflicting row from the the table. This will fire
81633         ** the triggers and remove both the table and index b-tree entries.
81634         **
81635         ** Otherwise, if there are no triggers or the recursive-triggers
81636         ** flag is not set, but the table has one or more indexes, call 
81637         ** GenerateRowIndexDelete(). This removes the index b-tree entries 
81638         ** only. The table b-tree entry will be replaced by the new entry 
81639         ** when it is inserted.  
81640         **
81641         ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
81642         ** also invoke MultiWrite() to indicate that this VDBE may require
81643         ** statement rollback (if the statement is aborted after the delete
81644         ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
81645         ** but being more selective here allows statements like:
81646         **
81647         **   REPLACE INTO t(rowid) VALUES($newrowid)
81648         **
81649         ** to run without a statement journal if there are no indexes on the
81650         ** table.
81651         */
81652         Trigger *pTrigger = 0;
81653         if( pParse->db->flags&SQLITE_RecTriggers ){
81654           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
81655         }
81656         if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
81657           sqlite3MultiWrite(pParse);
81658           sqlite3GenerateRowDelete(
81659               pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
81660           );
81661         }else if( pTab->pIndex ){
81662           sqlite3MultiWrite(pParse);
81663           sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
81664         }
81665         seenReplace = 1;
81666         break;
81667       }
81668       case OE_Ignore: {
81669         assert( seenReplace==0 );
81670         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
81671         break;
81672       }
81673     }
81674     sqlite3VdbeJumpHere(v, j3);
81675     if( isUpdate ){
81676       sqlite3VdbeJumpHere(v, j2);
81677     }
81678   }
81679
81680   /* Test all UNIQUE constraints by creating entries for each UNIQUE
81681   ** index and making sure that duplicate entries do not already exist.
81682   ** Add the new records to the indices as we go.
81683   */
81684   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
81685     int regIdx;
81686     int regR;
81687
81688     if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
81689
81690     /* Create a key for accessing the index entry */
81691     regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
81692     for(i=0; i<pIdx->nColumn; i++){
81693       int idx = pIdx->aiColumn[i];
81694       if( idx==pTab->iPKey ){
81695         sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
81696       }else{
81697         sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
81698       }
81699     }
81700     sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
81701     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
81702     sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
81703     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
81704
81705     /* Find out what action to take in case there is an indexing conflict */
81706     onError = pIdx->onError;
81707     if( onError==OE_None ){ 
81708       sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
81709       continue;  /* pIdx is not a UNIQUE index */
81710     }
81711     if( overrideError!=OE_Default ){
81712       onError = overrideError;
81713     }else if( onError==OE_Default ){
81714       onError = OE_Abort;
81715     }
81716     if( seenReplace ){
81717       if( onError==OE_Ignore ) onError = OE_Replace;
81718       else if( onError==OE_Fail ) onError = OE_Abort;
81719     }
81720     
81721     /* Check to see if the new index entry will be unique */
81722     regR = sqlite3GetTempReg(pParse);
81723     sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
81724     j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
81725                            regR, SQLITE_INT_TO_PTR(regIdx),
81726                            P4_INT32);
81727     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
81728
81729     /* Generate code that executes if the new index entry is not unique */
81730     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
81731         || onError==OE_Ignore || onError==OE_Replace );
81732     switch( onError ){
81733       case OE_Rollback:
81734       case OE_Abort:
81735       case OE_Fail: {
81736         int j;
81737         StrAccum errMsg;
81738         const char *zSep;
81739         char *zErr;
81740
81741         sqlite3StrAccumInit(&errMsg, 0, 0, 200);
81742         errMsg.db = pParse->db;
81743         zSep = pIdx->nColumn>1 ? "columns " : "column ";
81744         for(j=0; j<pIdx->nColumn; j++){
81745           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
81746           sqlite3StrAccumAppend(&errMsg, zSep, -1);
81747           zSep = ", ";
81748           sqlite3StrAccumAppend(&errMsg, zCol, -1);
81749         }
81750         sqlite3StrAccumAppend(&errMsg,
81751             pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
81752         zErr = sqlite3StrAccumFinish(&errMsg);
81753         sqlite3HaltConstraint(pParse, onError, zErr, 0);
81754         sqlite3DbFree(errMsg.db, zErr);
81755         break;
81756       }
81757       case OE_Ignore: {
81758         assert( seenReplace==0 );
81759         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
81760         break;
81761       }
81762       default: {
81763         Trigger *pTrigger = 0;
81764         assert( onError==OE_Replace );
81765         sqlite3MultiWrite(pParse);
81766         if( pParse->db->flags&SQLITE_RecTriggers ){
81767           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
81768         }
81769         sqlite3GenerateRowDelete(
81770             pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
81771         );
81772         seenReplace = 1;
81773         break;
81774       }
81775     }
81776     sqlite3VdbeJumpHere(v, j3);
81777     sqlite3ReleaseTempReg(pParse, regR);
81778   }
81779   
81780   if( pbMayReplace ){
81781     *pbMayReplace = seenReplace;
81782   }
81783 }
81784
81785 /*
81786 ** This routine generates code to finish the INSERT or UPDATE operation
81787 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
81788 ** A consecutive range of registers starting at regRowid contains the
81789 ** rowid and the content to be inserted.
81790 **
81791 ** The arguments to this routine should be the same as the first six
81792 ** arguments to sqlite3GenerateConstraintChecks.
81793 */
81794 SQLITE_PRIVATE void sqlite3CompleteInsertion(
81795   Parse *pParse,      /* The parser context */
81796   Table *pTab,        /* the table into which we are inserting */
81797   int baseCur,        /* Index of a read/write cursor pointing at pTab */
81798   int regRowid,       /* Range of content */
81799   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
81800   int isUpdate,       /* True for UPDATE, False for INSERT */
81801   int appendBias,     /* True if this is likely to be an append */
81802   int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
81803 ){
81804   int i;
81805   Vdbe *v;
81806   int nIdx;
81807   Index *pIdx;
81808   u8 pik_flags;
81809   int regData;
81810   int regRec;
81811
81812   v = sqlite3GetVdbe(pParse);
81813   assert( v!=0 );
81814   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
81815   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
81816   for(i=nIdx-1; i>=0; i--){
81817     if( aRegIdx[i]==0 ) continue;
81818     sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
81819     if( useSeekResult ){
81820       sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
81821     }
81822   }
81823   regData = regRowid + 1;
81824   regRec = sqlite3GetTempReg(pParse);
81825   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
81826   sqlite3TableAffinityStr(v, pTab);
81827   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
81828   if( pParse->nested ){
81829     pik_flags = 0;
81830   }else{
81831     pik_flags = OPFLAG_NCHANGE;
81832     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
81833   }
81834   if( appendBias ){
81835     pik_flags |= OPFLAG_APPEND;
81836   }
81837   if( useSeekResult ){
81838     pik_flags |= OPFLAG_USESEEKRESULT;
81839   }
81840   sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
81841   if( !pParse->nested ){
81842     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
81843   }
81844   sqlite3VdbeChangeP5(v, pik_flags);
81845 }
81846
81847 /*
81848 ** Generate code that will open cursors for a table and for all
81849 ** indices of that table.  The "baseCur" parameter is the cursor number used
81850 ** for the table.  Indices are opened on subsequent cursors.
81851 **
81852 ** Return the number of indices on the table.
81853 */
81854 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
81855   Parse *pParse,   /* Parsing context */
81856   Table *pTab,     /* Table to be opened */
81857   int baseCur,     /* Cursor number assigned to the table */
81858   int op           /* OP_OpenRead or OP_OpenWrite */
81859 ){
81860   int i;
81861   int iDb;
81862   Index *pIdx;
81863   Vdbe *v;
81864
81865   if( IsVirtual(pTab) ) return 0;
81866   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
81867   v = sqlite3GetVdbe(pParse);
81868   assert( v!=0 );
81869   sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
81870   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
81871     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
81872     assert( pIdx->pSchema==pTab->pSchema );
81873     sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
81874                       (char*)pKey, P4_KEYINFO_HANDOFF);
81875     VdbeComment((v, "%s", pIdx->zName));
81876   }
81877   if( pParse->nTab<baseCur+i ){
81878     pParse->nTab = baseCur+i;
81879   }
81880   return i-1;
81881 }
81882
81883
81884 #ifdef SQLITE_TEST
81885 /*
81886 ** The following global variable is incremented whenever the
81887 ** transfer optimization is used.  This is used for testing
81888 ** purposes only - to make sure the transfer optimization really
81889 ** is happening when it is suppose to.
81890 */
81891 SQLITE_API int sqlite3_xferopt_count;
81892 #endif /* SQLITE_TEST */
81893
81894
81895 #ifndef SQLITE_OMIT_XFER_OPT
81896 /*
81897 ** Check to collation names to see if they are compatible.
81898 */
81899 static int xferCompatibleCollation(const char *z1, const char *z2){
81900   if( z1==0 ){
81901     return z2==0;
81902   }
81903   if( z2==0 ){
81904     return 0;
81905   }
81906   return sqlite3StrICmp(z1, z2)==0;
81907 }
81908
81909
81910 /*
81911 ** Check to see if index pSrc is compatible as a source of data
81912 ** for index pDest in an insert transfer optimization.  The rules
81913 ** for a compatible index:
81914 **
81915 **    *   The index is over the same set of columns
81916 **    *   The same DESC and ASC markings occurs on all columns
81917 **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
81918 **    *   The same collating sequence on each column
81919 */
81920 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
81921   int i;
81922   assert( pDest && pSrc );
81923   assert( pDest->pTable!=pSrc->pTable );
81924   if( pDest->nColumn!=pSrc->nColumn ){
81925     return 0;   /* Different number of columns */
81926   }
81927   if( pDest->onError!=pSrc->onError ){
81928     return 0;   /* Different conflict resolution strategies */
81929   }
81930   for(i=0; i<pSrc->nColumn; i++){
81931     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
81932       return 0;   /* Different columns indexed */
81933     }
81934     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
81935       return 0;   /* Different sort orders */
81936     }
81937     if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
81938       return 0;   /* Different collating sequences */
81939     }
81940   }
81941
81942   /* If no test above fails then the indices must be compatible */
81943   return 1;
81944 }
81945
81946 /*
81947 ** Attempt the transfer optimization on INSERTs of the form
81948 **
81949 **     INSERT INTO tab1 SELECT * FROM tab2;
81950 **
81951 ** This optimization is only attempted if
81952 **
81953 **    (1)  tab1 and tab2 have identical schemas including all the
81954 **         same indices and constraints
81955 **
81956 **    (2)  tab1 and tab2 are different tables
81957 **
81958 **    (3)  There must be no triggers on tab1
81959 **
81960 **    (4)  The result set of the SELECT statement is "*"
81961 **
81962 **    (5)  The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
81963 **         or LIMIT clause.
81964 **
81965 **    (6)  The SELECT statement is a simple (not a compound) select that
81966 **         contains only tab2 in its FROM clause
81967 **
81968 ** This method for implementing the INSERT transfers raw records from
81969 ** tab2 over to tab1.  The columns are not decoded.  Raw records from
81970 ** the indices of tab2 are transfered to tab1 as well.  In so doing,
81971 ** the resulting tab1 has much less fragmentation.
81972 **
81973 ** This routine returns TRUE if the optimization is attempted.  If any
81974 ** of the conditions above fail so that the optimization should not
81975 ** be attempted, then this routine returns FALSE.
81976 */
81977 static int xferOptimization(
81978   Parse *pParse,        /* Parser context */
81979   Table *pDest,         /* The table we are inserting into */
81980   Select *pSelect,      /* A SELECT statement to use as the data source */
81981   int onError,          /* How to handle constraint errors */
81982   int iDbDest           /* The database of pDest */
81983 ){
81984   ExprList *pEList;                /* The result set of the SELECT */
81985   Table *pSrc;                     /* The table in the FROM clause of SELECT */
81986   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
81987   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
81988   int i;                           /* Loop counter */
81989   int iDbSrc;                      /* The database of pSrc */
81990   int iSrc, iDest;                 /* Cursors from source and destination */
81991   int addr1, addr2;                /* Loop addresses */
81992   int emptyDestTest;               /* Address of test for empty pDest */
81993   int emptySrcTest;                /* Address of test for empty pSrc */
81994   Vdbe *v;                         /* The VDBE we are building */
81995   KeyInfo *pKey;                   /* Key information for an index */
81996   int regAutoinc;                  /* Memory register used by AUTOINC */
81997   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
81998   int regData, regRowid;           /* Registers holding data and rowid */
81999
82000   if( pSelect==0 ){
82001     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
82002   }
82003   if( sqlite3TriggerList(pParse, pDest) ){
82004     return 0;   /* tab1 must not have triggers */
82005   }
82006 #ifndef SQLITE_OMIT_VIRTUALTABLE
82007   if( pDest->tabFlags & TF_Virtual ){
82008     return 0;   /* tab1 must not be a virtual table */
82009   }
82010 #endif
82011   if( onError==OE_Default ){
82012     onError = OE_Abort;
82013   }
82014   if( onError!=OE_Abort && onError!=OE_Rollback ){
82015     return 0;   /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
82016   }
82017   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
82018   if( pSelect->pSrc->nSrc!=1 ){
82019     return 0;   /* FROM clause must have exactly one term */
82020   }
82021   if( pSelect->pSrc->a[0].pSelect ){
82022     return 0;   /* FROM clause cannot contain a subquery */
82023   }
82024   if( pSelect->pWhere ){
82025     return 0;   /* SELECT may not have a WHERE clause */
82026   }
82027   if( pSelect->pOrderBy ){
82028     return 0;   /* SELECT may not have an ORDER BY clause */
82029   }
82030   /* Do not need to test for a HAVING clause.  If HAVING is present but
82031   ** there is no ORDER BY, we will get an error. */
82032   if( pSelect->pGroupBy ){
82033     return 0;   /* SELECT may not have a GROUP BY clause */
82034   }
82035   if( pSelect->pLimit ){
82036     return 0;   /* SELECT may not have a LIMIT clause */
82037   }
82038   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
82039   if( pSelect->pPrior ){
82040     return 0;   /* SELECT may not be a compound query */
82041   }
82042   if( pSelect->selFlags & SF_Distinct ){
82043     return 0;   /* SELECT may not be DISTINCT */
82044   }
82045   pEList = pSelect->pEList;
82046   assert( pEList!=0 );
82047   if( pEList->nExpr!=1 ){
82048     return 0;   /* The result set must have exactly one column */
82049   }
82050   assert( pEList->a[0].pExpr );
82051   if( pEList->a[0].pExpr->op!=TK_ALL ){
82052     return 0;   /* The result set must be the special operator "*" */
82053   }
82054
82055   /* At this point we have established that the statement is of the
82056   ** correct syntactic form to participate in this optimization.  Now
82057   ** we have to check the semantics.
82058   */
82059   pItem = pSelect->pSrc->a;
82060   pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
82061   if( pSrc==0 ){
82062     return 0;   /* FROM clause does not contain a real table */
82063   }
82064   if( pSrc==pDest ){
82065     return 0;   /* tab1 and tab2 may not be the same table */
82066   }
82067 #ifndef SQLITE_OMIT_VIRTUALTABLE
82068   if( pSrc->tabFlags & TF_Virtual ){
82069     return 0;   /* tab2 must not be a virtual table */
82070   }
82071 #endif
82072   if( pSrc->pSelect ){
82073     return 0;   /* tab2 may not be a view */
82074   }
82075   if( pDest->nCol!=pSrc->nCol ){
82076     return 0;   /* Number of columns must be the same in tab1 and tab2 */
82077   }
82078   if( pDest->iPKey!=pSrc->iPKey ){
82079     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
82080   }
82081   for(i=0; i<pDest->nCol; i++){
82082     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
82083       return 0;    /* Affinity must be the same on all columns */
82084     }
82085     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
82086       return 0;    /* Collating sequence must be the same on all columns */
82087     }
82088     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
82089       return 0;    /* tab2 must be NOT NULL if tab1 is */
82090     }
82091   }
82092   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
82093     if( pDestIdx->onError!=OE_None ){
82094       destHasUniqueIdx = 1;
82095     }
82096     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
82097       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
82098     }
82099     if( pSrcIdx==0 ){
82100       return 0;    /* pDestIdx has no corresponding index in pSrc */
82101     }
82102   }
82103 #ifndef SQLITE_OMIT_CHECK
82104   if( pDest->pCheck && sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
82105     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
82106   }
82107 #endif
82108
82109   /* If we get this far, it means either:
82110   **
82111   **    *   We can always do the transfer if the table contains an
82112   **        an integer primary key
82113   **
82114   **    *   We can conditionally do the transfer if the destination
82115   **        table is empty.
82116   */
82117 #ifdef SQLITE_TEST
82118   sqlite3_xferopt_count++;
82119 #endif
82120   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
82121   v = sqlite3GetVdbe(pParse);
82122   sqlite3CodeVerifySchema(pParse, iDbSrc);
82123   iSrc = pParse->nTab++;
82124   iDest = pParse->nTab++;
82125   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
82126   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
82127   if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
82128     /* If tables do not have an INTEGER PRIMARY KEY and there
82129     ** are indices to be copied and the destination is not empty,
82130     ** we have to disallow the transfer optimization because the
82131     ** the rowids might change which will mess up indexing.
82132     **
82133     ** Or if the destination has a UNIQUE index and is not empty,
82134     ** we also disallow the transfer optimization because we cannot
82135     ** insure that all entries in the union of DEST and SRC will be
82136     ** unique.
82137     */
82138     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
82139     emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
82140     sqlite3VdbeJumpHere(v, addr1);
82141   }else{
82142     emptyDestTest = 0;
82143   }
82144   sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
82145   emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
82146   regData = sqlite3GetTempReg(pParse);
82147   regRowid = sqlite3GetTempReg(pParse);
82148   if( pDest->iPKey>=0 ){
82149     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
82150     addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
82151     sqlite3HaltConstraint(
82152         pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
82153     sqlite3VdbeJumpHere(v, addr2);
82154     autoIncStep(pParse, regAutoinc, regRowid);
82155   }else if( pDest->pIndex==0 ){
82156     addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
82157   }else{
82158     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
82159     assert( (pDest->tabFlags & TF_Autoincrement)==0 );
82160   }
82161   sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
82162   sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
82163   sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
82164   sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
82165   sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
82166   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
82167     for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
82168       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
82169     }
82170     assert( pSrcIdx );
82171     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
82172     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
82173     pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
82174     sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
82175                       (char*)pKey, P4_KEYINFO_HANDOFF);
82176     VdbeComment((v, "%s", pSrcIdx->zName));
82177     pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
82178     sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
82179                       (char*)pKey, P4_KEYINFO_HANDOFF);
82180     VdbeComment((v, "%s", pDestIdx->zName));
82181     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
82182     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
82183     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
82184     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
82185     sqlite3VdbeJumpHere(v, addr1);
82186   }
82187   sqlite3VdbeJumpHere(v, emptySrcTest);
82188   sqlite3ReleaseTempReg(pParse, regRowid);
82189   sqlite3ReleaseTempReg(pParse, regData);
82190   sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
82191   sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
82192   if( emptyDestTest ){
82193     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
82194     sqlite3VdbeJumpHere(v, emptyDestTest);
82195     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
82196     return 0;
82197   }else{
82198     return 1;
82199   }
82200 }
82201 #endif /* SQLITE_OMIT_XFER_OPT */
82202
82203 /************** End of insert.c **********************************************/
82204 /************** Begin file legacy.c ******************************************/
82205 /*
82206 ** 2001 September 15
82207 **
82208 ** The author disclaims copyright to this source code.  In place of
82209 ** a legal notice, here is a blessing:
82210 **
82211 **    May you do good and not evil.
82212 **    May you find forgiveness for yourself and forgive others.
82213 **    May you share freely, never taking more than you give.
82214 **
82215 *************************************************************************
82216 ** Main file for the SQLite library.  The routines in this file
82217 ** implement the programmer interface to the library.  Routines in
82218 ** other files are for internal use by SQLite and should not be
82219 ** accessed by users of the library.
82220 */
82221
82222
82223 /*
82224 ** Execute SQL code.  Return one of the SQLITE_ success/failure
82225 ** codes.  Also write an error message into memory obtained from
82226 ** malloc() and make *pzErrMsg point to that message.
82227 **
82228 ** If the SQL is a query, then for each row in the query result
82229 ** the xCallback() function is called.  pArg becomes the first
82230 ** argument to xCallback().  If xCallback=NULL then no callback
82231 ** is invoked, even for queries.
82232 */
82233 SQLITE_API int sqlite3_exec(
82234   sqlite3 *db,                /* The database on which the SQL executes */
82235   const char *zSql,           /* The SQL to be executed */
82236   sqlite3_callback xCallback, /* Invoke this callback routine */
82237   void *pArg,                 /* First argument to xCallback() */
82238   char **pzErrMsg             /* Write error messages here */
82239 ){
82240   int rc = SQLITE_OK;         /* Return code */
82241   const char *zLeftover;      /* Tail of unprocessed SQL */
82242   sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
82243   char **azCols = 0;          /* Names of result columns */
82244   int nRetry = 0;             /* Number of retry attempts */
82245   int callbackIsInit;         /* True if callback data is initialized */
82246
82247   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
82248   if( zSql==0 ) zSql = "";
82249
82250   sqlite3_mutex_enter(db->mutex);
82251   sqlite3Error(db, SQLITE_OK, 0);
82252   while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
82253     int nCol;
82254     char **azVals = 0;
82255
82256     pStmt = 0;
82257     rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);
82258     assert( rc==SQLITE_OK || pStmt==0 );
82259     if( rc!=SQLITE_OK ){
82260       continue;
82261     }
82262     if( !pStmt ){
82263       /* this happens for a comment or white-space */
82264       zSql = zLeftover;
82265       continue;
82266     }
82267
82268     callbackIsInit = 0;
82269     nCol = sqlite3_column_count(pStmt);
82270
82271     while( 1 ){
82272       int i;
82273       rc = sqlite3_step(pStmt);
82274
82275       /* Invoke the callback function if required */
82276       if( xCallback && (SQLITE_ROW==rc || 
82277           (SQLITE_DONE==rc && !callbackIsInit
82278                            && db->flags&SQLITE_NullCallback)) ){
82279         if( !callbackIsInit ){
82280           azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
82281           if( azCols==0 ){
82282             goto exec_out;
82283           }
82284           for(i=0; i<nCol; i++){
82285             azCols[i] = (char *)sqlite3_column_name(pStmt, i);
82286             /* sqlite3VdbeSetColName() installs column names as UTF8
82287             ** strings so there is no way for sqlite3_column_name() to fail. */
82288             assert( azCols[i]!=0 );
82289           }
82290           callbackIsInit = 1;
82291         }
82292         if( rc==SQLITE_ROW ){
82293           azVals = &azCols[nCol];
82294           for(i=0; i<nCol; i++){
82295             azVals[i] = (char *)sqlite3_column_text(pStmt, i);
82296             if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
82297               db->mallocFailed = 1;
82298               goto exec_out;
82299             }
82300           }
82301         }
82302         if( xCallback(pArg, nCol, azVals, azCols) ){
82303           rc = SQLITE_ABORT;
82304           sqlite3VdbeFinalize((Vdbe *)pStmt);
82305           pStmt = 0;
82306           sqlite3Error(db, SQLITE_ABORT, 0);
82307           goto exec_out;
82308         }
82309       }
82310
82311       if( rc!=SQLITE_ROW ){
82312         rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
82313         pStmt = 0;
82314         if( rc!=SQLITE_SCHEMA ){
82315           nRetry = 0;
82316           zSql = zLeftover;
82317           while( sqlite3Isspace(zSql[0]) ) zSql++;
82318         }
82319         break;
82320       }
82321     }
82322
82323     sqlite3DbFree(db, azCols);
82324     azCols = 0;
82325   }
82326
82327 exec_out:
82328   if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
82329   sqlite3DbFree(db, azCols);
82330
82331   rc = sqlite3ApiExit(db, rc);
82332   if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
82333     int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
82334     *pzErrMsg = sqlite3Malloc(nErrMsg);
82335     if( *pzErrMsg ){
82336       memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
82337     }else{
82338       rc = SQLITE_NOMEM;
82339       sqlite3Error(db, SQLITE_NOMEM, 0);
82340     }
82341   }else if( pzErrMsg ){
82342     *pzErrMsg = 0;
82343   }
82344
82345   assert( (rc&db->errMask)==rc );
82346   sqlite3_mutex_leave(db->mutex);
82347   return rc;
82348 }
82349
82350 /************** End of legacy.c **********************************************/
82351 /************** Begin file loadext.c *****************************************/
82352 /*
82353 ** 2006 June 7
82354 **
82355 ** The author disclaims copyright to this source code.  In place of
82356 ** a legal notice, here is a blessing:
82357 **
82358 **    May you do good and not evil.
82359 **    May you find forgiveness for yourself and forgive others.
82360 **    May you share freely, never taking more than you give.
82361 **
82362 *************************************************************************
82363 ** This file contains code used to dynamically load extensions into
82364 ** the SQLite library.
82365 */
82366
82367 #ifndef SQLITE_CORE
82368   #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
82369 #endif
82370 /************** Include sqlite3ext.h in the middle of loadext.c **************/
82371 /************** Begin file sqlite3ext.h **************************************/
82372 /*
82373 ** 2006 June 7
82374 **
82375 ** The author disclaims copyright to this source code.  In place of
82376 ** a legal notice, here is a blessing:
82377 **
82378 **    May you do good and not evil.
82379 **    May you find forgiveness for yourself and forgive others.
82380 **    May you share freely, never taking more than you give.
82381 **
82382 *************************************************************************
82383 ** This header file defines the SQLite interface for use by
82384 ** shared libraries that want to be imported as extensions into
82385 ** an SQLite instance.  Shared libraries that intend to be loaded
82386 ** as extensions by SQLite should #include this file instead of 
82387 ** sqlite3.h.
82388 */
82389 #ifndef _SQLITE3EXT_H_
82390 #define _SQLITE3EXT_H_
82391
82392 typedef struct sqlite3_api_routines sqlite3_api_routines;
82393
82394 /*
82395 ** The following structure holds pointers to all of the SQLite API
82396 ** routines.
82397 **
82398 ** WARNING:  In order to maintain backwards compatibility, add new
82399 ** interfaces to the end of this structure only.  If you insert new
82400 ** interfaces in the middle of this structure, then older different
82401 ** versions of SQLite will not be able to load each others' shared
82402 ** libraries!
82403 */
82404 struct sqlite3_api_routines {
82405   void * (*aggregate_context)(sqlite3_context*,int nBytes);
82406   int  (*aggregate_count)(sqlite3_context*);
82407   int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
82408   int  (*bind_double)(sqlite3_stmt*,int,double);
82409   int  (*bind_int)(sqlite3_stmt*,int,int);
82410   int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
82411   int  (*bind_null)(sqlite3_stmt*,int);
82412   int  (*bind_parameter_count)(sqlite3_stmt*);
82413   int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
82414   const char * (*bind_parameter_name)(sqlite3_stmt*,int);
82415   int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
82416   int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
82417   int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
82418   int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
82419   int  (*busy_timeout)(sqlite3*,int ms);
82420   int  (*changes)(sqlite3*);
82421   int  (*close)(sqlite3*);
82422   int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const char*));
82423   int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const void*));
82424   const void * (*column_blob)(sqlite3_stmt*,int iCol);
82425   int  (*column_bytes)(sqlite3_stmt*,int iCol);
82426   int  (*column_bytes16)(sqlite3_stmt*,int iCol);
82427   int  (*column_count)(sqlite3_stmt*pStmt);
82428   const char * (*column_database_name)(sqlite3_stmt*,int);
82429   const void * (*column_database_name16)(sqlite3_stmt*,int);
82430   const char * (*column_decltype)(sqlite3_stmt*,int i);
82431   const void * (*column_decltype16)(sqlite3_stmt*,int);
82432   double  (*column_double)(sqlite3_stmt*,int iCol);
82433   int  (*column_int)(sqlite3_stmt*,int iCol);
82434   sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
82435   const char * (*column_name)(sqlite3_stmt*,int);
82436   const void * (*column_name16)(sqlite3_stmt*,int);
82437   const char * (*column_origin_name)(sqlite3_stmt*,int);
82438   const void * (*column_origin_name16)(sqlite3_stmt*,int);
82439   const char * (*column_table_name)(sqlite3_stmt*,int);
82440   const void * (*column_table_name16)(sqlite3_stmt*,int);
82441   const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
82442   const void * (*column_text16)(sqlite3_stmt*,int iCol);
82443   int  (*column_type)(sqlite3_stmt*,int iCol);
82444   sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
82445   void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
82446   int  (*complete)(const char*sql);
82447   int  (*complete16)(const void*sql);
82448   int  (*create_collation)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*));
82449   int  (*create_collation16)(sqlite3*,const void*,int,void*,int(*)(void*,int,const void*,int,const void*));
82450   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*));
82451   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*));
82452   int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
82453   int  (*data_count)(sqlite3_stmt*pStmt);
82454   sqlite3 * (*db_handle)(sqlite3_stmt*);
82455   int (*declare_vtab)(sqlite3*,const char*);
82456   int  (*enable_shared_cache)(int);
82457   int  (*errcode)(sqlite3*db);
82458   const char * (*errmsg)(sqlite3*);
82459   const void * (*errmsg16)(sqlite3*);
82460   int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
82461   int  (*expired)(sqlite3_stmt*);
82462   int  (*finalize)(sqlite3_stmt*pStmt);
82463   void  (*free)(void*);
82464   void  (*free_table)(char**result);
82465   int  (*get_autocommit)(sqlite3*);
82466   void * (*get_auxdata)(sqlite3_context*,int);
82467   int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
82468   int  (*global_recover)(void);
82469   void  (*interruptx)(sqlite3*);
82470   sqlite_int64  (*last_insert_rowid)(sqlite3*);
82471   const char * (*libversion)(void);
82472   int  (*libversion_number)(void);
82473   void *(*malloc)(int);
82474   char * (*mprintf)(const char*,...);
82475   int  (*open)(const char*,sqlite3**);
82476   int  (*open16)(const void*,sqlite3**);
82477   int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
82478   int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
82479   void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
82480   void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
82481   void *(*realloc)(void*,int);
82482   int  (*reset)(sqlite3_stmt*pStmt);
82483   void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
82484   void  (*result_double)(sqlite3_context*,double);
82485   void  (*result_error)(sqlite3_context*,const char*,int);
82486   void  (*result_error16)(sqlite3_context*,const void*,int);
82487   void  (*result_int)(sqlite3_context*,int);
82488   void  (*result_int64)(sqlite3_context*,sqlite_int64);
82489   void  (*result_null)(sqlite3_context*);
82490   void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
82491   void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
82492   void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
82493   void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
82494   void  (*result_value)(sqlite3_context*,sqlite3_value*);
82495   void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
82496   int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,const char*,const char*),void*);
82497   void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
82498   char * (*snprintf)(int,char*,const char*,...);
82499   int  (*step)(sqlite3_stmt*);
82500   int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,char const**,char const**,int*,int*,int*);
82501   void  (*thread_cleanup)(void);
82502   int  (*total_changes)(sqlite3*);
82503   void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
82504   int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
82505   void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,sqlite_int64),void*);
82506   void * (*user_data)(sqlite3_context*);
82507   const void * (*value_blob)(sqlite3_value*);
82508   int  (*value_bytes)(sqlite3_value*);
82509   int  (*value_bytes16)(sqlite3_value*);
82510   double  (*value_double)(sqlite3_value*);
82511   int  (*value_int)(sqlite3_value*);
82512   sqlite_int64  (*value_int64)(sqlite3_value*);
82513   int  (*value_numeric_type)(sqlite3_value*);
82514   const unsigned char * (*value_text)(sqlite3_value*);
82515   const void * (*value_text16)(sqlite3_value*);
82516   const void * (*value_text16be)(sqlite3_value*);
82517   const void * (*value_text16le)(sqlite3_value*);
82518   int  (*value_type)(sqlite3_value*);
82519   char *(*vmprintf)(const char*,va_list);
82520   /* Added ??? */
82521   int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
82522   /* Added by 3.3.13 */
82523   int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
82524   int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
82525   int (*clear_bindings)(sqlite3_stmt*);
82526   /* Added by 3.4.1 */
82527   int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,void (*xDestroy)(void *));
82528   /* Added by 3.5.0 */
82529   int (*bind_zeroblob)(sqlite3_stmt*,int,int);
82530   int (*blob_bytes)(sqlite3_blob*);
82531   int (*blob_close)(sqlite3_blob*);
82532   int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,int,sqlite3_blob**);
82533   int (*blob_read)(sqlite3_blob*,void*,int,int);
82534   int (*blob_write)(sqlite3_blob*,const void*,int,int);
82535   int (*create_collation_v2)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*),void(*)(void*));
82536   int (*file_control)(sqlite3*,const char*,int,void*);
82537   sqlite3_int64 (*memory_highwater)(int);
82538   sqlite3_int64 (*memory_used)(void);
82539   sqlite3_mutex *(*mutex_alloc)(int);
82540   void (*mutex_enter)(sqlite3_mutex*);
82541   void (*mutex_free)(sqlite3_mutex*);
82542   void (*mutex_leave)(sqlite3_mutex*);
82543   int (*mutex_try)(sqlite3_mutex*);
82544   int (*open_v2)(const char*,sqlite3**,int,const char*);
82545   int (*release_memory)(int);
82546   void (*result_error_nomem)(sqlite3_context*);
82547   void (*result_error_toobig)(sqlite3_context*);
82548   int (*sleep)(int);
82549   void (*soft_heap_limit)(int);
82550   sqlite3_vfs *(*vfs_find)(const char*);
82551   int (*vfs_register)(sqlite3_vfs*,int);
82552   int (*vfs_unregister)(sqlite3_vfs*);
82553   int (*xthreadsafe)(void);
82554   void (*result_zeroblob)(sqlite3_context*,int);
82555   void (*result_error_code)(sqlite3_context*,int);
82556   int (*test_control)(int, ...);
82557   void (*randomness)(int,void*);
82558   sqlite3 *(*context_db_handle)(sqlite3_context*);
82559   int (*extended_result_codes)(sqlite3*,int);
82560   int (*limit)(sqlite3*,int,int);
82561   sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
82562   const char *(*sql)(sqlite3_stmt*);
82563   int (*status)(int,int*,int*,int);
82564 };
82565
82566 /*
82567 ** The following macros redefine the API routines so that they are
82568 ** redirected throught the global sqlite3_api structure.
82569 **
82570 ** This header file is also used by the loadext.c source file
82571 ** (part of the main SQLite library - not an extension) so that
82572 ** it can get access to the sqlite3_api_routines structure
82573 ** definition.  But the main library does not want to redefine
82574 ** the API.  So the redefinition macros are only valid if the
82575 ** SQLITE_CORE macros is undefined.
82576 */
82577 #ifndef SQLITE_CORE
82578 #define sqlite3_aggregate_context      sqlite3_api->aggregate_context
82579 #ifndef SQLITE_OMIT_DEPRECATED
82580 #define sqlite3_aggregate_count        sqlite3_api->aggregate_count
82581 #endif
82582 #define sqlite3_bind_blob              sqlite3_api->bind_blob
82583 #define sqlite3_bind_double            sqlite3_api->bind_double
82584 #define sqlite3_bind_int               sqlite3_api->bind_int
82585 #define sqlite3_bind_int64             sqlite3_api->bind_int64
82586 #define sqlite3_bind_null              sqlite3_api->bind_null
82587 #define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
82588 #define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
82589 #define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
82590 #define sqlite3_bind_text              sqlite3_api->bind_text
82591 #define sqlite3_bind_text16            sqlite3_api->bind_text16
82592 #define sqlite3_bind_value             sqlite3_api->bind_value
82593 #define sqlite3_busy_handler           sqlite3_api->busy_handler
82594 #define sqlite3_busy_timeout           sqlite3_api->busy_timeout
82595 #define sqlite3_changes                sqlite3_api->changes
82596 #define sqlite3_close                  sqlite3_api->close
82597 #define sqlite3_collation_needed       sqlite3_api->collation_needed
82598 #define sqlite3_collation_needed16     sqlite3_api->collation_needed16
82599 #define sqlite3_column_blob            sqlite3_api->column_blob
82600 #define sqlite3_column_bytes           sqlite3_api->column_bytes
82601 #define sqlite3_column_bytes16         sqlite3_api->column_bytes16
82602 #define sqlite3_column_count           sqlite3_api->column_count
82603 #define sqlite3_column_database_name   sqlite3_api->column_database_name
82604 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
82605 #define sqlite3_column_decltype        sqlite3_api->column_decltype
82606 #define sqlite3_column_decltype16      sqlite3_api->column_decltype16
82607 #define sqlite3_column_double          sqlite3_api->column_double
82608 #define sqlite3_column_int             sqlite3_api->column_int
82609 #define sqlite3_column_int64           sqlite3_api->column_int64
82610 #define sqlite3_column_name            sqlite3_api->column_name
82611 #define sqlite3_column_name16          sqlite3_api->column_name16
82612 #define sqlite3_column_origin_name     sqlite3_api->column_origin_name
82613 #define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
82614 #define sqlite3_column_table_name      sqlite3_api->column_table_name
82615 #define sqlite3_column_table_name16    sqlite3_api->column_table_name16
82616 #define sqlite3_column_text            sqlite3_api->column_text
82617 #define sqlite3_column_text16          sqlite3_api->column_text16
82618 #define sqlite3_column_type            sqlite3_api->column_type
82619 #define sqlite3_column_value           sqlite3_api->column_value
82620 #define sqlite3_commit_hook            sqlite3_api->commit_hook
82621 #define sqlite3_complete               sqlite3_api->complete
82622 #define sqlite3_complete16             sqlite3_api->complete16
82623 #define sqlite3_create_collation       sqlite3_api->create_collation
82624 #define sqlite3_create_collation16     sqlite3_api->create_collation16
82625 #define sqlite3_create_function        sqlite3_api->create_function
82626 #define sqlite3_create_function16      sqlite3_api->create_function16
82627 #define sqlite3_create_module          sqlite3_api->create_module
82628 #define sqlite3_create_module_v2       sqlite3_api->create_module_v2
82629 #define sqlite3_data_count             sqlite3_api->data_count
82630 #define sqlite3_db_handle              sqlite3_api->db_handle
82631 #define sqlite3_declare_vtab           sqlite3_api->declare_vtab
82632 #define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
82633 #define sqlite3_errcode                sqlite3_api->errcode
82634 #define sqlite3_errmsg                 sqlite3_api->errmsg
82635 #define sqlite3_errmsg16               sqlite3_api->errmsg16
82636 #define sqlite3_exec                   sqlite3_api->exec
82637 #ifndef SQLITE_OMIT_DEPRECATED
82638 #define sqlite3_expired                sqlite3_api->expired
82639 #endif
82640 #define sqlite3_finalize               sqlite3_api->finalize
82641 #define sqlite3_free                   sqlite3_api->free
82642 #define sqlite3_free_table             sqlite3_api->free_table
82643 #define sqlite3_get_autocommit         sqlite3_api->get_autocommit
82644 #define sqlite3_get_auxdata            sqlite3_api->get_auxdata
82645 #define sqlite3_get_table              sqlite3_api->get_table
82646 #ifndef SQLITE_OMIT_DEPRECATED
82647 #define sqlite3_global_recover         sqlite3_api->global_recover
82648 #endif
82649 #define sqlite3_interrupt              sqlite3_api->interruptx
82650 #define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
82651 #define sqlite3_libversion             sqlite3_api->libversion
82652 #define sqlite3_libversion_number      sqlite3_api->libversion_number
82653 #define sqlite3_malloc                 sqlite3_api->malloc
82654 #define sqlite3_mprintf                sqlite3_api->mprintf
82655 #define sqlite3_open                   sqlite3_api->open
82656 #define sqlite3_open16                 sqlite3_api->open16
82657 #define sqlite3_prepare                sqlite3_api->prepare
82658 #define sqlite3_prepare16              sqlite3_api->prepare16
82659 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
82660 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
82661 #define sqlite3_profile                sqlite3_api->profile
82662 #define sqlite3_progress_handler       sqlite3_api->progress_handler
82663 #define sqlite3_realloc                sqlite3_api->realloc
82664 #define sqlite3_reset                  sqlite3_api->reset
82665 #define sqlite3_result_blob            sqlite3_api->result_blob
82666 #define sqlite3_result_double          sqlite3_api->result_double
82667 #define sqlite3_result_error           sqlite3_api->result_error
82668 #define sqlite3_result_error16         sqlite3_api->result_error16
82669 #define sqlite3_result_int             sqlite3_api->result_int
82670 #define sqlite3_result_int64           sqlite3_api->result_int64
82671 #define sqlite3_result_null            sqlite3_api->result_null
82672 #define sqlite3_result_text            sqlite3_api->result_text
82673 #define sqlite3_result_text16          sqlite3_api->result_text16
82674 #define sqlite3_result_text16be        sqlite3_api->result_text16be
82675 #define sqlite3_result_text16le        sqlite3_api->result_text16le
82676 #define sqlite3_result_value           sqlite3_api->result_value
82677 #define sqlite3_rollback_hook          sqlite3_api->rollback_hook
82678 #define sqlite3_set_authorizer         sqlite3_api->set_authorizer
82679 #define sqlite3_set_auxdata            sqlite3_api->set_auxdata
82680 #define sqlite3_snprintf               sqlite3_api->snprintf
82681 #define sqlite3_step                   sqlite3_api->step
82682 #define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
82683 #define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
82684 #define sqlite3_total_changes          sqlite3_api->total_changes
82685 #define sqlite3_trace                  sqlite3_api->trace
82686 #ifndef SQLITE_OMIT_DEPRECATED
82687 #define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
82688 #endif
82689 #define sqlite3_update_hook            sqlite3_api->update_hook
82690 #define sqlite3_user_data              sqlite3_api->user_data
82691 #define sqlite3_value_blob             sqlite3_api->value_blob
82692 #define sqlite3_value_bytes            sqlite3_api->value_bytes
82693 #define sqlite3_value_bytes16          sqlite3_api->value_bytes16
82694 #define sqlite3_value_double           sqlite3_api->value_double
82695 #define sqlite3_value_int              sqlite3_api->value_int
82696 #define sqlite3_value_int64            sqlite3_api->value_int64
82697 #define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
82698 #define sqlite3_value_text             sqlite3_api->value_text
82699 #define sqlite3_value_text16           sqlite3_api->value_text16
82700 #define sqlite3_value_text16be         sqlite3_api->value_text16be
82701 #define sqlite3_value_text16le         sqlite3_api->value_text16le
82702 #define sqlite3_value_type             sqlite3_api->value_type
82703 #define sqlite3_vmprintf               sqlite3_api->vmprintf
82704 #define sqlite3_overload_function      sqlite3_api->overload_function
82705 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
82706 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
82707 #define sqlite3_clear_bindings         sqlite3_api->clear_bindings
82708 #define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
82709 #define sqlite3_blob_bytes             sqlite3_api->blob_bytes
82710 #define sqlite3_blob_close             sqlite3_api->blob_close
82711 #define sqlite3_blob_open              sqlite3_api->blob_open
82712 #define sqlite3_blob_read              sqlite3_api->blob_read
82713 #define sqlite3_blob_write             sqlite3_api->blob_write
82714 #define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
82715 #define sqlite3_file_control           sqlite3_api->file_control
82716 #define sqlite3_memory_highwater       sqlite3_api->memory_highwater
82717 #define sqlite3_memory_used            sqlite3_api->memory_used
82718 #define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
82719 #define sqlite3_mutex_enter            sqlite3_api->mutex_enter
82720 #define sqlite3_mutex_free             sqlite3_api->mutex_free
82721 #define sqlite3_mutex_leave            sqlite3_api->mutex_leave
82722 #define sqlite3_mutex_try              sqlite3_api->mutex_try
82723 #define sqlite3_open_v2                sqlite3_api->open_v2
82724 #define sqlite3_release_memory         sqlite3_api->release_memory
82725 #define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
82726 #define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
82727 #define sqlite3_sleep                  sqlite3_api->sleep
82728 #define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
82729 #define sqlite3_vfs_find               sqlite3_api->vfs_find
82730 #define sqlite3_vfs_register           sqlite3_api->vfs_register
82731 #define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
82732 #define sqlite3_threadsafe             sqlite3_api->xthreadsafe
82733 #define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
82734 #define sqlite3_result_error_code      sqlite3_api->result_error_code
82735 #define sqlite3_test_control           sqlite3_api->test_control
82736 #define sqlite3_randomness             sqlite3_api->randomness
82737 #define sqlite3_context_db_handle      sqlite3_api->context_db_handle
82738 #define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
82739 #define sqlite3_limit                  sqlite3_api->limit
82740 #define sqlite3_next_stmt              sqlite3_api->next_stmt
82741 #define sqlite3_sql                    sqlite3_api->sql
82742 #define sqlite3_status                 sqlite3_api->status
82743 #endif /* SQLITE_CORE */
82744
82745 #define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api = 0;
82746 #define SQLITE_EXTENSION_INIT2(v)  sqlite3_api = v;
82747
82748 #endif /* _SQLITE3EXT_H_ */
82749
82750 /************** End of sqlite3ext.h ******************************************/
82751 /************** Continuing where we left off in loadext.c ********************/
82752
82753 #ifndef SQLITE_OMIT_LOAD_EXTENSION
82754
82755 /*
82756 ** Some API routines are omitted when various features are
82757 ** excluded from a build of SQLite.  Substitute a NULL pointer
82758 ** for any missing APIs.
82759 */
82760 #ifndef SQLITE_ENABLE_COLUMN_METADATA
82761 # define sqlite3_column_database_name   0
82762 # define sqlite3_column_database_name16 0
82763 # define sqlite3_column_table_name      0
82764 # define sqlite3_column_table_name16    0
82765 # define sqlite3_column_origin_name     0
82766 # define sqlite3_column_origin_name16   0
82767 # define sqlite3_table_column_metadata  0
82768 #endif
82769
82770 #ifdef SQLITE_OMIT_AUTHORIZATION
82771 # define sqlite3_set_authorizer         0
82772 #endif
82773
82774 #ifdef SQLITE_OMIT_UTF16
82775 # define sqlite3_bind_text16            0
82776 # define sqlite3_collation_needed16     0
82777 # define sqlite3_column_decltype16      0
82778 # define sqlite3_column_name16          0
82779 # define sqlite3_column_text16          0
82780 # define sqlite3_complete16             0
82781 # define sqlite3_create_collation16     0
82782 # define sqlite3_create_function16      0
82783 # define sqlite3_errmsg16               0
82784 # define sqlite3_open16                 0
82785 # define sqlite3_prepare16              0
82786 # define sqlite3_prepare16_v2           0
82787 # define sqlite3_result_error16         0
82788 # define sqlite3_result_text16          0
82789 # define sqlite3_result_text16be        0
82790 # define sqlite3_result_text16le        0
82791 # define sqlite3_value_text16           0
82792 # define sqlite3_value_text16be         0
82793 # define sqlite3_value_text16le         0
82794 # define sqlite3_column_database_name16 0
82795 # define sqlite3_column_table_name16    0
82796 # define sqlite3_column_origin_name16   0
82797 #endif
82798
82799 #ifdef SQLITE_OMIT_COMPLETE
82800 # define sqlite3_complete 0
82801 # define sqlite3_complete16 0
82802 #endif
82803
82804 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
82805 # define sqlite3_progress_handler 0
82806 #endif
82807
82808 #ifdef SQLITE_OMIT_VIRTUALTABLE
82809 # define sqlite3_create_module 0
82810 # define sqlite3_create_module_v2 0
82811 # define sqlite3_declare_vtab 0
82812 #endif
82813
82814 #ifdef SQLITE_OMIT_SHARED_CACHE
82815 # define sqlite3_enable_shared_cache 0
82816 #endif
82817
82818 #ifdef SQLITE_OMIT_TRACE
82819 # define sqlite3_profile       0
82820 # define sqlite3_trace         0
82821 #endif
82822
82823 #ifdef SQLITE_OMIT_GET_TABLE
82824 # define sqlite3_free_table    0
82825 # define sqlite3_get_table     0
82826 #endif
82827
82828 #ifdef SQLITE_OMIT_INCRBLOB
82829 #define sqlite3_bind_zeroblob  0
82830 #define sqlite3_blob_bytes     0
82831 #define sqlite3_blob_close     0
82832 #define sqlite3_blob_open      0
82833 #define sqlite3_blob_read      0
82834 #define sqlite3_blob_write     0
82835 #endif
82836
82837 /*
82838 ** The following structure contains pointers to all SQLite API routines.
82839 ** A pointer to this structure is passed into extensions when they are
82840 ** loaded so that the extension can make calls back into the SQLite
82841 ** library.
82842 **
82843 ** When adding new APIs, add them to the bottom of this structure
82844 ** in order to preserve backwards compatibility.
82845 **
82846 ** Extensions that use newer APIs should first call the
82847 ** sqlite3_libversion_number() to make sure that the API they
82848 ** intend to use is supported by the library.  Extensions should
82849 ** also check to make sure that the pointer to the function is
82850 ** not NULL before calling it.
82851 */
82852 static const sqlite3_api_routines sqlite3Apis = {
82853   sqlite3_aggregate_context,
82854 #ifndef SQLITE_OMIT_DEPRECATED
82855   sqlite3_aggregate_count,
82856 #else
82857   0,
82858 #endif
82859   sqlite3_bind_blob,
82860   sqlite3_bind_double,
82861   sqlite3_bind_int,
82862   sqlite3_bind_int64,
82863   sqlite3_bind_null,
82864   sqlite3_bind_parameter_count,
82865   sqlite3_bind_parameter_index,
82866   sqlite3_bind_parameter_name,
82867   sqlite3_bind_text,
82868   sqlite3_bind_text16,
82869   sqlite3_bind_value,
82870   sqlite3_busy_handler,
82871   sqlite3_busy_timeout,
82872   sqlite3_changes,
82873   sqlite3_close,
82874   sqlite3_collation_needed,
82875   sqlite3_collation_needed16,
82876   sqlite3_column_blob,
82877   sqlite3_column_bytes,
82878   sqlite3_column_bytes16,
82879   sqlite3_column_count,
82880   sqlite3_column_database_name,
82881   sqlite3_column_database_name16,
82882   sqlite3_column_decltype,
82883   sqlite3_column_decltype16,
82884   sqlite3_column_double,
82885   sqlite3_column_int,
82886   sqlite3_column_int64,
82887   sqlite3_column_name,
82888   sqlite3_column_name16,
82889   sqlite3_column_origin_name,
82890   sqlite3_column_origin_name16,
82891   sqlite3_column_table_name,
82892   sqlite3_column_table_name16,
82893   sqlite3_column_text,
82894   sqlite3_column_text16,
82895   sqlite3_column_type,
82896   sqlite3_column_value,
82897   sqlite3_commit_hook,
82898   sqlite3_complete,
82899   sqlite3_complete16,
82900   sqlite3_create_collation,
82901   sqlite3_create_collation16,
82902   sqlite3_create_function,
82903   sqlite3_create_function16,
82904   sqlite3_create_module,
82905   sqlite3_data_count,
82906   sqlite3_db_handle,
82907   sqlite3_declare_vtab,
82908   sqlite3_enable_shared_cache,
82909   sqlite3_errcode,
82910   sqlite3_errmsg,
82911   sqlite3_errmsg16,
82912   sqlite3_exec,
82913 #ifndef SQLITE_OMIT_DEPRECATED
82914   sqlite3_expired,
82915 #else
82916   0,
82917 #endif
82918   sqlite3_finalize,
82919   sqlite3_free,
82920   sqlite3_free_table,
82921   sqlite3_get_autocommit,
82922   sqlite3_get_auxdata,
82923   sqlite3_get_table,
82924   0,     /* Was sqlite3_global_recover(), but that function is deprecated */
82925   sqlite3_interrupt,
82926   sqlite3_last_insert_rowid,
82927   sqlite3_libversion,
82928   sqlite3_libversion_number,
82929   sqlite3_malloc,
82930   sqlite3_mprintf,
82931   sqlite3_open,
82932   sqlite3_open16,
82933   sqlite3_prepare,
82934   sqlite3_prepare16,
82935   sqlite3_profile,
82936   sqlite3_progress_handler,
82937   sqlite3_realloc,
82938   sqlite3_reset,
82939   sqlite3_result_blob,
82940   sqlite3_result_double,
82941   sqlite3_result_error,
82942   sqlite3_result_error16,
82943   sqlite3_result_int,
82944   sqlite3_result_int64,
82945   sqlite3_result_null,
82946   sqlite3_result_text,
82947   sqlite3_result_text16,
82948   sqlite3_result_text16be,
82949   sqlite3_result_text16le,
82950   sqlite3_result_value,
82951   sqlite3_rollback_hook,
82952   sqlite3_set_authorizer,
82953   sqlite3_set_auxdata,
82954   sqlite3_snprintf,
82955   sqlite3_step,
82956   sqlite3_table_column_metadata,
82957 #ifndef SQLITE_OMIT_DEPRECATED
82958   sqlite3_thread_cleanup,
82959 #else
82960   0,
82961 #endif
82962   sqlite3_total_changes,
82963   sqlite3_trace,
82964 #ifndef SQLITE_OMIT_DEPRECATED
82965   sqlite3_transfer_bindings,
82966 #else
82967   0,
82968 #endif
82969   sqlite3_update_hook,
82970   sqlite3_user_data,
82971   sqlite3_value_blob,
82972   sqlite3_value_bytes,
82973   sqlite3_value_bytes16,
82974   sqlite3_value_double,
82975   sqlite3_value_int,
82976   sqlite3_value_int64,
82977   sqlite3_value_numeric_type,
82978   sqlite3_value_text,
82979   sqlite3_value_text16,
82980   sqlite3_value_text16be,
82981   sqlite3_value_text16le,
82982   sqlite3_value_type,
82983   sqlite3_vmprintf,
82984   /*
82985   ** The original API set ends here.  All extensions can call any
82986   ** of the APIs above provided that the pointer is not NULL.  But
82987   ** before calling APIs that follow, extension should check the
82988   ** sqlite3_libversion_number() to make sure they are dealing with
82989   ** a library that is new enough to support that API.
82990   *************************************************************************
82991   */
82992   sqlite3_overload_function,
82993
82994   /*
82995   ** Added after 3.3.13
82996   */
82997   sqlite3_prepare_v2,
82998   sqlite3_prepare16_v2,
82999   sqlite3_clear_bindings,
83000
83001   /*
83002   ** Added for 3.4.1
83003   */
83004   sqlite3_create_module_v2,
83005
83006   /*
83007   ** Added for 3.5.0
83008   */
83009   sqlite3_bind_zeroblob,
83010   sqlite3_blob_bytes,
83011   sqlite3_blob_close,
83012   sqlite3_blob_open,
83013   sqlite3_blob_read,
83014   sqlite3_blob_write,
83015   sqlite3_create_collation_v2,
83016   sqlite3_file_control,
83017   sqlite3_memory_highwater,
83018   sqlite3_memory_used,
83019 #ifdef SQLITE_MUTEX_OMIT
83020   0, 
83021   0, 
83022   0,
83023   0,
83024   0,
83025 #else
83026   sqlite3_mutex_alloc,
83027   sqlite3_mutex_enter,
83028   sqlite3_mutex_free,
83029   sqlite3_mutex_leave,
83030   sqlite3_mutex_try,
83031 #endif
83032   sqlite3_open_v2,
83033   sqlite3_release_memory,
83034   sqlite3_result_error_nomem,
83035   sqlite3_result_error_toobig,
83036   sqlite3_sleep,
83037   sqlite3_soft_heap_limit,
83038   sqlite3_vfs_find,
83039   sqlite3_vfs_register,
83040   sqlite3_vfs_unregister,
83041
83042   /*
83043   ** Added for 3.5.8
83044   */
83045   sqlite3_threadsafe,
83046   sqlite3_result_zeroblob,
83047   sqlite3_result_error_code,
83048   sqlite3_test_control,
83049   sqlite3_randomness,
83050   sqlite3_context_db_handle,
83051
83052   /*
83053   ** Added for 3.6.0
83054   */
83055   sqlite3_extended_result_codes,
83056   sqlite3_limit,
83057   sqlite3_next_stmt,
83058   sqlite3_sql,
83059   sqlite3_status,
83060 };
83061
83062 /*
83063 ** Attempt to load an SQLite extension library contained in the file
83064 ** zFile.  The entry point is zProc.  zProc may be 0 in which case a
83065 ** default entry point name (sqlite3_extension_init) is used.  Use
83066 ** of the default name is recommended.
83067 **
83068 ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
83069 **
83070 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with 
83071 ** error message text.  The calling function should free this memory
83072 ** by calling sqlite3DbFree(db, ).
83073 */
83074 static int sqlite3LoadExtension(
83075   sqlite3 *db,          /* Load the extension into this database connection */
83076   const char *zFile,    /* Name of the shared library containing extension */
83077   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
83078   char **pzErrMsg       /* Put error message here if not 0 */
83079 ){
83080   sqlite3_vfs *pVfs = db->pVfs;
83081   void *handle;
83082   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
83083   char *zErrmsg = 0;
83084   void **aHandle;
83085   const int nMsg = 300;
83086
83087   if( pzErrMsg ) *pzErrMsg = 0;
83088
83089   /* Ticket #1863.  To avoid a creating security problems for older
83090   ** applications that relink against newer versions of SQLite, the
83091   ** ability to run load_extension is turned off by default.  One
83092   ** must call sqlite3_enable_load_extension() to turn on extension
83093   ** loading.  Otherwise you get the following error.
83094   */
83095   if( (db->flags & SQLITE_LoadExtension)==0 ){
83096     if( pzErrMsg ){
83097       *pzErrMsg = sqlite3_mprintf("not authorized");
83098     }
83099     return SQLITE_ERROR;
83100   }
83101
83102   if( zProc==0 ){
83103     zProc = "sqlite3_extension_init";
83104   }
83105
83106   handle = sqlite3OsDlOpen(pVfs, zFile);
83107   if( handle==0 ){
83108     if( pzErrMsg ){
83109       zErrmsg = sqlite3StackAllocZero(db, nMsg);
83110       if( zErrmsg ){
83111         sqlite3_snprintf(nMsg, zErrmsg, 
83112             "unable to open shared library [%s]", zFile);
83113         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
83114         *pzErrMsg = sqlite3DbStrDup(0, zErrmsg);
83115         sqlite3StackFree(db, zErrmsg);
83116       }
83117     }
83118     return SQLITE_ERROR;
83119   }
83120   xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
83121                    sqlite3OsDlSym(pVfs, handle, zProc);
83122   if( xInit==0 ){
83123     if( pzErrMsg ){
83124       zErrmsg = sqlite3StackAllocZero(db, nMsg);
83125       if( zErrmsg ){
83126         sqlite3_snprintf(nMsg, zErrmsg,
83127             "no entry point [%s] in shared library [%s]", zProc,zFile);
83128         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
83129         *pzErrMsg = sqlite3DbStrDup(0, zErrmsg);
83130         sqlite3StackFree(db, zErrmsg);
83131       }
83132       sqlite3OsDlClose(pVfs, handle);
83133     }
83134     return SQLITE_ERROR;
83135   }else if( xInit(db, &zErrmsg, &sqlite3Apis) ){
83136     if( pzErrMsg ){
83137       *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
83138     }
83139     sqlite3_free(zErrmsg);
83140     sqlite3OsDlClose(pVfs, handle);
83141     return SQLITE_ERROR;
83142   }
83143
83144   /* Append the new shared library handle to the db->aExtension array. */
83145   aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
83146   if( aHandle==0 ){
83147     return SQLITE_NOMEM;
83148   }
83149   if( db->nExtension>0 ){
83150     memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
83151   }
83152   sqlite3DbFree(db, db->aExtension);
83153   db->aExtension = aHandle;
83154
83155   db->aExtension[db->nExtension++] = handle;
83156   return SQLITE_OK;
83157 }
83158 SQLITE_API int sqlite3_load_extension(
83159   sqlite3 *db,          /* Load the extension into this database connection */
83160   const char *zFile,    /* Name of the shared library containing extension */
83161   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
83162   char **pzErrMsg       /* Put error message here if not 0 */
83163 ){
83164   int rc;
83165   sqlite3_mutex_enter(db->mutex);
83166   rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
83167   rc = sqlite3ApiExit(db, rc);
83168   sqlite3_mutex_leave(db->mutex);
83169   return rc;
83170 }
83171
83172 /*
83173 ** Call this routine when the database connection is closing in order
83174 ** to clean up loaded extensions
83175 */
83176 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
83177   int i;
83178   assert( sqlite3_mutex_held(db->mutex) );
83179   for(i=0; i<db->nExtension; i++){
83180     sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
83181   }
83182   sqlite3DbFree(db, db->aExtension);
83183 }
83184
83185 /*
83186 ** Enable or disable extension loading.  Extension loading is disabled by
83187 ** default so as not to open security holes in older applications.
83188 */
83189 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
83190   sqlite3_mutex_enter(db->mutex);
83191   if( onoff ){
83192     db->flags |= SQLITE_LoadExtension;
83193   }else{
83194     db->flags &= ~SQLITE_LoadExtension;
83195   }
83196   sqlite3_mutex_leave(db->mutex);
83197   return SQLITE_OK;
83198 }
83199
83200 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
83201
83202 /*
83203 ** The auto-extension code added regardless of whether or not extension
83204 ** loading is supported.  We need a dummy sqlite3Apis pointer for that
83205 ** code if regular extension loading is not available.  This is that
83206 ** dummy pointer.
83207 */
83208 #ifdef SQLITE_OMIT_LOAD_EXTENSION
83209 static const sqlite3_api_routines sqlite3Apis = { 0 };
83210 #endif
83211
83212
83213 /*
83214 ** The following object holds the list of automatically loaded
83215 ** extensions.
83216 **
83217 ** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
83218 ** mutex must be held while accessing this list.
83219 */
83220 typedef struct sqlite3AutoExtList sqlite3AutoExtList;
83221 static SQLITE_WSD struct sqlite3AutoExtList {
83222   int nExt;              /* Number of entries in aExt[] */          
83223   void (**aExt)(void);   /* Pointers to the extension init functions */
83224 } sqlite3Autoext = { 0, 0 };
83225
83226 /* The "wsdAutoext" macro will resolve to the autoextension
83227 ** state vector.  If writable static data is unsupported on the target,
83228 ** we have to locate the state vector at run-time.  In the more common
83229 ** case where writable static data is supported, wsdStat can refer directly
83230 ** to the "sqlite3Autoext" state vector declared above.
83231 */
83232 #ifdef SQLITE_OMIT_WSD
83233 # define wsdAutoextInit \
83234   sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
83235 # define wsdAutoext x[0]
83236 #else
83237 # define wsdAutoextInit
83238 # define wsdAutoext sqlite3Autoext
83239 #endif
83240
83241
83242 /*
83243 ** Register a statically linked extension that is automatically
83244 ** loaded by every new database connection.
83245 */
83246 SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
83247   int rc = SQLITE_OK;
83248 #ifndef SQLITE_OMIT_AUTOINIT
83249   rc = sqlite3_initialize();
83250   if( rc ){
83251     return rc;
83252   }else
83253 #endif
83254   {
83255     int i;
83256 #if SQLITE_THREADSAFE
83257     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
83258 #endif
83259     wsdAutoextInit;
83260     sqlite3_mutex_enter(mutex);
83261     for(i=0; i<wsdAutoext.nExt; i++){
83262       if( wsdAutoext.aExt[i]==xInit ) break;
83263     }
83264     if( i==wsdAutoext.nExt ){
83265       int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
83266       void (**aNew)(void);
83267       aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
83268       if( aNew==0 ){
83269         rc = SQLITE_NOMEM;
83270       }else{
83271         wsdAutoext.aExt = aNew;
83272         wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
83273         wsdAutoext.nExt++;
83274       }
83275     }
83276     sqlite3_mutex_leave(mutex);
83277     assert( (rc&0xff)==rc );
83278     return rc;
83279   }
83280 }
83281
83282 /*
83283 ** Reset the automatic extension loading mechanism.
83284 */
83285 SQLITE_API void sqlite3_reset_auto_extension(void){
83286 #ifndef SQLITE_OMIT_AUTOINIT
83287   if( sqlite3_initialize()==SQLITE_OK )
83288 #endif
83289   {
83290 #if SQLITE_THREADSAFE
83291     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
83292 #endif
83293     wsdAutoextInit;
83294     sqlite3_mutex_enter(mutex);
83295     sqlite3_free(wsdAutoext.aExt);
83296     wsdAutoext.aExt = 0;
83297     wsdAutoext.nExt = 0;
83298     sqlite3_mutex_leave(mutex);
83299   }
83300 }
83301
83302 /*
83303 ** Load all automatic extensions.
83304 **
83305 ** If anything goes wrong, set an error in the database connection.
83306 */
83307 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
83308   int i;
83309   int go = 1;
83310   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
83311
83312   wsdAutoextInit;
83313   if( wsdAutoext.nExt==0 ){
83314     /* Common case: early out without every having to acquire a mutex */
83315     return;
83316   }
83317   for(i=0; go; i++){
83318     char *zErrmsg;
83319 #if SQLITE_THREADSAFE
83320     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
83321 #endif
83322     sqlite3_mutex_enter(mutex);
83323     if( i>=wsdAutoext.nExt ){
83324       xInit = 0;
83325       go = 0;
83326     }else{
83327       xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
83328               wsdAutoext.aExt[i];
83329     }
83330     sqlite3_mutex_leave(mutex);
83331     zErrmsg = 0;
83332     if( xInit && xInit(db, &zErrmsg, &sqlite3Apis) ){
83333       sqlite3Error(db, SQLITE_ERROR,
83334             "automatic extension loading failed: %s", zErrmsg);
83335       go = 0;
83336     }
83337     sqlite3_free(zErrmsg);
83338   }
83339 }
83340
83341 /************** End of loadext.c *********************************************/
83342 /************** Begin file pragma.c ******************************************/
83343 /*
83344 ** 2003 April 6
83345 **
83346 ** The author disclaims copyright to this source code.  In place of
83347 ** a legal notice, here is a blessing:
83348 **
83349 **    May you do good and not evil.
83350 **    May you find forgiveness for yourself and forgive others.
83351 **    May you share freely, never taking more than you give.
83352 **
83353 *************************************************************************
83354 ** This file contains code used to implement the PRAGMA command.
83355 */
83356
83357 /* Ignore this whole file if pragmas are disabled
83358 */
83359 #if !defined(SQLITE_OMIT_PRAGMA)
83360
83361 /*
83362 ** Interpret the given string as a safety level.  Return 0 for OFF,
83363 ** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or 
83364 ** unrecognized string argument.
83365 **
83366 ** Note that the values returned are one less that the values that
83367 ** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
83368 ** to support legacy SQL code.  The safety level used to be boolean
83369 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
83370 */
83371 static u8 getSafetyLevel(const char *z){
83372                              /* 123456789 123456789 */
83373   static const char zText[] = "onoffalseyestruefull";
83374   static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
83375   static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
83376   static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
83377   int i, n;
83378   if( sqlite3Isdigit(*z) ){
83379     return (u8)atoi(z);
83380   }
83381   n = sqlite3Strlen30(z);
83382   for(i=0; i<ArraySize(iLength); i++){
83383     if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
83384       return iValue[i];
83385     }
83386   }
83387   return 1;
83388 }
83389
83390 /*
83391 ** Interpret the given string as a boolean value.
83392 */
83393 static u8 getBoolean(const char *z){
83394   return getSafetyLevel(z)&1;
83395 }
83396
83397 /*
83398 ** Interpret the given string as a locking mode value.
83399 */
83400 static int getLockingMode(const char *z){
83401   if( z ){
83402     if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
83403     if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
83404   }
83405   return PAGER_LOCKINGMODE_QUERY;
83406 }
83407
83408 #ifndef SQLITE_OMIT_AUTOVACUUM
83409 /*
83410 ** Interpret the given string as an auto-vacuum mode value.
83411 **
83412 ** The following strings, "none", "full" and "incremental" are 
83413 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
83414 */
83415 static int getAutoVacuum(const char *z){
83416   int i;
83417   if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
83418   if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
83419   if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
83420   i = atoi(z);
83421   return (u8)((i>=0&&i<=2)?i:0);
83422 }
83423 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
83424
83425 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
83426 /*
83427 ** Interpret the given string as a temp db location. Return 1 for file
83428 ** backed temporary databases, 2 for the Red-Black tree in memory database
83429 ** and 0 to use the compile-time default.
83430 */
83431 static int getTempStore(const char *z){
83432   if( z[0]>='0' && z[0]<='2' ){
83433     return z[0] - '0';
83434   }else if( sqlite3StrICmp(z, "file")==0 ){
83435     return 1;
83436   }else if( sqlite3StrICmp(z, "memory")==0 ){
83437     return 2;
83438   }else{
83439     return 0;
83440   }
83441 }
83442 #endif /* SQLITE_PAGER_PRAGMAS */
83443
83444 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
83445 /*
83446 ** Invalidate temp storage, either when the temp storage is changed
83447 ** from default, or when 'file' and the temp_store_directory has changed
83448 */
83449 static int invalidateTempStorage(Parse *pParse){
83450   sqlite3 *db = pParse->db;
83451   if( db->aDb[1].pBt!=0 ){
83452     if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
83453       sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
83454         "from within a transaction");
83455       return SQLITE_ERROR;
83456     }
83457     sqlite3BtreeClose(db->aDb[1].pBt);
83458     db->aDb[1].pBt = 0;
83459     sqlite3ResetInternalSchema(db, 0);
83460   }
83461   return SQLITE_OK;
83462 }
83463 #endif /* SQLITE_PAGER_PRAGMAS */
83464
83465 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
83466 /*
83467 ** If the TEMP database is open, close it and mark the database schema
83468 ** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
83469 ** or DEFAULT_TEMP_STORE pragmas.
83470 */
83471 static int changeTempStorage(Parse *pParse, const char *zStorageType){
83472   int ts = getTempStore(zStorageType);
83473   sqlite3 *db = pParse->db;
83474   if( db->temp_store==ts ) return SQLITE_OK;
83475   if( invalidateTempStorage( pParse ) != SQLITE_OK ){
83476     return SQLITE_ERROR;
83477   }
83478   db->temp_store = (u8)ts;
83479   return SQLITE_OK;
83480 }
83481 #endif /* SQLITE_PAGER_PRAGMAS */
83482
83483 /*
83484 ** Generate code to return a single integer value.
83485 */
83486 static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
83487   Vdbe *v = sqlite3GetVdbe(pParse);
83488   int mem = ++pParse->nMem;
83489   i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
83490   if( pI64 ){
83491     memcpy(pI64, &value, sizeof(value));
83492   }
83493   sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
83494   sqlite3VdbeSetNumCols(v, 1);
83495   sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
83496   sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
83497 }
83498
83499 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
83500 /*
83501 ** Check to see if zRight and zLeft refer to a pragma that queries
83502 ** or changes one of the flags in db->flags.  Return 1 if so and 0 if not.
83503 ** Also, implement the pragma.
83504 */
83505 static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
83506   static const struct sPragmaType {
83507     const char *zName;  /* Name of the pragma */
83508     int mask;           /* Mask for the db->flags value */
83509   } aPragma[] = {
83510     { "full_column_names",        SQLITE_FullColNames  },
83511     { "short_column_names",       SQLITE_ShortColNames },
83512     { "count_changes",            SQLITE_CountRows     },
83513     { "empty_result_callbacks",   SQLITE_NullCallback  },
83514     { "legacy_file_format",       SQLITE_LegacyFileFmt },
83515     { "fullfsync",                SQLITE_FullFSync     },
83516     { "reverse_unordered_selects", SQLITE_ReverseOrder  },
83517 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
83518     { "automatic_index",          SQLITE_AutoIndex     },
83519 #endif
83520 #ifdef SQLITE_DEBUG
83521     { "sql_trace",                SQLITE_SqlTrace      },
83522     { "vdbe_listing",             SQLITE_VdbeListing   },
83523     { "vdbe_trace",               SQLITE_VdbeTrace     },
83524 #endif
83525 #ifndef SQLITE_OMIT_CHECK
83526     { "ignore_check_constraints", SQLITE_IgnoreChecks  },
83527 #endif
83528     /* The following is VERY experimental */
83529     { "writable_schema",          SQLITE_WriteSchema|SQLITE_RecoveryMode },
83530     { "omit_readlock",            SQLITE_NoReadlock    },
83531
83532     /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
83533     ** flag if there are any active statements. */
83534     { "read_uncommitted",         SQLITE_ReadUncommitted },
83535     { "recursive_triggers",       SQLITE_RecTriggers },
83536
83537     /* This flag may only be set if both foreign-key and trigger support
83538     ** are present in the build.  */
83539 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
83540     { "foreign_keys",             SQLITE_ForeignKeys },
83541 #endif
83542   };
83543   int i;
83544   const struct sPragmaType *p;
83545   for(i=0, p=aPragma; i<ArraySize(aPragma); i++, p++){
83546     if( sqlite3StrICmp(zLeft, p->zName)==0 ){
83547       sqlite3 *db = pParse->db;
83548       Vdbe *v;
83549       v = sqlite3GetVdbe(pParse);
83550       assert( v!=0 );  /* Already allocated by sqlite3Pragma() */
83551       if( ALWAYS(v) ){
83552         if( zRight==0 ){
83553           returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
83554         }else{
83555           int mask = p->mask;          /* Mask of bits to set or clear. */
83556           if( db->autoCommit==0 ){
83557             /* Foreign key support may not be enabled or disabled while not
83558             ** in auto-commit mode.  */
83559             mask &= ~(SQLITE_ForeignKeys);
83560           }
83561
83562           if( getBoolean(zRight) ){
83563             db->flags |= mask;
83564           }else{
83565             db->flags &= ~mask;
83566           }
83567
83568           /* Many of the flag-pragmas modify the code generated by the SQL 
83569           ** compiler (eg. count_changes). So add an opcode to expire all
83570           ** compiled SQL statements after modifying a pragma value.
83571           */
83572           sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
83573         }
83574       }
83575
83576       return 1;
83577     }
83578   }
83579   return 0;
83580 }
83581 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
83582
83583 /*
83584 ** Return a human-readable name for a constraint resolution action.
83585 */
83586 #ifndef SQLITE_OMIT_FOREIGN_KEY
83587 static const char *actionName(u8 action){
83588   const char *zName;
83589   switch( action ){
83590     case OE_SetNull:  zName = "SET NULL";        break;
83591     case OE_SetDflt:  zName = "SET DEFAULT";     break;
83592     case OE_Cascade:  zName = "CASCADE";         break;
83593     case OE_Restrict: zName = "RESTRICT";        break;
83594     default:          zName = "NO ACTION";  
83595                       assert( action==OE_None ); break;
83596   }
83597   return zName;
83598 }
83599 #endif
83600
83601
83602 /*
83603 ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
83604 ** defined in pager.h. This function returns the associated lowercase
83605 ** journal-mode name.
83606 */
83607 SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
83608   static char * const azModeName[] = {
83609     "delete", "persist", "off", "truncate", "memory"
83610 #ifndef SQLITE_OMIT_WAL
83611      , "wal"
83612 #endif
83613   };
83614   assert( PAGER_JOURNALMODE_DELETE==0 );
83615   assert( PAGER_JOURNALMODE_PERSIST==1 );
83616   assert( PAGER_JOURNALMODE_OFF==2 );
83617   assert( PAGER_JOURNALMODE_TRUNCATE==3 );
83618   assert( PAGER_JOURNALMODE_MEMORY==4 );
83619   assert( PAGER_JOURNALMODE_WAL==5 );
83620   assert( eMode>=0 && eMode<=ArraySize(azModeName) );
83621
83622   if( eMode==ArraySize(azModeName) ) return 0;
83623   return azModeName[eMode];
83624 }
83625
83626 /*
83627 ** Process a pragma statement.  
83628 **
83629 ** Pragmas are of this form:
83630 **
83631 **      PRAGMA [database.]id [= value]
83632 **
83633 ** The identifier might also be a string.  The value is a string, and
83634 ** identifier, or a number.  If minusFlag is true, then the value is
83635 ** a number that was preceded by a minus sign.
83636 **
83637 ** If the left side is "database.id" then pId1 is the database name
83638 ** and pId2 is the id.  If the left side is just "id" then pId1 is the
83639 ** id and pId2 is any empty string.
83640 */
83641 SQLITE_PRIVATE void sqlite3Pragma(
83642   Parse *pParse, 
83643   Token *pId1,        /* First part of [database.]id field */
83644   Token *pId2,        /* Second part of [database.]id field, or NULL */
83645   Token *pValue,      /* Token for <value>, or NULL */
83646   int minusFlag       /* True if a '-' sign preceded <value> */
83647 ){
83648   char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
83649   char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
83650   const char *zDb = 0;   /* The database name */
83651   Token *pId;            /* Pointer to <id> token */
83652   int iDb;               /* Database index for <database> */
83653   sqlite3 *db = pParse->db;
83654   Db *pDb;
83655   Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(db);
83656   if( v==0 ) return;
83657   sqlite3VdbeRunOnlyOnce(v);
83658   pParse->nMem = 2;
83659
83660   /* Interpret the [database.] part of the pragma statement. iDb is the
83661   ** index of the database this pragma is being applied to in db.aDb[]. */
83662   iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
83663   if( iDb<0 ) return;
83664   pDb = &db->aDb[iDb];
83665
83666   /* If the temp database has been explicitly named as part of the 
83667   ** pragma, make sure it is open. 
83668   */
83669   if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
83670     return;
83671   }
83672
83673   zLeft = sqlite3NameFromToken(db, pId);
83674   if( !zLeft ) return;
83675   if( minusFlag ){
83676     zRight = sqlite3MPrintf(db, "-%T", pValue);
83677   }else{
83678     zRight = sqlite3NameFromToken(db, pValue);
83679   }
83680
83681   assert( pId2 );
83682   zDb = pId2->n>0 ? pDb->zName : 0;
83683   if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
83684     goto pragma_out;
83685   }
83686  
83687 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
83688   /*
83689   **  PRAGMA [database.]default_cache_size
83690   **  PRAGMA [database.]default_cache_size=N
83691   **
83692   ** The first form reports the current persistent setting for the
83693   ** page cache size.  The value returned is the maximum number of
83694   ** pages in the page cache.  The second form sets both the current
83695   ** page cache size value and the persistent page cache size value
83696   ** stored in the database file.
83697   **
83698   ** Older versions of SQLite would set the default cache size to a
83699   ** negative number to indicate synchronous=OFF.  These days, synchronous
83700   ** is always on by default regardless of the sign of the default cache
83701   ** size.  But continue to take the absolute value of the default cache
83702   ** size of historical compatibility.
83703   */
83704   if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
83705     static const VdbeOpList getCacheSize[] = {
83706       { OP_Transaction, 0, 0,        0},                         /* 0 */
83707       { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
83708       { OP_IfPos,       1, 7,        0},
83709       { OP_Integer,     0, 2,        0},
83710       { OP_Subtract,    1, 2,        1},
83711       { OP_IfPos,       1, 7,        0},
83712       { OP_Integer,     0, 1,        0},                         /* 6 */
83713       { OP_ResultRow,   1, 1,        0},
83714     };
83715     int addr;
83716     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
83717     sqlite3VdbeUsesBtree(v, iDb);
83718     if( !zRight ){
83719       sqlite3VdbeSetNumCols(v, 1);
83720       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
83721       pParse->nMem += 2;
83722       addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
83723       sqlite3VdbeChangeP1(v, addr, iDb);
83724       sqlite3VdbeChangeP1(v, addr+1, iDb);
83725       sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
83726     }else{
83727       int size = atoi(zRight);
83728       if( size<0 ) size = -size;
83729       sqlite3BeginWriteOperation(pParse, 0, iDb);
83730       sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
83731       sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
83732       pDb->pSchema->cache_size = size;
83733       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
83734     }
83735   }else
83736
83737   /*
83738   **  PRAGMA [database.]page_size
83739   **  PRAGMA [database.]page_size=N
83740   **
83741   ** The first form reports the current setting for the
83742   ** database page size in bytes.  The second form sets the
83743   ** database page size value.  The value can only be set if
83744   ** the database has not yet been created.
83745   */
83746   if( sqlite3StrICmp(zLeft,"page_size")==0 ){
83747     Btree *pBt = pDb->pBt;
83748     assert( pBt!=0 );
83749     if( !zRight ){
83750       int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
83751       returnSingleInt(pParse, "page_size", size);
83752     }else{
83753       /* Malloc may fail when setting the page-size, as there is an internal
83754       ** buffer that the pager module resizes using sqlite3_realloc().
83755       */
83756       db->nextPagesize = atoi(zRight);
83757       if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
83758         db->mallocFailed = 1;
83759       }
83760     }
83761   }else
83762
83763   /*
83764   **  PRAGMA [database.]max_page_count
83765   **  PRAGMA [database.]max_page_count=N
83766   **
83767   ** The first form reports the current setting for the
83768   ** maximum number of pages in the database file.  The 
83769   ** second form attempts to change this setting.  Both
83770   ** forms return the current setting.
83771   */
83772   if( sqlite3StrICmp(zLeft,"max_page_count")==0 ){
83773     Btree *pBt = pDb->pBt;
83774     int newMax = 0;
83775     assert( pBt!=0 );
83776     if( zRight ){
83777       newMax = atoi(zRight);
83778     }
83779     if( ALWAYS(pBt) ){
83780       newMax = sqlite3BtreeMaxPageCount(pBt, newMax);
83781     }
83782     returnSingleInt(pParse, "max_page_count", newMax);
83783   }else
83784
83785   /*
83786   **  PRAGMA [database.]secure_delete
83787   **  PRAGMA [database.]secure_delete=ON/OFF
83788   **
83789   ** The first form reports the current setting for the
83790   ** secure_delete flag.  The second form changes the secure_delete
83791   ** flag setting and reports thenew value.
83792   */
83793   if( sqlite3StrICmp(zLeft,"secure_delete")==0 ){
83794     Btree *pBt = pDb->pBt;
83795     int b = -1;
83796     assert( pBt!=0 );
83797     if( zRight ){
83798       b = getBoolean(zRight);
83799     }
83800     if( pId2->n==0 && b>=0 ){
83801       int ii;
83802       for(ii=0; ii<db->nDb; ii++){
83803         sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
83804       }
83805     }
83806     b = sqlite3BtreeSecureDelete(pBt, b);
83807     returnSingleInt(pParse, "secure_delete", b);
83808   }else
83809
83810   /*
83811   **  PRAGMA [database.]page_count
83812   **
83813   ** Return the number of pages in the specified database.
83814   */
83815   if( sqlite3StrICmp(zLeft,"page_count")==0 ){
83816     int iReg;
83817     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
83818     sqlite3CodeVerifySchema(pParse, iDb);
83819     iReg = ++pParse->nMem;
83820     sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
83821     sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
83822     sqlite3VdbeSetNumCols(v, 1);
83823     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "page_count", SQLITE_STATIC);
83824   }else
83825
83826   /*
83827   **  PRAGMA [database.]locking_mode
83828   **  PRAGMA [database.]locking_mode = (normal|exclusive)
83829   */
83830   if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
83831     const char *zRet = "normal";
83832     int eMode = getLockingMode(zRight);
83833
83834     if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
83835       /* Simple "PRAGMA locking_mode;" statement. This is a query for
83836       ** the current default locking mode (which may be different to
83837       ** the locking-mode of the main database).
83838       */
83839       eMode = db->dfltLockMode;
83840     }else{
83841       Pager *pPager;
83842       if( pId2->n==0 ){
83843         /* This indicates that no database name was specified as part
83844         ** of the PRAGMA command. In this case the locking-mode must be
83845         ** set on all attached databases, as well as the main db file.
83846         **
83847         ** Also, the sqlite3.dfltLockMode variable is set so that
83848         ** any subsequently attached databases also use the specified
83849         ** locking mode.
83850         */
83851         int ii;
83852         assert(pDb==&db->aDb[0]);
83853         for(ii=2; ii<db->nDb; ii++){
83854           pPager = sqlite3BtreePager(db->aDb[ii].pBt);
83855           sqlite3PagerLockingMode(pPager, eMode);
83856         }
83857         db->dfltLockMode = (u8)eMode;
83858       }
83859       pPager = sqlite3BtreePager(pDb->pBt);
83860       eMode = sqlite3PagerLockingMode(pPager, eMode);
83861     }
83862
83863     assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
83864     if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
83865       zRet = "exclusive";
83866     }
83867     sqlite3VdbeSetNumCols(v, 1);
83868     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
83869     sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
83870     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
83871   }else
83872
83873   /*
83874   **  PRAGMA [database.]journal_mode
83875   **  PRAGMA [database.]journal_mode =
83876   **                      (delete|persist|off|truncate|memory|wal|off)
83877   */
83878   if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
83879     int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */
83880     int ii;           /* Loop counter */
83881
83882     /* Force the schema to be loaded on all databases.  This cases all
83883     ** database files to be opened and the journal_modes set. */
83884     if( sqlite3ReadSchema(pParse) ){
83885       goto pragma_out;
83886     }
83887
83888     sqlite3VdbeSetNumCols(v, 1);
83889     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
83890
83891     if( zRight==0 ){
83892       /* If there is no "=MODE" part of the pragma, do a query for the
83893       ** current mode */
83894       eMode = PAGER_JOURNALMODE_QUERY;
83895     }else{
83896       const char *zMode;
83897       int n = sqlite3Strlen30(zRight);
83898       for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
83899         if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
83900       }
83901       if( !zMode ){
83902         /* If the "=MODE" part does not match any known journal mode,
83903         ** then do a query */
83904         eMode = PAGER_JOURNALMODE_QUERY;
83905       }
83906     }
83907     if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
83908       /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
83909       iDb = 0;
83910       pId2->n = 1;
83911     }
83912     for(ii=db->nDb-1; ii>=0; ii--){
83913       if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
83914         sqlite3VdbeUsesBtree(v, ii);
83915         sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
83916       }
83917     }
83918     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
83919   }else
83920
83921   /*
83922   **  PRAGMA [database.]journal_size_limit
83923   **  PRAGMA [database.]journal_size_limit=N
83924   **
83925   ** Get or set the size limit on rollback journal files.
83926   */
83927   if( sqlite3StrICmp(zLeft,"journal_size_limit")==0 ){
83928     Pager *pPager = sqlite3BtreePager(pDb->pBt);
83929     i64 iLimit = -2;
83930     if( zRight ){
83931       sqlite3Atoi64(zRight, &iLimit);
83932       if( iLimit<-1 ) iLimit = -1;
83933     }
83934     iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
83935     returnSingleInt(pParse, "journal_size_limit", iLimit);
83936   }else
83937
83938 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
83939
83940   /*
83941   **  PRAGMA [database.]auto_vacuum
83942   **  PRAGMA [database.]auto_vacuum=N
83943   **
83944   ** Get or set the value of the database 'auto-vacuum' parameter.
83945   ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
83946   */
83947 #ifndef SQLITE_OMIT_AUTOVACUUM
83948   if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
83949     Btree *pBt = pDb->pBt;
83950     assert( pBt!=0 );
83951     if( sqlite3ReadSchema(pParse) ){
83952       goto pragma_out;
83953     }
83954     if( !zRight ){
83955       int auto_vacuum;
83956       if( ALWAYS(pBt) ){
83957          auto_vacuum = sqlite3BtreeGetAutoVacuum(pBt);
83958       }else{
83959          auto_vacuum = SQLITE_DEFAULT_AUTOVACUUM;
83960       }
83961       returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
83962     }else{
83963       int eAuto = getAutoVacuum(zRight);
83964       assert( eAuto>=0 && eAuto<=2 );
83965       db->nextAutovac = (u8)eAuto;
83966       if( ALWAYS(eAuto>=0) ){
83967         /* Call SetAutoVacuum() to set initialize the internal auto and
83968         ** incr-vacuum flags. This is required in case this connection
83969         ** creates the database file. It is important that it is created
83970         ** as an auto-vacuum capable db.
83971         */
83972         int rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
83973         if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
83974           /* When setting the auto_vacuum mode to either "full" or 
83975           ** "incremental", write the value of meta[6] in the database
83976           ** file. Before writing to meta[6], check that meta[3] indicates
83977           ** that this really is an auto-vacuum capable database.
83978           */
83979           static const VdbeOpList setMeta6[] = {
83980             { OP_Transaction,    0,         1,                 0},    /* 0 */
83981             { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
83982             { OP_If,             1,         0,                 0},    /* 2 */
83983             { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
83984             { OP_Integer,        0,         1,                 0},    /* 4 */
83985             { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 1},    /* 5 */
83986           };
83987           int iAddr;
83988           iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
83989           sqlite3VdbeChangeP1(v, iAddr, iDb);
83990           sqlite3VdbeChangeP1(v, iAddr+1, iDb);
83991           sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
83992           sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
83993           sqlite3VdbeChangeP1(v, iAddr+5, iDb);
83994           sqlite3VdbeUsesBtree(v, iDb);
83995         }
83996       }
83997     }
83998   }else
83999 #endif
84000
84001   /*
84002   **  PRAGMA [database.]incremental_vacuum(N)
84003   **
84004   ** Do N steps of incremental vacuuming on a database.
84005   */
84006 #ifndef SQLITE_OMIT_AUTOVACUUM
84007   if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
84008     int iLimit, addr;
84009     if( sqlite3ReadSchema(pParse) ){
84010       goto pragma_out;
84011     }
84012     if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
84013       iLimit = 0x7fffffff;
84014     }
84015     sqlite3BeginWriteOperation(pParse, 0, iDb);
84016     sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
84017     addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
84018     sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
84019     sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
84020     sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
84021     sqlite3VdbeJumpHere(v, addr);
84022   }else
84023 #endif
84024
84025 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
84026   /*
84027   **  PRAGMA [database.]cache_size
84028   **  PRAGMA [database.]cache_size=N
84029   **
84030   ** The first form reports the current local setting for the
84031   ** page cache size.  The local setting can be different from
84032   ** the persistent cache size value that is stored in the database
84033   ** file itself.  The value returned is the maximum number of
84034   ** pages in the page cache.  The second form sets the local
84035   ** page cache size value.  It does not change the persistent
84036   ** cache size stored on the disk so the cache size will revert
84037   ** to its default value when the database is closed and reopened.
84038   ** N should be a positive integer.
84039   */
84040   if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
84041     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
84042     if( !zRight ){
84043       returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
84044     }else{
84045       int size = atoi(zRight);
84046       if( size<0 ) size = -size;
84047       pDb->pSchema->cache_size = size;
84048       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
84049     }
84050   }else
84051
84052   /*
84053   **   PRAGMA temp_store
84054   **   PRAGMA temp_store = "default"|"memory"|"file"
84055   **
84056   ** Return or set the local value of the temp_store flag.  Changing
84057   ** the local value does not make changes to the disk file and the default
84058   ** value will be restored the next time the database is opened.
84059   **
84060   ** Note that it is possible for the library compile-time options to
84061   ** override this setting
84062   */
84063   if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
84064     if( !zRight ){
84065       returnSingleInt(pParse, "temp_store", db->temp_store);
84066     }else{
84067       changeTempStorage(pParse, zRight);
84068     }
84069   }else
84070
84071   /*
84072   **   PRAGMA temp_store_directory
84073   **   PRAGMA temp_store_directory = ""|"directory_name"
84074   **
84075   ** Return or set the local value of the temp_store_directory flag.  Changing
84076   ** the value sets a specific directory to be used for temporary files.
84077   ** Setting to a null string reverts to the default temporary directory search.
84078   ** If temporary directory is changed, then invalidateTempStorage.
84079   **
84080   */
84081   if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
84082     if( !zRight ){
84083       if( sqlite3_temp_directory ){
84084         sqlite3VdbeSetNumCols(v, 1);
84085         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
84086             "temp_store_directory", SQLITE_STATIC);
84087         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
84088         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
84089       }
84090     }else{
84091 #ifndef SQLITE_OMIT_WSD
84092       if( zRight[0] ){
84093         int rc;
84094         int res;
84095         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
84096         if( rc!=SQLITE_OK || res==0 ){
84097           sqlite3ErrorMsg(pParse, "not a writable directory");
84098           goto pragma_out;
84099         }
84100       }
84101       if( SQLITE_TEMP_STORE==0
84102        || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
84103        || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
84104       ){
84105         invalidateTempStorage(pParse);
84106       }
84107       sqlite3_free(sqlite3_temp_directory);
84108       if( zRight[0] ){
84109         sqlite3_temp_directory = sqlite3DbStrDup(0, zRight);
84110       }else{
84111         sqlite3_temp_directory = 0;
84112       }
84113 #endif /* SQLITE_OMIT_WSD */
84114     }
84115   }else
84116
84117 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
84118 #  if defined(__APPLE__)
84119 #    define SQLITE_ENABLE_LOCKING_STYLE 1
84120 #  else
84121 #    define SQLITE_ENABLE_LOCKING_STYLE 0
84122 #  endif
84123 #endif
84124 #if SQLITE_ENABLE_LOCKING_STYLE
84125   /*
84126    **   PRAGMA [database.]lock_proxy_file
84127    **   PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
84128    **
84129    ** Return or set the value of the lock_proxy_file flag.  Changing
84130    ** the value sets a specific file to be used for database access locks.
84131    **
84132    */
84133   if( sqlite3StrICmp(zLeft, "lock_proxy_file")==0 ){
84134     if( !zRight ){
84135       Pager *pPager = sqlite3BtreePager(pDb->pBt);
84136       char *proxy_file_path = NULL;
84137       sqlite3_file *pFile = sqlite3PagerFile(pPager);
84138       sqlite3OsFileControl(pFile, SQLITE_GET_LOCKPROXYFILE, 
84139                            &proxy_file_path);
84140       
84141       if( proxy_file_path ){
84142         sqlite3VdbeSetNumCols(v, 1);
84143         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
84144                               "lock_proxy_file", SQLITE_STATIC);
84145         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
84146         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
84147       }
84148     }else{
84149       Pager *pPager = sqlite3BtreePager(pDb->pBt);
84150       sqlite3_file *pFile = sqlite3PagerFile(pPager);
84151       int res;
84152       if( zRight[0] ){
84153         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
84154                                      zRight);
84155       } else {
84156         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
84157                                      NULL);
84158       }
84159       if( res!=SQLITE_OK ){
84160         sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
84161         goto pragma_out;
84162       }
84163     }
84164   }else
84165 #endif /* SQLITE_ENABLE_LOCKING_STYLE */      
84166     
84167   /*
84168   **   PRAGMA [database.]synchronous
84169   **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
84170   **
84171   ** Return or set the local value of the synchronous flag.  Changing
84172   ** the local value does not make changes to the disk file and the
84173   ** default value will be restored the next time the database is
84174   ** opened.
84175   */
84176   if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
84177     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
84178     if( !zRight ){
84179       returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
84180     }else{
84181       if( !db->autoCommit ){
84182         sqlite3ErrorMsg(pParse, 
84183             "Safety level may not be changed inside a transaction");
84184       }else{
84185         pDb->safety_level = getSafetyLevel(zRight)+1;
84186       }
84187     }
84188   }else
84189 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
84190
84191 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
84192   if( flagPragma(pParse, zLeft, zRight) ){
84193     /* The flagPragma() subroutine also generates any necessary code
84194     ** there is nothing more to do here */
84195   }else
84196 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
84197
84198 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
84199   /*
84200   **   PRAGMA table_info(<table>)
84201   **
84202   ** Return a single row for each column of the named table. The columns of
84203   ** the returned data set are:
84204   **
84205   ** cid:        Column id (numbered from left to right, starting at 0)
84206   ** name:       Column name
84207   ** type:       Column declaration type.
84208   ** notnull:    True if 'NOT NULL' is part of column declaration
84209   ** dflt_value: The default value for the column, if any.
84210   */
84211   if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
84212     Table *pTab;
84213     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
84214     pTab = sqlite3FindTable(db, zRight, zDb);
84215     if( pTab ){
84216       int i;
84217       int nHidden = 0;
84218       Column *pCol;
84219       sqlite3VdbeSetNumCols(v, 6);
84220       pParse->nMem = 6;
84221       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
84222       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
84223       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
84224       sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
84225       sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
84226       sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
84227       sqlite3ViewGetColumnNames(pParse, pTab);
84228       for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
84229         if( IsHiddenColumn(pCol) ){
84230           nHidden++;
84231           continue;
84232         }
84233         sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
84234         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
84235         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
84236            pCol->zType ? pCol->zType : "", 0);
84237         sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
84238         if( pCol->zDflt ){
84239           sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
84240         }else{
84241           sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
84242         }
84243         sqlite3VdbeAddOp2(v, OP_Integer, pCol->isPrimKey, 6);
84244         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
84245       }
84246     }
84247   }else
84248
84249   if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
84250     Index *pIdx;
84251     Table *pTab;
84252     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
84253     pIdx = sqlite3FindIndex(db, zRight, zDb);
84254     if( pIdx ){
84255       int i;
84256       pTab = pIdx->pTable;
84257       sqlite3VdbeSetNumCols(v, 3);
84258       pParse->nMem = 3;
84259       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
84260       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
84261       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
84262       for(i=0; i<pIdx->nColumn; i++){
84263         int cnum = pIdx->aiColumn[i];
84264         sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
84265         sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
84266         assert( pTab->nCol>cnum );
84267         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
84268         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
84269       }
84270     }
84271   }else
84272
84273   if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
84274     Index *pIdx;
84275     Table *pTab;
84276     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
84277     pTab = sqlite3FindTable(db, zRight, zDb);
84278     if( pTab ){
84279       v = sqlite3GetVdbe(pParse);
84280       pIdx = pTab->pIndex;
84281       if( pIdx ){
84282         int i = 0; 
84283         sqlite3VdbeSetNumCols(v, 3);
84284         pParse->nMem = 3;
84285         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
84286         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
84287         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
84288         while(pIdx){
84289           sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
84290           sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
84291           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
84292           sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
84293           ++i;
84294           pIdx = pIdx->pNext;
84295         }
84296       }
84297     }
84298   }else
84299
84300   if( sqlite3StrICmp(zLeft, "database_list")==0 ){
84301     int i;
84302     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
84303     sqlite3VdbeSetNumCols(v, 3);
84304     pParse->nMem = 3;
84305     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
84306     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
84307     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
84308     for(i=0; i<db->nDb; i++){
84309       if( db->aDb[i].pBt==0 ) continue;
84310       assert( db->aDb[i].zName!=0 );
84311       sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
84312       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
84313       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
84314            sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
84315       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
84316     }
84317   }else
84318
84319   if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
84320     int i = 0;
84321     HashElem *p;
84322     sqlite3VdbeSetNumCols(v, 2);
84323     pParse->nMem = 2;
84324     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
84325     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
84326     for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
84327       CollSeq *pColl = (CollSeq *)sqliteHashData(p);
84328       sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
84329       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
84330       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
84331     }
84332   }else
84333 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
84334
84335 #ifndef SQLITE_OMIT_FOREIGN_KEY
84336   if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
84337     FKey *pFK;
84338     Table *pTab;
84339     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
84340     pTab = sqlite3FindTable(db, zRight, zDb);
84341     if( pTab ){
84342       v = sqlite3GetVdbe(pParse);
84343       pFK = pTab->pFKey;
84344       if( pFK ){
84345         int i = 0; 
84346         sqlite3VdbeSetNumCols(v, 8);
84347         pParse->nMem = 8;
84348         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
84349         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
84350         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
84351         sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
84352         sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
84353         sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
84354         sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
84355         sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
84356         while(pFK){
84357           int j;
84358           for(j=0; j<pFK->nCol; j++){
84359             char *zCol = pFK->aCol[j].zCol;
84360             char *zOnDelete = (char *)actionName(pFK->aAction[0]);
84361             char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
84362             sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
84363             sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
84364             sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
84365             sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
84366                               pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
84367             sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
84368             sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
84369             sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
84370             sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
84371             sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
84372           }
84373           ++i;
84374           pFK = pFK->pNextFrom;
84375         }
84376       }
84377     }
84378   }else
84379 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
84380
84381 #ifndef NDEBUG
84382   if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
84383     if( zRight ){
84384       if( getBoolean(zRight) ){
84385         sqlite3ParserTrace(stderr, "parser: ");
84386       }else{
84387         sqlite3ParserTrace(0, 0);
84388       }
84389     }
84390   }else
84391 #endif
84392
84393   /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
84394   ** used will be case sensitive or not depending on the RHS.
84395   */
84396   if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
84397     if( zRight ){
84398       sqlite3RegisterLikeFunctions(db, getBoolean(zRight));
84399     }
84400   }else
84401
84402 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
84403 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
84404 #endif
84405
84406 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
84407   /* Pragma "quick_check" is an experimental reduced version of 
84408   ** integrity_check designed to detect most database corruption
84409   ** without most of the overhead of a full integrity-check.
84410   */
84411   if( sqlite3StrICmp(zLeft, "integrity_check")==0
84412    || sqlite3StrICmp(zLeft, "quick_check")==0 
84413   ){
84414     int i, j, addr, mxErr;
84415
84416     /* Code that appears at the end of the integrity check.  If no error
84417     ** messages have been generated, output OK.  Otherwise output the
84418     ** error message
84419     */
84420     static const VdbeOpList endCode[] = {
84421       { OP_AddImm,      1, 0,        0},    /* 0 */
84422       { OP_IfNeg,       1, 0,        0},    /* 1 */
84423       { OP_String8,     0, 3,        0},    /* 2 */
84424       { OP_ResultRow,   3, 1,        0},
84425     };
84426
84427     int isQuick = (zLeft[0]=='q');
84428
84429     /* Initialize the VDBE program */
84430     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
84431     pParse->nMem = 6;
84432     sqlite3VdbeSetNumCols(v, 1);
84433     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
84434
84435     /* Set the maximum error count */
84436     mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
84437     if( zRight ){
84438       mxErr = atoi(zRight);
84439       if( mxErr<=0 ){
84440         mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
84441       }
84442     }
84443     sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
84444
84445     /* Do an integrity check on each database file */
84446     for(i=0; i<db->nDb; i++){
84447       HashElem *x;
84448       Hash *pTbls;
84449       int cnt = 0;
84450
84451       if( OMIT_TEMPDB && i==1 ) continue;
84452
84453       sqlite3CodeVerifySchema(pParse, i);
84454       addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
84455       sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
84456       sqlite3VdbeJumpHere(v, addr);
84457
84458       /* Do an integrity check of the B-Tree
84459       **
84460       ** Begin by filling registers 2, 3, ... with the root pages numbers
84461       ** for all tables and indices in the database.
84462       */
84463       pTbls = &db->aDb[i].pSchema->tblHash;
84464       for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
84465         Table *pTab = sqliteHashData(x);
84466         Index *pIdx;
84467         sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
84468         cnt++;
84469         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
84470           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
84471           cnt++;
84472         }
84473       }
84474
84475       /* Make sure sufficient number of registers have been allocated */
84476       if( pParse->nMem < cnt+4 ){
84477         pParse->nMem = cnt+4;
84478       }
84479
84480       /* Do the b-tree integrity checks */
84481       sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
84482       sqlite3VdbeChangeP5(v, (u8)i);
84483       addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
84484       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
84485          sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
84486          P4_DYNAMIC);
84487       sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
84488       sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
84489       sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
84490       sqlite3VdbeJumpHere(v, addr);
84491
84492       /* Make sure all the indices are constructed correctly.
84493       */
84494       for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
84495         Table *pTab = sqliteHashData(x);
84496         Index *pIdx;
84497         int loopTop;
84498
84499         if( pTab->pIndex==0 ) continue;
84500         addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
84501         sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
84502         sqlite3VdbeJumpHere(v, addr);
84503         sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
84504         sqlite3VdbeAddOp2(v, OP_Integer, 0, 2);  /* reg(2) will count entries */
84505         loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0);
84506         sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1);   /* increment entry count */
84507         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
84508           int jmp2;
84509           int r1;
84510           static const VdbeOpList idxErr[] = {
84511             { OP_AddImm,      1, -1,  0},
84512             { OP_String8,     0,  3,  0},    /* 1 */
84513             { OP_Rowid,       1,  4,  0},
84514             { OP_String8,     0,  5,  0},    /* 3 */
84515             { OP_String8,     0,  6,  0},    /* 4 */
84516             { OP_Concat,      4,  3,  3},
84517             { OP_Concat,      5,  3,  3},
84518             { OP_Concat,      6,  3,  3},
84519             { OP_ResultRow,   3,  1,  0},
84520             { OP_IfPos,       1,  0,  0},    /* 9 */
84521             { OP_Halt,        0,  0,  0},
84522           };
84523           r1 = sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 0);
84524           jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1);
84525           addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
84526           sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
84527           sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
84528           sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_STATIC);
84529           sqlite3VdbeJumpHere(v, addr+9);
84530           sqlite3VdbeJumpHere(v, jmp2);
84531         }
84532         sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
84533         sqlite3VdbeJumpHere(v, loopTop);
84534         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
84535           static const VdbeOpList cntIdx[] = {
84536              { OP_Integer,      0,  3,  0},
84537              { OP_Rewind,       0,  0,  0},  /* 1 */
84538              { OP_AddImm,       3,  1,  0},
84539              { OP_Next,         0,  0,  0},  /* 3 */
84540              { OP_Eq,           2,  0,  3},  /* 4 */
84541              { OP_AddImm,       1, -1,  0},
84542              { OP_String8,      0,  2,  0},  /* 6 */
84543              { OP_String8,      0,  3,  0},  /* 7 */
84544              { OP_Concat,       3,  2,  2},
84545              { OP_ResultRow,    2,  1,  0},
84546           };
84547           addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
84548           sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
84549           sqlite3VdbeJumpHere(v, addr);
84550           addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
84551           sqlite3VdbeChangeP1(v, addr+1, j+2);
84552           sqlite3VdbeChangeP2(v, addr+1, addr+4);
84553           sqlite3VdbeChangeP1(v, addr+3, j+2);
84554           sqlite3VdbeChangeP2(v, addr+3, addr+2);
84555           sqlite3VdbeJumpHere(v, addr+4);
84556           sqlite3VdbeChangeP4(v, addr+6, 
84557                      "wrong # of entries in index ", P4_STATIC);
84558           sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_STATIC);
84559         }
84560       } 
84561     }
84562     addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
84563     sqlite3VdbeChangeP2(v, addr, -mxErr);
84564     sqlite3VdbeJumpHere(v, addr+1);
84565     sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
84566   }else
84567 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
84568
84569 #ifndef SQLITE_OMIT_UTF16
84570   /*
84571   **   PRAGMA encoding
84572   **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
84573   **
84574   ** In its first form, this pragma returns the encoding of the main
84575   ** database. If the database is not initialized, it is initialized now.
84576   **
84577   ** The second form of this pragma is a no-op if the main database file
84578   ** has not already been initialized. In this case it sets the default
84579   ** encoding that will be used for the main database file if a new file
84580   ** is created. If an existing main database file is opened, then the
84581   ** default text encoding for the existing database is used.
84582   ** 
84583   ** In all cases new databases created using the ATTACH command are
84584   ** created to use the same default text encoding as the main database. If
84585   ** the main database has not been initialized and/or created when ATTACH
84586   ** is executed, this is done before the ATTACH operation.
84587   **
84588   ** In the second form this pragma sets the text encoding to be used in
84589   ** new database files created using this database handle. It is only
84590   ** useful if invoked immediately after the main database i
84591   */
84592   if( sqlite3StrICmp(zLeft, "encoding")==0 ){
84593     static const struct EncName {
84594       char *zName;
84595       u8 enc;
84596     } encnames[] = {
84597       { "UTF8",     SQLITE_UTF8        },
84598       { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
84599       { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
84600       { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
84601       { "UTF16le",  SQLITE_UTF16LE     },
84602       { "UTF16be",  SQLITE_UTF16BE     },
84603       { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
84604       { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
84605       { 0, 0 }
84606     };
84607     const struct EncName *pEnc;
84608     if( !zRight ){    /* "PRAGMA encoding" */
84609       if( sqlite3ReadSchema(pParse) ) goto pragma_out;
84610       sqlite3VdbeSetNumCols(v, 1);
84611       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
84612       sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
84613       assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
84614       assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
84615       assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
84616       sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
84617       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
84618     }else{                        /* "PRAGMA encoding = XXX" */
84619       /* Only change the value of sqlite.enc if the database handle is not
84620       ** initialized. If the main database exists, the new sqlite.enc value
84621       ** will be overwritten when the schema is next loaded. If it does not
84622       ** already exists, it will be created to use the new encoding value.
84623       */
84624       if( 
84625         !(DbHasProperty(db, 0, DB_SchemaLoaded)) || 
84626         DbHasProperty(db, 0, DB_Empty) 
84627       ){
84628         for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
84629           if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
84630             ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
84631             break;
84632           }
84633         }
84634         if( !pEnc->zName ){
84635           sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
84636         }
84637       }
84638     }
84639   }else
84640 #endif /* SQLITE_OMIT_UTF16 */
84641
84642 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
84643   /*
84644   **   PRAGMA [database.]schema_version
84645   **   PRAGMA [database.]schema_version = <integer>
84646   **
84647   **   PRAGMA [database.]user_version
84648   **   PRAGMA [database.]user_version = <integer>
84649   **
84650   ** The pragma's schema_version and user_version are used to set or get
84651   ** the value of the schema-version and user-version, respectively. Both
84652   ** the schema-version and the user-version are 32-bit signed integers
84653   ** stored in the database header.
84654   **
84655   ** The schema-cookie is usually only manipulated internally by SQLite. It
84656   ** is incremented by SQLite whenever the database schema is modified (by
84657   ** creating or dropping a table or index). The schema version is used by
84658   ** SQLite each time a query is executed to ensure that the internal cache
84659   ** of the schema used when compiling the SQL query matches the schema of
84660   ** the database against which the compiled query is actually executed.
84661   ** Subverting this mechanism by using "PRAGMA schema_version" to modify
84662   ** the schema-version is potentially dangerous and may lead to program
84663   ** crashes or database corruption. Use with caution!
84664   **
84665   ** The user-version is not used internally by SQLite. It may be used by
84666   ** applications for any purpose.
84667   */
84668   if( sqlite3StrICmp(zLeft, "schema_version")==0 
84669    || sqlite3StrICmp(zLeft, "user_version")==0 
84670    || sqlite3StrICmp(zLeft, "freelist_count")==0 
84671   ){
84672     int iCookie;   /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
84673     sqlite3VdbeUsesBtree(v, iDb);
84674     switch( zLeft[0] ){
84675       case 'f': case 'F':
84676         iCookie = BTREE_FREE_PAGE_COUNT;
84677         break;
84678       case 's': case 'S':
84679         iCookie = BTREE_SCHEMA_VERSION;
84680         break;
84681       default:
84682         iCookie = BTREE_USER_VERSION;
84683         break;
84684     }
84685
84686     if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
84687       /* Write the specified cookie value */
84688       static const VdbeOpList setCookie[] = {
84689         { OP_Transaction,    0,  1,  0},    /* 0 */
84690         { OP_Integer,        0,  1,  0},    /* 1 */
84691         { OP_SetCookie,      0,  0,  1},    /* 2 */
84692       };
84693       int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
84694       sqlite3VdbeChangeP1(v, addr, iDb);
84695       sqlite3VdbeChangeP1(v, addr+1, atoi(zRight));
84696       sqlite3VdbeChangeP1(v, addr+2, iDb);
84697       sqlite3VdbeChangeP2(v, addr+2, iCookie);
84698     }else{
84699       /* Read the specified cookie value */
84700       static const VdbeOpList readCookie[] = {
84701         { OP_Transaction,     0,  0,  0},    /* 0 */
84702         { OP_ReadCookie,      0,  1,  0},    /* 1 */
84703         { OP_ResultRow,       1,  1,  0}
84704       };
84705       int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
84706       sqlite3VdbeChangeP1(v, addr, iDb);
84707       sqlite3VdbeChangeP1(v, addr+1, iDb);
84708       sqlite3VdbeChangeP3(v, addr+1, iCookie);
84709       sqlite3VdbeSetNumCols(v, 1);
84710       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
84711     }
84712   }else
84713 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
84714
84715 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
84716   /*
84717   **   PRAGMA compile_options
84718   **
84719   ** Return the names of all compile-time options used in this build,
84720   ** one option per row.
84721   */
84722   if( sqlite3StrICmp(zLeft, "compile_options")==0 ){
84723     int i = 0;
84724     const char *zOpt;
84725     sqlite3VdbeSetNumCols(v, 1);
84726     pParse->nMem = 1;
84727     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
84728     while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
84729       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
84730       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
84731     }
84732   }else
84733 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
84734
84735 #ifndef SQLITE_OMIT_WAL
84736   /*
84737   **   PRAGMA [database.]wal_checkpoint
84738   **
84739   ** Checkpoint the database.
84740   */
84741   if( sqlite3StrICmp(zLeft, "wal_checkpoint")==0 ){
84742     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
84743     sqlite3VdbeAddOp3(v, OP_Checkpoint, pId2->z?iDb:SQLITE_MAX_ATTACHED, 0, 0);
84744   }else
84745
84746   /*
84747   **   PRAGMA wal_autocheckpoint
84748   **   PRAGMA wal_autocheckpoint = N
84749   **
84750   ** Configure a database connection to automatically checkpoint a database
84751   ** after accumulating N frames in the log. Or query for the current value
84752   ** of N.
84753   */
84754   if( sqlite3StrICmp(zLeft, "wal_autocheckpoint")==0 ){
84755     if( zRight ){
84756       int nAuto = atoi(zRight);
84757       sqlite3_wal_autocheckpoint(db, nAuto);
84758     }
84759     returnSingleInt(pParse, "wal_autocheckpoint", 
84760        db->xWalCallback==sqlite3WalDefaultHook ? 
84761            SQLITE_PTR_TO_INT(db->pWalArg) : 0);
84762   }else
84763 #endif
84764
84765 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
84766   /*
84767   ** Report the current state of file logs for all databases
84768   */
84769   if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
84770     static const char *const azLockName[] = {
84771       "unlocked", "shared", "reserved", "pending", "exclusive"
84772     };
84773     int i;
84774     sqlite3VdbeSetNumCols(v, 2);
84775     pParse->nMem = 2;
84776     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
84777     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
84778     for(i=0; i<db->nDb; i++){
84779       Btree *pBt;
84780       Pager *pPager;
84781       const char *zState = "unknown";
84782       int j;
84783       if( db->aDb[i].zName==0 ) continue;
84784       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
84785       pBt = db->aDb[i].pBt;
84786       if( pBt==0 || (pPager = sqlite3BtreePager(pBt))==0 ){
84787         zState = "closed";
84788       }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0, 
84789                                      SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
84790          zState = azLockName[j];
84791       }
84792       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
84793       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
84794     }
84795
84796   }else
84797 #endif
84798
84799 #ifdef SQLITE_HAS_CODEC
84800   if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){
84801     sqlite3_key(db, zRight, sqlite3Strlen30(zRight));
84802   }else
84803   if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){
84804     sqlite3_rekey(db, zRight, sqlite3Strlen30(zRight));
84805   }else
84806   if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 ||
84807                  sqlite3StrICmp(zLeft, "hexrekey")==0) ){
84808     int i, h1, h2;
84809     char zKey[40];
84810     for(i=0; (h1 = zRight[i])!=0 && (h2 = zRight[i+1])!=0; i+=2){
84811       h1 += 9*(1&(h1>>6));
84812       h2 += 9*(1&(h2>>6));
84813       zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
84814     }
84815     if( (zLeft[3] & 0xf)==0xb ){
84816       sqlite3_key(db, zKey, i/2);
84817     }else{
84818       sqlite3_rekey(db, zKey, i/2);
84819     }
84820   }else
84821 #endif
84822 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
84823   if( sqlite3StrICmp(zLeft, "activate_extensions")==0 ){
84824 #ifdef SQLITE_HAS_CODEC
84825     if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
84826       sqlite3_activate_see(&zRight[4]);
84827     }
84828 #endif
84829 #ifdef SQLITE_ENABLE_CEROD
84830     if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
84831       sqlite3_activate_cerod(&zRight[6]);
84832     }
84833 #endif
84834   }else
84835 #endif
84836
84837  
84838   {/* Empty ELSE clause */}
84839
84840   /*
84841   ** Reset the safety level, in case the fullfsync flag or synchronous
84842   ** setting changed.
84843   */
84844 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
84845   if( db->autoCommit ){
84846     sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
84847                (db->flags&SQLITE_FullFSync)!=0);
84848   }
84849 #endif
84850 pragma_out:
84851   sqlite3DbFree(db, zLeft);
84852   sqlite3DbFree(db, zRight);
84853 }
84854
84855 #endif /* SQLITE_OMIT_PRAGMA */
84856
84857 /************** End of pragma.c **********************************************/
84858 /************** Begin file prepare.c *****************************************/
84859 /*
84860 ** 2005 May 25
84861 **
84862 ** The author disclaims copyright to this source code.  In place of
84863 ** a legal notice, here is a blessing:
84864 **
84865 **    May you do good and not evil.
84866 **    May you find forgiveness for yourself and forgive others.
84867 **    May you share freely, never taking more than you give.
84868 **
84869 *************************************************************************
84870 ** This file contains the implementation of the sqlite3_prepare()
84871 ** interface, and routines that contribute to loading the database schema
84872 ** from disk.
84873 */
84874
84875 /*
84876 ** Fill the InitData structure with an error message that indicates
84877 ** that the database is corrupt.
84878 */
84879 static void corruptSchema(
84880   InitData *pData,     /* Initialization context */
84881   const char *zObj,    /* Object being parsed at the point of error */
84882   const char *zExtra   /* Error information */
84883 ){
84884   sqlite3 *db = pData->db;
84885   if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
84886     if( zObj==0 ) zObj = "?";
84887     sqlite3SetString(pData->pzErrMsg, db,
84888       "malformed database schema (%s)", zObj);
84889     if( zExtra ){
84890       *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg, 
84891                                  "%s - %s", *pData->pzErrMsg, zExtra);
84892     }
84893   }
84894   pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT;
84895 }
84896
84897 /*
84898 ** This is the callback routine for the code that initializes the
84899 ** database.  See sqlite3Init() below for additional information.
84900 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
84901 **
84902 ** Each callback contains the following information:
84903 **
84904 **     argv[0] = name of thing being created
84905 **     argv[1] = root page number for table or index. 0 for trigger or view.
84906 **     argv[2] = SQL text for the CREATE statement.
84907 **
84908 */
84909 SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
84910   InitData *pData = (InitData*)pInit;
84911   sqlite3 *db = pData->db;
84912   int iDb = pData->iDb;
84913
84914   assert( argc==3 );
84915   UNUSED_PARAMETER2(NotUsed, argc);
84916   assert( sqlite3_mutex_held(db->mutex) );
84917   DbClearProperty(db, iDb, DB_Empty);
84918   if( db->mallocFailed ){
84919     corruptSchema(pData, argv[0], 0);
84920     return 1;
84921   }
84922
84923   assert( iDb>=0 && iDb<db->nDb );
84924   if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
84925   if( argv[1]==0 ){
84926     corruptSchema(pData, argv[0], 0);
84927   }else if( argv[2] && argv[2][0] ){
84928     /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
84929     ** But because db->init.busy is set to 1, no VDBE code is generated
84930     ** or executed.  All the parser does is build the internal data
84931     ** structures that describe the table, index, or view.
84932     */
84933     int rc;
84934     sqlite3_stmt *pStmt;
84935     TESTONLY(int rcp);            /* Return code from sqlite3_prepare() */
84936
84937     assert( db->init.busy );
84938     db->init.iDb = iDb;
84939     db->init.newTnum = atoi(argv[1]);
84940     db->init.orphanTrigger = 0;
84941     TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
84942     rc = db->errCode;
84943     assert( (rc&0xFF)==(rcp&0xFF) );
84944     db->init.iDb = 0;
84945     if( SQLITE_OK!=rc ){
84946       if( db->init.orphanTrigger ){
84947         assert( iDb==1 );
84948       }else{
84949         pData->rc = rc;
84950         if( rc==SQLITE_NOMEM ){
84951           db->mallocFailed = 1;
84952         }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
84953           corruptSchema(pData, argv[0], sqlite3_errmsg(db));
84954         }
84955       }
84956     }
84957     sqlite3_finalize(pStmt);
84958   }else if( argv[0]==0 ){
84959     corruptSchema(pData, 0, 0);
84960   }else{
84961     /* If the SQL column is blank it means this is an index that
84962     ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
84963     ** constraint for a CREATE TABLE.  The index should have already
84964     ** been created when we processed the CREATE TABLE.  All we have
84965     ** to do here is record the root page number for that index.
84966     */
84967     Index *pIndex;
84968     pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
84969     if( pIndex==0 ){
84970       /* This can occur if there exists an index on a TEMP table which
84971       ** has the same name as another index on a permanent index.  Since
84972       ** the permanent table is hidden by the TEMP table, we can also
84973       ** safely ignore the index on the permanent table.
84974       */
84975       /* Do Nothing */;
84976     }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
84977       corruptSchema(pData, argv[0], "invalid rootpage");
84978     }
84979   }
84980   return 0;
84981 }
84982
84983 /*
84984 ** Attempt to read the database schema and initialize internal
84985 ** data structures for a single database file.  The index of the
84986 ** database file is given by iDb.  iDb==0 is used for the main
84987 ** database.  iDb==1 should never be used.  iDb>=2 is used for
84988 ** auxiliary databases.  Return one of the SQLITE_ error codes to
84989 ** indicate success or failure.
84990 */
84991 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
84992   int rc;
84993   int i;
84994   int size;
84995   Table *pTab;
84996   Db *pDb;
84997   char const *azArg[4];
84998   int meta[5];
84999   InitData initData;
85000   char const *zMasterSchema;
85001   char const *zMasterName = SCHEMA_TABLE(iDb);
85002   int openedTransaction = 0;
85003
85004   /*
85005   ** The master database table has a structure like this
85006   */
85007   static const char master_schema[] = 
85008      "CREATE TABLE sqlite_master(\n"
85009      "  type text,\n"
85010      "  name text,\n"
85011      "  tbl_name text,\n"
85012      "  rootpage integer,\n"
85013      "  sql text\n"
85014      ")"
85015   ;
85016 #ifndef SQLITE_OMIT_TEMPDB
85017   static const char temp_master_schema[] = 
85018      "CREATE TEMP TABLE sqlite_temp_master(\n"
85019      "  type text,\n"
85020      "  name text,\n"
85021      "  tbl_name text,\n"
85022      "  rootpage integer,\n"
85023      "  sql text\n"
85024      ")"
85025   ;
85026 #else
85027   #define temp_master_schema 0
85028 #endif
85029
85030   assert( iDb>=0 && iDb<db->nDb );
85031   assert( db->aDb[iDb].pSchema );
85032   assert( sqlite3_mutex_held(db->mutex) );
85033   assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
85034
85035   /* zMasterSchema and zInitScript are set to point at the master schema
85036   ** and initialisation script appropriate for the database being
85037   ** initialised. zMasterName is the name of the master table.
85038   */
85039   if( !OMIT_TEMPDB && iDb==1 ){
85040     zMasterSchema = temp_master_schema;
85041   }else{
85042     zMasterSchema = master_schema;
85043   }
85044   zMasterName = SCHEMA_TABLE(iDb);
85045
85046   /* Construct the schema tables.  */
85047   azArg[0] = zMasterName;
85048   azArg[1] = "1";
85049   azArg[2] = zMasterSchema;
85050   azArg[3] = 0;
85051   initData.db = db;
85052   initData.iDb = iDb;
85053   initData.rc = SQLITE_OK;
85054   initData.pzErrMsg = pzErrMsg;
85055   sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
85056   if( initData.rc ){
85057     rc = initData.rc;
85058     goto error_out;
85059   }
85060   pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
85061   if( ALWAYS(pTab) ){
85062     pTab->tabFlags |= TF_Readonly;
85063   }
85064
85065   /* Create a cursor to hold the database open
85066   */
85067   pDb = &db->aDb[iDb];
85068   if( pDb->pBt==0 ){
85069     if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
85070       DbSetProperty(db, 1, DB_SchemaLoaded);
85071     }
85072     return SQLITE_OK;
85073   }
85074
85075   /* If there is not already a read-only (or read-write) transaction opened
85076   ** on the b-tree database, open one now. If a transaction is opened, it 
85077   ** will be closed before this function returns.  */
85078   sqlite3BtreeEnter(pDb->pBt);
85079   if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
85080     rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
85081     if( rc!=SQLITE_OK ){
85082       sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
85083       goto initone_error_out;
85084     }
85085     openedTransaction = 1;
85086   }
85087
85088   /* Get the database meta information.
85089   **
85090   ** Meta values are as follows:
85091   **    meta[0]   Schema cookie.  Changes with each schema change.
85092   **    meta[1]   File format of schema layer.
85093   **    meta[2]   Size of the page cache.
85094   **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
85095   **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
85096   **    meta[5]   User version
85097   **    meta[6]   Incremental vacuum mode
85098   **    meta[7]   unused
85099   **    meta[8]   unused
85100   **    meta[9]   unused
85101   **
85102   ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
85103   ** the possible values of meta[4].
85104   */
85105   for(i=0; i<ArraySize(meta); i++){
85106     sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
85107   }
85108   pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
85109
85110   /* If opening a non-empty database, check the text encoding. For the
85111   ** main database, set sqlite3.enc to the encoding of the main database.
85112   ** For an attached db, it is an error if the encoding is not the same
85113   ** as sqlite3.enc.
85114   */
85115   if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
85116     if( iDb==0 ){
85117       u8 encoding;
85118       /* If opening the main database, set ENC(db). */
85119       encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
85120       if( encoding==0 ) encoding = SQLITE_UTF8;
85121       ENC(db) = encoding;
85122       db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
85123     }else{
85124       /* If opening an attached database, the encoding much match ENC(db) */
85125       if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
85126         sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
85127             " text encoding as main database");
85128         rc = SQLITE_ERROR;
85129         goto initone_error_out;
85130       }
85131     }
85132   }else{
85133     DbSetProperty(db, iDb, DB_Empty);
85134   }
85135   pDb->pSchema->enc = ENC(db);
85136
85137   if( pDb->pSchema->cache_size==0 ){
85138     size = meta[BTREE_DEFAULT_CACHE_SIZE-1];
85139     if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
85140     if( size<0 ) size = -size;
85141     pDb->pSchema->cache_size = size;
85142     sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
85143   }
85144
85145   /*
85146   ** file_format==1    Version 3.0.0.
85147   ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
85148   ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
85149   ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
85150   */
85151   pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
85152   if( pDb->pSchema->file_format==0 ){
85153     pDb->pSchema->file_format = 1;
85154   }
85155   if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
85156     sqlite3SetString(pzErrMsg, db, "unsupported file format");
85157     rc = SQLITE_ERROR;
85158     goto initone_error_out;
85159   }
85160
85161   /* Ticket #2804:  When we open a database in the newer file format,
85162   ** clear the legacy_file_format pragma flag so that a VACUUM will
85163   ** not downgrade the database and thus invalidate any descending
85164   ** indices that the user might have created.
85165   */
85166   if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
85167     db->flags &= ~SQLITE_LegacyFileFmt;
85168   }
85169
85170   /* Read the schema information out of the schema tables
85171   */
85172   assert( db->init.busy );
85173   {
85174     char *zSql;
85175     zSql = sqlite3MPrintf(db, 
85176         "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
85177         db->aDb[iDb].zName, zMasterName);
85178 #ifndef SQLITE_OMIT_AUTHORIZATION
85179     {
85180       int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
85181       xAuth = db->xAuth;
85182       db->xAuth = 0;
85183 #endif
85184       rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
85185 #ifndef SQLITE_OMIT_AUTHORIZATION
85186       db->xAuth = xAuth;
85187     }
85188 #endif
85189     if( rc==SQLITE_OK ) rc = initData.rc;
85190     sqlite3DbFree(db, zSql);
85191 #ifndef SQLITE_OMIT_ANALYZE
85192     if( rc==SQLITE_OK ){
85193       sqlite3AnalysisLoad(db, iDb);
85194     }
85195 #endif
85196   }
85197   if( db->mallocFailed ){
85198     rc = SQLITE_NOMEM;
85199     sqlite3ResetInternalSchema(db, 0);
85200   }
85201   if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
85202     /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
85203     ** the schema loaded, even if errors occurred. In this situation the 
85204     ** current sqlite3_prepare() operation will fail, but the following one
85205     ** will attempt to compile the supplied statement against whatever subset
85206     ** of the schema was loaded before the error occurred. The primary
85207     ** purpose of this is to allow access to the sqlite_master table
85208     ** even when its contents have been corrupted.
85209     */
85210     DbSetProperty(db, iDb, DB_SchemaLoaded);
85211     rc = SQLITE_OK;
85212   }
85213
85214   /* Jump here for an error that occurs after successfully allocating
85215   ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
85216   ** before that point, jump to error_out.
85217   */
85218 initone_error_out:
85219   if( openedTransaction ){
85220     sqlite3BtreeCommit(pDb->pBt);
85221   }
85222   sqlite3BtreeLeave(pDb->pBt);
85223
85224 error_out:
85225   if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
85226     db->mallocFailed = 1;
85227   }
85228   return rc;
85229 }
85230
85231 /*
85232 ** Initialize all database files - the main database file, the file
85233 ** used to store temporary tables, and any additional database files
85234 ** created using ATTACH statements.  Return a success code.  If an
85235 ** error occurs, write an error message into *pzErrMsg.
85236 **
85237 ** After a database is initialized, the DB_SchemaLoaded bit is set
85238 ** bit is set in the flags field of the Db structure. If the database
85239 ** file was of zero-length, then the DB_Empty flag is also set.
85240 */
85241 SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
85242   int i, rc;
85243   int commit_internal = !(db->flags&SQLITE_InternChanges);
85244   
85245   assert( sqlite3_mutex_held(db->mutex) );
85246   rc = SQLITE_OK;
85247   db->init.busy = 1;
85248   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
85249     if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
85250     rc = sqlite3InitOne(db, i, pzErrMsg);
85251     if( rc ){
85252       sqlite3ResetInternalSchema(db, i);
85253     }
85254   }
85255
85256   /* Once all the other databases have been initialised, load the schema
85257   ** for the TEMP database. This is loaded last, as the TEMP database
85258   ** schema may contain references to objects in other databases.
85259   */
85260 #ifndef SQLITE_OMIT_TEMPDB
85261   if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
85262                     && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
85263     rc = sqlite3InitOne(db, 1, pzErrMsg);
85264     if( rc ){
85265       sqlite3ResetInternalSchema(db, 1);
85266     }
85267   }
85268 #endif
85269
85270   db->init.busy = 0;
85271   if( rc==SQLITE_OK && commit_internal ){
85272     sqlite3CommitInternalChanges(db);
85273   }
85274
85275   return rc; 
85276 }
85277
85278 /*
85279 ** This routine is a no-op if the database schema is already initialised.
85280 ** Otherwise, the schema is loaded. An error code is returned.
85281 */
85282 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
85283   int rc = SQLITE_OK;
85284   sqlite3 *db = pParse->db;
85285   assert( sqlite3_mutex_held(db->mutex) );
85286   if( !db->init.busy ){
85287     rc = sqlite3Init(db, &pParse->zErrMsg);
85288   }
85289   if( rc!=SQLITE_OK ){
85290     pParse->rc = rc;
85291     pParse->nErr++;
85292   }
85293   return rc;
85294 }
85295
85296
85297 /*
85298 ** Check schema cookies in all databases.  If any cookie is out
85299 ** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
85300 ** make no changes to pParse->rc.
85301 */
85302 static void schemaIsValid(Parse *pParse){
85303   sqlite3 *db = pParse->db;
85304   int iDb;
85305   int rc;
85306   int cookie;
85307
85308   assert( pParse->checkSchema );
85309   assert( sqlite3_mutex_held(db->mutex) );
85310   for(iDb=0; iDb<db->nDb; iDb++){
85311     int openedTransaction = 0;         /* True if a transaction is opened */
85312     Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
85313     if( pBt==0 ) continue;
85314
85315     /* If there is not already a read-only (or read-write) transaction opened
85316     ** on the b-tree database, open one now. If a transaction is opened, it 
85317     ** will be closed immediately after reading the meta-value. */
85318     if( !sqlite3BtreeIsInReadTrans(pBt) ){
85319       rc = sqlite3BtreeBeginTrans(pBt, 0);
85320       if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
85321         db->mallocFailed = 1;
85322       }
85323       if( rc!=SQLITE_OK ) return;
85324       openedTransaction = 1;
85325     }
85326
85327     /* Read the schema cookie from the database. If it does not match the 
85328     ** value stored as part of the in-memory schema representation,
85329     ** set Parse.rc to SQLITE_SCHEMA. */
85330     sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
85331     if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
85332       pParse->rc = SQLITE_SCHEMA;
85333     }
85334
85335     /* Close the transaction, if one was opened. */
85336     if( openedTransaction ){
85337       sqlite3BtreeCommit(pBt);
85338     }
85339   }
85340 }
85341
85342 /*
85343 ** Convert a schema pointer into the iDb index that indicates
85344 ** which database file in db->aDb[] the schema refers to.
85345 **
85346 ** If the same database is attached more than once, the first
85347 ** attached database is returned.
85348 */
85349 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
85350   int i = -1000000;
85351
85352   /* If pSchema is NULL, then return -1000000. This happens when code in 
85353   ** expr.c is trying to resolve a reference to a transient table (i.e. one
85354   ** created by a sub-select). In this case the return value of this 
85355   ** function should never be used.
85356   **
85357   ** We return -1000000 instead of the more usual -1 simply because using
85358   ** -1000000 as the incorrect index into db->aDb[] is much 
85359   ** more likely to cause a segfault than -1 (of course there are assert()
85360   ** statements too, but it never hurts to play the odds).
85361   */
85362   assert( sqlite3_mutex_held(db->mutex) );
85363   if( pSchema ){
85364     for(i=0; ALWAYS(i<db->nDb); i++){
85365       if( db->aDb[i].pSchema==pSchema ){
85366         break;
85367       }
85368     }
85369     assert( i>=0 && i<db->nDb );
85370   }
85371   return i;
85372 }
85373
85374 /*
85375 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
85376 */
85377 static int sqlite3Prepare(
85378   sqlite3 *db,              /* Database handle. */
85379   const char *zSql,         /* UTF-8 encoded SQL statement. */
85380   int nBytes,               /* Length of zSql in bytes. */
85381   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
85382   Vdbe *pReprepare,         /* VM being reprepared */
85383   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
85384   const char **pzTail       /* OUT: End of parsed string */
85385 ){
85386   Parse *pParse;            /* Parsing context */
85387   char *zErrMsg = 0;        /* Error message */
85388   int rc = SQLITE_OK;       /* Result code */
85389   int i;                    /* Loop counter */
85390
85391   /* Allocate the parsing context */
85392   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
85393   if( pParse==0 ){
85394     rc = SQLITE_NOMEM;
85395     goto end_prepare;
85396   }
85397   pParse->pReprepare = pReprepare;
85398   assert( ppStmt && *ppStmt==0 );
85399   assert( !db->mallocFailed );
85400   assert( sqlite3_mutex_held(db->mutex) );
85401
85402   /* Check to verify that it is possible to get a read lock on all
85403   ** database schemas.  The inability to get a read lock indicates that
85404   ** some other database connection is holding a write-lock, which in
85405   ** turn means that the other connection has made uncommitted changes
85406   ** to the schema.
85407   **
85408   ** Were we to proceed and prepare the statement against the uncommitted
85409   ** schema changes and if those schema changes are subsequently rolled
85410   ** back and different changes are made in their place, then when this
85411   ** prepared statement goes to run the schema cookie would fail to detect
85412   ** the schema change.  Disaster would follow.
85413   **
85414   ** This thread is currently holding mutexes on all Btrees (because
85415   ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
85416   ** is not possible for another thread to start a new schema change
85417   ** while this routine is running.  Hence, we do not need to hold 
85418   ** locks on the schema, we just need to make sure nobody else is 
85419   ** holding them.
85420   **
85421   ** Note that setting READ_UNCOMMITTED overrides most lock detection,
85422   ** but it does *not* override schema lock detection, so this all still
85423   ** works even if READ_UNCOMMITTED is set.
85424   */
85425   for(i=0; i<db->nDb; i++) {
85426     Btree *pBt = db->aDb[i].pBt;
85427     if( pBt ){
85428       assert( sqlite3BtreeHoldsMutex(pBt) );
85429       rc = sqlite3BtreeSchemaLocked(pBt);
85430       if( rc ){
85431         const char *zDb = db->aDb[i].zName;
85432         sqlite3Error(db, rc, "database schema is locked: %s", zDb);
85433         testcase( db->flags & SQLITE_ReadUncommitted );
85434         goto end_prepare;
85435       }
85436     }
85437   }
85438
85439   sqlite3VtabUnlockList(db);
85440
85441   pParse->db = db;
85442   pParse->nQueryLoop = (double)1;
85443   if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
85444     char *zSqlCopy;
85445     int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
85446     testcase( nBytes==mxLen );
85447     testcase( nBytes==mxLen+1 );
85448     if( nBytes>mxLen ){
85449       sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
85450       rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
85451       goto end_prepare;
85452     }
85453     zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
85454     if( zSqlCopy ){
85455       sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
85456       sqlite3DbFree(db, zSqlCopy);
85457       pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
85458     }else{
85459       pParse->zTail = &zSql[nBytes];
85460     }
85461   }else{
85462     sqlite3RunParser(pParse, zSql, &zErrMsg);
85463   }
85464   assert( 1==(int)pParse->nQueryLoop );
85465
85466   if( db->mallocFailed ){
85467     pParse->rc = SQLITE_NOMEM;
85468   }
85469   if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
85470   if( pParse->checkSchema ){
85471     schemaIsValid(pParse);
85472   }
85473   if( pParse->rc==SQLITE_SCHEMA ){
85474     sqlite3ResetInternalSchema(db, 0);
85475   }
85476   if( db->mallocFailed ){
85477     pParse->rc = SQLITE_NOMEM;
85478   }
85479   if( pzTail ){
85480     *pzTail = pParse->zTail;
85481   }
85482   rc = pParse->rc;
85483
85484 #ifndef SQLITE_OMIT_EXPLAIN
85485   if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
85486     static const char * const azColName[] = {
85487        "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
85488        "order", "from", "detail"
85489     };
85490     int iFirst, mx;
85491     if( pParse->explain==2 ){
85492       sqlite3VdbeSetNumCols(pParse->pVdbe, 3);
85493       iFirst = 8;
85494       mx = 11;
85495     }else{
85496       sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
85497       iFirst = 0;
85498       mx = 8;
85499     }
85500     for(i=iFirst; i<mx; i++){
85501       sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
85502                             azColName[i], SQLITE_STATIC);
85503     }
85504   }
85505 #endif
85506
85507   assert( db->init.busy==0 || saveSqlFlag==0 );
85508   if( db->init.busy==0 ){
85509     Vdbe *pVdbe = pParse->pVdbe;
85510     sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
85511   }
85512   if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
85513     sqlite3VdbeFinalize(pParse->pVdbe);
85514     assert(!(*ppStmt));
85515   }else{
85516     *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
85517   }
85518
85519   if( zErrMsg ){
85520     sqlite3Error(db, rc, "%s", zErrMsg);
85521     sqlite3DbFree(db, zErrMsg);
85522   }else{
85523     sqlite3Error(db, rc, 0);
85524   }
85525
85526   /* Delete any TriggerPrg structures allocated while parsing this statement. */
85527   while( pParse->pTriggerPrg ){
85528     TriggerPrg *pT = pParse->pTriggerPrg;
85529     pParse->pTriggerPrg = pT->pNext;
85530     sqlite3VdbeProgramDelete(db, pT->pProgram, 0);
85531     sqlite3DbFree(db, pT);
85532   }
85533
85534 end_prepare:
85535
85536   sqlite3StackFree(db, pParse);
85537   rc = sqlite3ApiExit(db, rc);
85538   assert( (rc&db->errMask)==rc );
85539   return rc;
85540 }
85541 static int sqlite3LockAndPrepare(
85542   sqlite3 *db,              /* Database handle. */
85543   const char *zSql,         /* UTF-8 encoded SQL statement. */
85544   int nBytes,               /* Length of zSql in bytes. */
85545   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
85546   Vdbe *pOld,               /* VM being reprepared */
85547   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
85548   const char **pzTail       /* OUT: End of parsed string */
85549 ){
85550   int rc;
85551   assert( ppStmt!=0 );
85552   *ppStmt = 0;
85553   if( !sqlite3SafetyCheckOk(db) ){
85554     return SQLITE_MISUSE_BKPT;
85555   }
85556   sqlite3_mutex_enter(db->mutex);
85557   sqlite3BtreeEnterAll(db);
85558   rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
85559   if( rc==SQLITE_SCHEMA ){
85560     sqlite3_finalize(*ppStmt);
85561     rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
85562   }
85563   sqlite3BtreeLeaveAll(db);
85564   sqlite3_mutex_leave(db->mutex);
85565   return rc;
85566 }
85567
85568 /*
85569 ** Rerun the compilation of a statement after a schema change.
85570 **
85571 ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
85572 ** if the statement cannot be recompiled because another connection has
85573 ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
85574 ** occurs, return SQLITE_SCHEMA.
85575 */
85576 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
85577   int rc;
85578   sqlite3_stmt *pNew;
85579   const char *zSql;
85580   sqlite3 *db;
85581
85582   assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
85583   zSql = sqlite3_sql((sqlite3_stmt *)p);
85584   assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
85585   db = sqlite3VdbeDb(p);
85586   assert( sqlite3_mutex_held(db->mutex) );
85587   rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
85588   if( rc ){
85589     if( rc==SQLITE_NOMEM ){
85590       db->mallocFailed = 1;
85591     }
85592     assert( pNew==0 );
85593     return rc;
85594   }else{
85595     assert( pNew!=0 );
85596   }
85597   sqlite3VdbeSwap((Vdbe*)pNew, p);
85598   sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
85599   sqlite3VdbeResetStepResult((Vdbe*)pNew);
85600   sqlite3VdbeFinalize((Vdbe*)pNew);
85601   return SQLITE_OK;
85602 }
85603
85604
85605 /*
85606 ** Two versions of the official API.  Legacy and new use.  In the legacy
85607 ** version, the original SQL text is not saved in the prepared statement
85608 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
85609 ** sqlite3_step().  In the new version, the original SQL text is retained
85610 ** and the statement is automatically recompiled if an schema change
85611 ** occurs.
85612 */
85613 SQLITE_API int sqlite3_prepare(
85614   sqlite3 *db,              /* Database handle. */
85615   const char *zSql,         /* UTF-8 encoded SQL statement. */
85616   int nBytes,               /* Length of zSql in bytes. */
85617   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
85618   const char **pzTail       /* OUT: End of parsed string */
85619 ){
85620   int rc;
85621   rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
85622   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
85623   return rc;
85624 }
85625 SQLITE_API int sqlite3_prepare_v2(
85626   sqlite3 *db,              /* Database handle. */
85627   const char *zSql,         /* UTF-8 encoded SQL statement. */
85628   int nBytes,               /* Length of zSql in bytes. */
85629   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
85630   const char **pzTail       /* OUT: End of parsed string */
85631 ){
85632   int rc;
85633   rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
85634   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
85635   return rc;
85636 }
85637
85638
85639 #ifndef SQLITE_OMIT_UTF16
85640 /*
85641 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
85642 */
85643 static int sqlite3Prepare16(
85644   sqlite3 *db,              /* Database handle. */ 
85645   const void *zSql,         /* UTF-8 encoded SQL statement. */
85646   int nBytes,               /* Length of zSql in bytes. */
85647   int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
85648   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
85649   const void **pzTail       /* OUT: End of parsed string */
85650 ){
85651   /* This function currently works by first transforming the UTF-16
85652   ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
85653   ** tricky bit is figuring out the pointer to return in *pzTail.
85654   */
85655   char *zSql8;
85656   const char *zTail8 = 0;
85657   int rc = SQLITE_OK;
85658
85659   assert( ppStmt );
85660   *ppStmt = 0;
85661   if( !sqlite3SafetyCheckOk(db) ){
85662     return SQLITE_MISUSE_BKPT;
85663   }
85664   sqlite3_mutex_enter(db->mutex);
85665   zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
85666   if( zSql8 ){
85667     rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
85668   }
85669
85670   if( zTail8 && pzTail ){
85671     /* If sqlite3_prepare returns a tail pointer, we calculate the
85672     ** equivalent pointer into the UTF-16 string by counting the unicode
85673     ** characters between zSql8 and zTail8, and then returning a pointer
85674     ** the same number of characters into the UTF-16 string.
85675     */
85676     int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
85677     *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
85678   }
85679   sqlite3DbFree(db, zSql8); 
85680   rc = sqlite3ApiExit(db, rc);
85681   sqlite3_mutex_leave(db->mutex);
85682   return rc;
85683 }
85684
85685 /*
85686 ** Two versions of the official API.  Legacy and new use.  In the legacy
85687 ** version, the original SQL text is not saved in the prepared statement
85688 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
85689 ** sqlite3_step().  In the new version, the original SQL text is retained
85690 ** and the statement is automatically recompiled if an schema change
85691 ** occurs.
85692 */
85693 SQLITE_API int sqlite3_prepare16(
85694   sqlite3 *db,              /* Database handle. */ 
85695   const void *zSql,         /* UTF-8 encoded SQL statement. */
85696   int nBytes,               /* Length of zSql in bytes. */
85697   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
85698   const void **pzTail       /* OUT: End of parsed string */
85699 ){
85700   int rc;
85701   rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
85702   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
85703   return rc;
85704 }
85705 SQLITE_API int sqlite3_prepare16_v2(
85706   sqlite3 *db,              /* Database handle. */ 
85707   const void *zSql,         /* UTF-8 encoded SQL statement. */
85708   int nBytes,               /* Length of zSql in bytes. */
85709   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
85710   const void **pzTail       /* OUT: End of parsed string */
85711 ){
85712   int rc;
85713   rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
85714   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
85715   return rc;
85716 }
85717
85718 #endif /* SQLITE_OMIT_UTF16 */
85719
85720 /************** End of prepare.c *********************************************/
85721 /************** Begin file select.c ******************************************/
85722 /*
85723 ** 2001 September 15
85724 **
85725 ** The author disclaims copyright to this source code.  In place of
85726 ** a legal notice, here is a blessing:
85727 **
85728 **    May you do good and not evil.
85729 **    May you find forgiveness for yourself and forgive others.
85730 **    May you share freely, never taking more than you give.
85731 **
85732 *************************************************************************
85733 ** This file contains C code routines that are called by the parser
85734 ** to handle SELECT statements in SQLite.
85735 */
85736
85737
85738 /*
85739 ** Delete all the content of a Select structure but do not deallocate
85740 ** the select structure itself.
85741 */
85742 static void clearSelect(sqlite3 *db, Select *p){
85743   sqlite3ExprListDelete(db, p->pEList);
85744   sqlite3SrcListDelete(db, p->pSrc);
85745   sqlite3ExprDelete(db, p->pWhere);
85746   sqlite3ExprListDelete(db, p->pGroupBy);
85747   sqlite3ExprDelete(db, p->pHaving);
85748   sqlite3ExprListDelete(db, p->pOrderBy);
85749   sqlite3SelectDelete(db, p->pPrior);
85750   sqlite3ExprDelete(db, p->pLimit);
85751   sqlite3ExprDelete(db, p->pOffset);
85752 }
85753
85754 /*
85755 ** Initialize a SelectDest structure.
85756 */
85757 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
85758   pDest->eDest = (u8)eDest;
85759   pDest->iParm = iParm;
85760   pDest->affinity = 0;
85761   pDest->iMem = 0;
85762   pDest->nMem = 0;
85763 }
85764
85765
85766 /*
85767 ** Allocate a new Select structure and return a pointer to that
85768 ** structure.
85769 */
85770 SQLITE_PRIVATE Select *sqlite3SelectNew(
85771   Parse *pParse,        /* Parsing context */
85772   ExprList *pEList,     /* which columns to include in the result */
85773   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
85774   Expr *pWhere,         /* the WHERE clause */
85775   ExprList *pGroupBy,   /* the GROUP BY clause */
85776   Expr *pHaving,        /* the HAVING clause */
85777   ExprList *pOrderBy,   /* the ORDER BY clause */
85778   int isDistinct,       /* true if the DISTINCT keyword is present */
85779   Expr *pLimit,         /* LIMIT value.  NULL means not used */
85780   Expr *pOffset         /* OFFSET value.  NULL means no offset */
85781 ){
85782   Select *pNew;
85783   Select standin;
85784   sqlite3 *db = pParse->db;
85785   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
85786   assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
85787   if( pNew==0 ){
85788     pNew = &standin;
85789     memset(pNew, 0, sizeof(*pNew));
85790   }
85791   if( pEList==0 ){
85792     pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
85793   }
85794   pNew->pEList = pEList;
85795   pNew->pSrc = pSrc;
85796   pNew->pWhere = pWhere;
85797   pNew->pGroupBy = pGroupBy;
85798   pNew->pHaving = pHaving;
85799   pNew->pOrderBy = pOrderBy;
85800   pNew->selFlags = isDistinct ? SF_Distinct : 0;
85801   pNew->op = TK_SELECT;
85802   pNew->pLimit = pLimit;
85803   pNew->pOffset = pOffset;
85804   assert( pOffset==0 || pLimit!=0 );
85805   pNew->addrOpenEphm[0] = -1;
85806   pNew->addrOpenEphm[1] = -1;
85807   pNew->addrOpenEphm[2] = -1;
85808   if( db->mallocFailed ) {
85809     clearSelect(db, pNew);
85810     if( pNew!=&standin ) sqlite3DbFree(db, pNew);
85811     pNew = 0;
85812   }
85813   return pNew;
85814 }
85815
85816 /*
85817 ** Delete the given Select structure and all of its substructures.
85818 */
85819 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
85820   if( p ){
85821     clearSelect(db, p);
85822     sqlite3DbFree(db, p);
85823   }
85824 }
85825
85826 /*
85827 ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
85828 ** type of join.  Return an integer constant that expresses that type
85829 ** in terms of the following bit values:
85830 **
85831 **     JT_INNER
85832 **     JT_CROSS
85833 **     JT_OUTER
85834 **     JT_NATURAL
85835 **     JT_LEFT
85836 **     JT_RIGHT
85837 **
85838 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
85839 **
85840 ** If an illegal or unsupported join type is seen, then still return
85841 ** a join type, but put an error in the pParse structure.
85842 */
85843 SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
85844   int jointype = 0;
85845   Token *apAll[3];
85846   Token *p;
85847                              /*   0123456789 123456789 123456789 123 */
85848   static const char zKeyText[] = "naturaleftouterightfullinnercross";
85849   static const struct {
85850     u8 i;        /* Beginning of keyword text in zKeyText[] */
85851     u8 nChar;    /* Length of the keyword in characters */
85852     u8 code;     /* Join type mask */
85853   } aKeyword[] = {
85854     /* natural */ { 0,  7, JT_NATURAL                },
85855     /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
85856     /* outer   */ { 10, 5, JT_OUTER                  },
85857     /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
85858     /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
85859     /* inner   */ { 23, 5, JT_INNER                  },
85860     /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
85861   };
85862   int i, j;
85863   apAll[0] = pA;
85864   apAll[1] = pB;
85865   apAll[2] = pC;
85866   for(i=0; i<3 && apAll[i]; i++){
85867     p = apAll[i];
85868     for(j=0; j<ArraySize(aKeyword); j++){
85869       if( p->n==aKeyword[j].nChar 
85870           && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
85871         jointype |= aKeyword[j].code;
85872         break;
85873       }
85874     }
85875     testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
85876     if( j>=ArraySize(aKeyword) ){
85877       jointype |= JT_ERROR;
85878       break;
85879     }
85880   }
85881   if(
85882      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
85883      (jointype & JT_ERROR)!=0
85884   ){
85885     const char *zSp = " ";
85886     assert( pB!=0 );
85887     if( pC==0 ){ zSp++; }
85888     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
85889        "%T %T%s%T", pA, pB, zSp, pC);
85890     jointype = JT_INNER;
85891   }else if( (jointype & JT_OUTER)!=0 
85892          && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
85893     sqlite3ErrorMsg(pParse, 
85894       "RIGHT and FULL OUTER JOINs are not currently supported");
85895     jointype = JT_INNER;
85896   }
85897   return jointype;
85898 }
85899
85900 /*
85901 ** Return the index of a column in a table.  Return -1 if the column
85902 ** is not contained in the table.
85903 */
85904 static int columnIndex(Table *pTab, const char *zCol){
85905   int i;
85906   for(i=0; i<pTab->nCol; i++){
85907     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
85908   }
85909   return -1;
85910 }
85911
85912 /*
85913 ** Search the first N tables in pSrc, from left to right, looking for a
85914 ** table that has a column named zCol.  
85915 **
85916 ** When found, set *piTab and *piCol to the table index and column index
85917 ** of the matching column and return TRUE.
85918 **
85919 ** If not found, return FALSE.
85920 */
85921 static int tableAndColumnIndex(
85922   SrcList *pSrc,       /* Array of tables to search */
85923   int N,               /* Number of tables in pSrc->a[] to search */
85924   const char *zCol,    /* Name of the column we are looking for */
85925   int *piTab,          /* Write index of pSrc->a[] here */
85926   int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
85927 ){
85928   int i;               /* For looping over tables in pSrc */
85929   int iCol;            /* Index of column matching zCol */
85930
85931   assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
85932   for(i=0; i<N; i++){
85933     iCol = columnIndex(pSrc->a[i].pTab, zCol);
85934     if( iCol>=0 ){
85935       if( piTab ){
85936         *piTab = i;
85937         *piCol = iCol;
85938       }
85939       return 1;
85940     }
85941   }
85942   return 0;
85943 }
85944
85945 /*
85946 ** This function is used to add terms implied by JOIN syntax to the
85947 ** WHERE clause expression of a SELECT statement. The new term, which
85948 ** is ANDed with the existing WHERE clause, is of the form:
85949 **
85950 **    (tab1.col1 = tab2.col2)
85951 **
85952 ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the 
85953 ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
85954 ** column iColRight of tab2.
85955 */
85956 static void addWhereTerm(
85957   Parse *pParse,                  /* Parsing context */
85958   SrcList *pSrc,                  /* List of tables in FROM clause */
85959   int iLeft,                      /* Index of first table to join in pSrc */
85960   int iColLeft,                   /* Index of column in first table */
85961   int iRight,                     /* Index of second table in pSrc */
85962   int iColRight,                  /* Index of column in second table */
85963   int isOuterJoin,                /* True if this is an OUTER join */
85964   Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
85965 ){
85966   sqlite3 *db = pParse->db;
85967   Expr *pE1;
85968   Expr *pE2;
85969   Expr *pEq;
85970
85971   assert( iLeft<iRight );
85972   assert( pSrc->nSrc>iRight );
85973   assert( pSrc->a[iLeft].pTab );
85974   assert( pSrc->a[iRight].pTab );
85975
85976   pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
85977   pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
85978
85979   pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
85980   if( pEq && isOuterJoin ){
85981     ExprSetProperty(pEq, EP_FromJoin);
85982     assert( !ExprHasAnyProperty(pEq, EP_TokenOnly|EP_Reduced) );
85983     ExprSetIrreducible(pEq);
85984     pEq->iRightJoinTable = (i16)pE2->iTable;
85985   }
85986   *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
85987 }
85988
85989 /*
85990 ** Set the EP_FromJoin property on all terms of the given expression.
85991 ** And set the Expr.iRightJoinTable to iTable for every term in the
85992 ** expression.
85993 **
85994 ** The EP_FromJoin property is used on terms of an expression to tell
85995 ** the LEFT OUTER JOIN processing logic that this term is part of the
85996 ** join restriction specified in the ON or USING clause and not a part
85997 ** of the more general WHERE clause.  These terms are moved over to the
85998 ** WHERE clause during join processing but we need to remember that they
85999 ** originated in the ON or USING clause.
86000 **
86001 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
86002 ** expression depends on table iRightJoinTable even if that table is not
86003 ** explicitly mentioned in the expression.  That information is needed
86004 ** for cases like this:
86005 **
86006 **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
86007 **
86008 ** The where clause needs to defer the handling of the t1.x=5
86009 ** term until after the t2 loop of the join.  In that way, a
86010 ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
86011 ** defer the handling of t1.x=5, it will be processed immediately
86012 ** after the t1 loop and rows with t1.x!=5 will never appear in
86013 ** the output, which is incorrect.
86014 */
86015 static void setJoinExpr(Expr *p, int iTable){
86016   while( p ){
86017     ExprSetProperty(p, EP_FromJoin);
86018     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
86019     ExprSetIrreducible(p);
86020     p->iRightJoinTable = (i16)iTable;
86021     setJoinExpr(p->pLeft, iTable);
86022     p = p->pRight;
86023   } 
86024 }
86025
86026 /*
86027 ** This routine processes the join information for a SELECT statement.
86028 ** ON and USING clauses are converted into extra terms of the WHERE clause.
86029 ** NATURAL joins also create extra WHERE clause terms.
86030 **
86031 ** The terms of a FROM clause are contained in the Select.pSrc structure.
86032 ** The left most table is the first entry in Select.pSrc.  The right-most
86033 ** table is the last entry.  The join operator is held in the entry to
86034 ** the left.  Thus entry 0 contains the join operator for the join between
86035 ** entries 0 and 1.  Any ON or USING clauses associated with the join are
86036 ** also attached to the left entry.
86037 **
86038 ** This routine returns the number of errors encountered.
86039 */
86040 static int sqliteProcessJoin(Parse *pParse, Select *p){
86041   SrcList *pSrc;                  /* All tables in the FROM clause */
86042   int i, j;                       /* Loop counters */
86043   struct SrcList_item *pLeft;     /* Left table being joined */
86044   struct SrcList_item *pRight;    /* Right table being joined */
86045
86046   pSrc = p->pSrc;
86047   pLeft = &pSrc->a[0];
86048   pRight = &pLeft[1];
86049   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
86050     Table *pLeftTab = pLeft->pTab;
86051     Table *pRightTab = pRight->pTab;
86052     int isOuter;
86053
86054     if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
86055     isOuter = (pRight->jointype & JT_OUTER)!=0;
86056
86057     /* When the NATURAL keyword is present, add WHERE clause terms for
86058     ** every column that the two tables have in common.
86059     */
86060     if( pRight->jointype & JT_NATURAL ){
86061       if( pRight->pOn || pRight->pUsing ){
86062         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
86063            "an ON or USING clause", 0);
86064         return 1;
86065       }
86066       for(j=0; j<pRightTab->nCol; j++){
86067         char *zName;   /* Name of column in the right table */
86068         int iLeft;     /* Matching left table */
86069         int iLeftCol;  /* Matching column in the left table */
86070
86071         zName = pRightTab->aCol[j].zName;
86072         if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
86073           addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
86074                        isOuter, &p->pWhere);
86075         }
86076       }
86077     }
86078
86079     /* Disallow both ON and USING clauses in the same join
86080     */
86081     if( pRight->pOn && pRight->pUsing ){
86082       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
86083         "clauses in the same join");
86084       return 1;
86085     }
86086
86087     /* Add the ON clause to the end of the WHERE clause, connected by
86088     ** an AND operator.
86089     */
86090     if( pRight->pOn ){
86091       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
86092       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
86093       pRight->pOn = 0;
86094     }
86095
86096     /* Create extra terms on the WHERE clause for each column named
86097     ** in the USING clause.  Example: If the two tables to be joined are 
86098     ** A and B and the USING clause names X, Y, and Z, then add this
86099     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
86100     ** Report an error if any column mentioned in the USING clause is
86101     ** not contained in both tables to be joined.
86102     */
86103     if( pRight->pUsing ){
86104       IdList *pList = pRight->pUsing;
86105       for(j=0; j<pList->nId; j++){
86106         char *zName;     /* Name of the term in the USING clause */
86107         int iLeft;       /* Table on the left with matching column name */
86108         int iLeftCol;    /* Column number of matching column on the left */
86109         int iRightCol;   /* Column number of matching column on the right */
86110
86111         zName = pList->a[j].zName;
86112         iRightCol = columnIndex(pRightTab, zName);
86113         if( iRightCol<0
86114          || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
86115         ){
86116           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
86117             "not present in both tables", zName);
86118           return 1;
86119         }
86120         addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
86121                      isOuter, &p->pWhere);
86122       }
86123     }
86124   }
86125   return 0;
86126 }
86127
86128 /*
86129 ** Insert code into "v" that will push the record on the top of the
86130 ** stack into the sorter.
86131 */
86132 static void pushOntoSorter(
86133   Parse *pParse,         /* Parser context */
86134   ExprList *pOrderBy,    /* The ORDER BY clause */
86135   Select *pSelect,       /* The whole SELECT statement */
86136   int regData            /* Register holding data to be sorted */
86137 ){
86138   Vdbe *v = pParse->pVdbe;
86139   int nExpr = pOrderBy->nExpr;
86140   int regBase = sqlite3GetTempRange(pParse, nExpr+2);
86141   int regRecord = sqlite3GetTempReg(pParse);
86142   sqlite3ExprCacheClear(pParse);
86143   sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
86144   sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
86145   sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
86146   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
86147   sqlite3VdbeAddOp2(v, OP_IdxInsert, pOrderBy->iECursor, regRecord);
86148   sqlite3ReleaseTempReg(pParse, regRecord);
86149   sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
86150   if( pSelect->iLimit ){
86151     int addr1, addr2;
86152     int iLimit;
86153     if( pSelect->iOffset ){
86154       iLimit = pSelect->iOffset+1;
86155     }else{
86156       iLimit = pSelect->iLimit;
86157     }
86158     addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
86159     sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
86160     addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
86161     sqlite3VdbeJumpHere(v, addr1);
86162     sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
86163     sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
86164     sqlite3VdbeJumpHere(v, addr2);
86165     pSelect->iLimit = 0;
86166   }
86167 }
86168
86169 /*
86170 ** Add code to implement the OFFSET
86171 */
86172 static void codeOffset(
86173   Vdbe *v,          /* Generate code into this VM */
86174   Select *p,        /* The SELECT statement being coded */
86175   int iContinue     /* Jump here to skip the current record */
86176 ){
86177   if( p->iOffset && iContinue!=0 ){
86178     int addr;
86179     sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
86180     addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
86181     sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
86182     VdbeComment((v, "skip OFFSET records"));
86183     sqlite3VdbeJumpHere(v, addr);
86184   }
86185 }
86186
86187 /*
86188 ** Add code that will check to make sure the N registers starting at iMem
86189 ** form a distinct entry.  iTab is a sorting index that holds previously
86190 ** seen combinations of the N values.  A new entry is made in iTab
86191 ** if the current N values are new.
86192 **
86193 ** A jump to addrRepeat is made and the N+1 values are popped from the
86194 ** stack if the top N elements are not distinct.
86195 */
86196 static void codeDistinct(
86197   Parse *pParse,     /* Parsing and code generating context */
86198   int iTab,          /* A sorting index used to test for distinctness */
86199   int addrRepeat,    /* Jump to here if not distinct */
86200   int N,             /* Number of elements */
86201   int iMem           /* First element */
86202 ){
86203   Vdbe *v;
86204   int r1;
86205
86206   v = pParse->pVdbe;
86207   r1 = sqlite3GetTempReg(pParse);
86208   sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
86209   sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
86210   sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
86211   sqlite3ReleaseTempReg(pParse, r1);
86212 }
86213
86214 /*
86215 ** Generate an error message when a SELECT is used within a subexpression
86216 ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
86217 ** column.  We do this in a subroutine because the error occurs in multiple
86218 ** places.
86219 */
86220 static int checkForMultiColumnSelectError(
86221   Parse *pParse,       /* Parse context. */
86222   SelectDest *pDest,   /* Destination of SELECT results */
86223   int nExpr            /* Number of result columns returned by SELECT */
86224 ){
86225   int eDest = pDest->eDest;
86226   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
86227     sqlite3ErrorMsg(pParse, "only a single result allowed for "
86228        "a SELECT that is part of an expression");
86229     return 1;
86230   }else{
86231     return 0;
86232   }
86233 }
86234
86235 /*
86236 ** This routine generates the code for the inside of the inner loop
86237 ** of a SELECT.
86238 **
86239 ** If srcTab and nColumn are both zero, then the pEList expressions
86240 ** are evaluated in order to get the data for this row.  If nColumn>0
86241 ** then data is pulled from srcTab and pEList is used only to get the
86242 ** datatypes for each column.
86243 */
86244 static void selectInnerLoop(
86245   Parse *pParse,          /* The parser context */
86246   Select *p,              /* The complete select statement being coded */
86247   ExprList *pEList,       /* List of values being extracted */
86248   int srcTab,             /* Pull data from this table */
86249   int nColumn,            /* Number of columns in the source table */
86250   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
86251   int distinct,           /* If >=0, make sure results are distinct */
86252   SelectDest *pDest,      /* How to dispose of the results */
86253   int iContinue,          /* Jump here to continue with next row */
86254   int iBreak              /* Jump here to break out of the inner loop */
86255 ){
86256   Vdbe *v = pParse->pVdbe;
86257   int i;
86258   int hasDistinct;        /* True if the DISTINCT keyword is present */
86259   int regResult;              /* Start of memory holding result set */
86260   int eDest = pDest->eDest;   /* How to dispose of results */
86261   int iParm = pDest->iParm;   /* First argument to disposal method */
86262   int nResultCol;             /* Number of result columns */
86263
86264   assert( v );
86265   if( NEVER(v==0) ) return;
86266   assert( pEList!=0 );
86267   hasDistinct = distinct>=0;
86268   if( pOrderBy==0 && !hasDistinct ){
86269     codeOffset(v, p, iContinue);
86270   }
86271
86272   /* Pull the requested columns.
86273   */
86274   if( nColumn>0 ){
86275     nResultCol = nColumn;
86276   }else{
86277     nResultCol = pEList->nExpr;
86278   }
86279   if( pDest->iMem==0 ){
86280     pDest->iMem = pParse->nMem+1;
86281     pDest->nMem = nResultCol;
86282     pParse->nMem += nResultCol;
86283   }else{ 
86284     assert( pDest->nMem==nResultCol );
86285   }
86286   regResult = pDest->iMem;
86287   if( nColumn>0 ){
86288     for(i=0; i<nColumn; i++){
86289       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
86290     }
86291   }else if( eDest!=SRT_Exists ){
86292     /* If the destination is an EXISTS(...) expression, the actual
86293     ** values returned by the SELECT are not required.
86294     */
86295     sqlite3ExprCacheClear(pParse);
86296     sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
86297   }
86298   nColumn = nResultCol;
86299
86300   /* If the DISTINCT keyword was present on the SELECT statement
86301   ** and this row has been seen before, then do not make this row
86302   ** part of the result.
86303   */
86304   if( hasDistinct ){
86305     assert( pEList!=0 );
86306     assert( pEList->nExpr==nColumn );
86307     codeDistinct(pParse, distinct, iContinue, nColumn, regResult);
86308     if( pOrderBy==0 ){
86309       codeOffset(v, p, iContinue);
86310     }
86311   }
86312
86313   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
86314     return;
86315   }
86316
86317   switch( eDest ){
86318     /* In this mode, write each query result to the key of the temporary
86319     ** table iParm.
86320     */
86321 #ifndef SQLITE_OMIT_COMPOUND_SELECT
86322     case SRT_Union: {
86323       int r1;
86324       r1 = sqlite3GetTempReg(pParse);
86325       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
86326       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
86327       sqlite3ReleaseTempReg(pParse, r1);
86328       break;
86329     }
86330
86331     /* Construct a record from the query result, but instead of
86332     ** saving that record, use it as a key to delete elements from
86333     ** the temporary table iParm.
86334     */
86335     case SRT_Except: {
86336       sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
86337       break;
86338     }
86339 #endif
86340
86341     /* Store the result as data using a unique key.
86342     */
86343     case SRT_Table:
86344     case SRT_EphemTab: {
86345       int r1 = sqlite3GetTempReg(pParse);
86346       testcase( eDest==SRT_Table );
86347       testcase( eDest==SRT_EphemTab );
86348       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
86349       if( pOrderBy ){
86350         pushOntoSorter(pParse, pOrderBy, p, r1);
86351       }else{
86352         int r2 = sqlite3GetTempReg(pParse);
86353         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
86354         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
86355         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
86356         sqlite3ReleaseTempReg(pParse, r2);
86357       }
86358       sqlite3ReleaseTempReg(pParse, r1);
86359       break;
86360     }
86361
86362 #ifndef SQLITE_OMIT_SUBQUERY
86363     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
86364     ** then there should be a single item on the stack.  Write this
86365     ** item into the set table with bogus data.
86366     */
86367     case SRT_Set: {
86368       assert( nColumn==1 );
86369       p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity);
86370       if( pOrderBy ){
86371         /* At first glance you would think we could optimize out the
86372         ** ORDER BY in this case since the order of entries in the set
86373         ** does not matter.  But there might be a LIMIT clause, in which
86374         ** case the order does matter */
86375         pushOntoSorter(pParse, pOrderBy, p, regResult);
86376       }else{
86377         int r1 = sqlite3GetTempReg(pParse);
86378         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);
86379         sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
86380         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
86381         sqlite3ReleaseTempReg(pParse, r1);
86382       }
86383       break;
86384     }
86385
86386     /* If any row exist in the result set, record that fact and abort.
86387     */
86388     case SRT_Exists: {
86389       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
86390       /* The LIMIT clause will terminate the loop for us */
86391       break;
86392     }
86393
86394     /* If this is a scalar select that is part of an expression, then
86395     ** store the results in the appropriate memory cell and break out
86396     ** of the scan loop.
86397     */
86398     case SRT_Mem: {
86399       assert( nColumn==1 );
86400       if( pOrderBy ){
86401         pushOntoSorter(pParse, pOrderBy, p, regResult);
86402       }else{
86403         sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
86404         /* The LIMIT clause will jump out of the loop for us */
86405       }
86406       break;
86407     }
86408 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
86409
86410     /* Send the data to the callback function or to a subroutine.  In the
86411     ** case of a subroutine, the subroutine itself is responsible for
86412     ** popping the data from the stack.
86413     */
86414     case SRT_Coroutine:
86415     case SRT_Output: {
86416       testcase( eDest==SRT_Coroutine );
86417       testcase( eDest==SRT_Output );
86418       if( pOrderBy ){
86419         int r1 = sqlite3GetTempReg(pParse);
86420         sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
86421         pushOntoSorter(pParse, pOrderBy, p, r1);
86422         sqlite3ReleaseTempReg(pParse, r1);
86423       }else if( eDest==SRT_Coroutine ){
86424         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
86425       }else{
86426         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
86427         sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
86428       }
86429       break;
86430     }
86431
86432 #if !defined(SQLITE_OMIT_TRIGGER)
86433     /* Discard the results.  This is used for SELECT statements inside
86434     ** the body of a TRIGGER.  The purpose of such selects is to call
86435     ** user-defined functions that have side effects.  We do not care
86436     ** about the actual results of the select.
86437     */
86438     default: {
86439       assert( eDest==SRT_Discard );
86440       break;
86441     }
86442 #endif
86443   }
86444
86445   /* Jump to the end of the loop if the LIMIT is reached.
86446   */
86447   if( p->iLimit ){
86448     assert( pOrderBy==0 );  /* If there is an ORDER BY, the call to
86449                             ** pushOntoSorter() would have cleared p->iLimit */
86450     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
86451   }
86452 }
86453
86454 /*
86455 ** Given an expression list, generate a KeyInfo structure that records
86456 ** the collating sequence for each expression in that expression list.
86457 **
86458 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
86459 ** KeyInfo structure is appropriate for initializing a virtual index to
86460 ** implement that clause.  If the ExprList is the result set of a SELECT
86461 ** then the KeyInfo structure is appropriate for initializing a virtual
86462 ** index to implement a DISTINCT test.
86463 **
86464 ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
86465 ** function is responsible for seeing that this structure is eventually
86466 ** freed.  Add the KeyInfo structure to the P4 field of an opcode using
86467 ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
86468 */
86469 static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
86470   sqlite3 *db = pParse->db;
86471   int nExpr;
86472   KeyInfo *pInfo;
86473   struct ExprList_item *pItem;
86474   int i;
86475
86476   nExpr = pList->nExpr;
86477   pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
86478   if( pInfo ){
86479     pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
86480     pInfo->nField = (u16)nExpr;
86481     pInfo->enc = ENC(db);
86482     pInfo->db = db;
86483     for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
86484       CollSeq *pColl;
86485       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
86486       if( !pColl ){
86487         pColl = db->pDfltColl;
86488       }
86489       pInfo->aColl[i] = pColl;
86490       pInfo->aSortOrder[i] = pItem->sortOrder;
86491     }
86492   }
86493   return pInfo;
86494 }
86495
86496
86497 /*
86498 ** If the inner loop was generated using a non-null pOrderBy argument,
86499 ** then the results were placed in a sorter.  After the loop is terminated
86500 ** we need to run the sorter and output the results.  The following
86501 ** routine generates the code needed to do that.
86502 */
86503 static void generateSortTail(
86504   Parse *pParse,    /* Parsing context */
86505   Select *p,        /* The SELECT statement */
86506   Vdbe *v,          /* Generate code into this VDBE */
86507   int nColumn,      /* Number of columns of data */
86508   SelectDest *pDest /* Write the sorted results here */
86509 ){
86510   int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */
86511   int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
86512   int addr;
86513   int iTab;
86514   int pseudoTab = 0;
86515   ExprList *pOrderBy = p->pOrderBy;
86516
86517   int eDest = pDest->eDest;
86518   int iParm = pDest->iParm;
86519
86520   int regRow;
86521   int regRowid;
86522
86523   iTab = pOrderBy->iECursor;
86524   regRow = sqlite3GetTempReg(pParse);
86525   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
86526     pseudoTab = pParse->nTab++;
86527     sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
86528     regRowid = 0;
86529   }else{
86530     regRowid = sqlite3GetTempReg(pParse);
86531   }
86532   addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
86533   codeOffset(v, p, addrContinue);
86534   sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr + 1, regRow);
86535   switch( eDest ){
86536     case SRT_Table:
86537     case SRT_EphemTab: {
86538       testcase( eDest==SRT_Table );
86539       testcase( eDest==SRT_EphemTab );
86540       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
86541       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
86542       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
86543       break;
86544     }
86545 #ifndef SQLITE_OMIT_SUBQUERY
86546     case SRT_Set: {
86547       assert( nColumn==1 );
86548       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);
86549       sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
86550       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
86551       break;
86552     }
86553     case SRT_Mem: {
86554       assert( nColumn==1 );
86555       sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
86556       /* The LIMIT clause will terminate the loop for us */
86557       break;
86558     }
86559 #endif
86560     default: {
86561       int i;
86562       assert( eDest==SRT_Output || eDest==SRT_Coroutine ); 
86563       testcase( eDest==SRT_Output );
86564       testcase( eDest==SRT_Coroutine );
86565       for(i=0; i<nColumn; i++){
86566         assert( regRow!=pDest->iMem+i );
86567         sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i);
86568         if( i==0 ){
86569           sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
86570         }
86571       }
86572       if( eDest==SRT_Output ){
86573         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn);
86574         sqlite3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn);
86575       }else{
86576         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
86577       }
86578       break;
86579     }
86580   }
86581   sqlite3ReleaseTempReg(pParse, regRow);
86582   sqlite3ReleaseTempReg(pParse, regRowid);
86583
86584   /* LIMIT has been implemented by the pushOntoSorter() routine.
86585   */
86586   assert( p->iLimit==0 );
86587
86588   /* The bottom of the loop
86589   */
86590   sqlite3VdbeResolveLabel(v, addrContinue);
86591   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
86592   sqlite3VdbeResolveLabel(v, addrBreak);
86593   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
86594     sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
86595   }
86596 }
86597
86598 /*
86599 ** Return a pointer to a string containing the 'declaration type' of the
86600 ** expression pExpr. The string may be treated as static by the caller.
86601 **
86602 ** The declaration type is the exact datatype definition extracted from the
86603 ** original CREATE TABLE statement if the expression is a column. The
86604 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
86605 ** is considered a column can be complex in the presence of subqueries. The
86606 ** result-set expression in all of the following SELECT statements is 
86607 ** considered a column by this function.
86608 **
86609 **   SELECT col FROM tbl;
86610 **   SELECT (SELECT col FROM tbl;
86611 **   SELECT (SELECT col FROM tbl);
86612 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
86613 ** 
86614 ** The declaration type for any expression other than a column is NULL.
86615 */
86616 static const char *columnType(
86617   NameContext *pNC, 
86618   Expr *pExpr,
86619   const char **pzOriginDb,
86620   const char **pzOriginTab,
86621   const char **pzOriginCol
86622 ){
86623   char const *zType = 0;
86624   char const *zOriginDb = 0;
86625   char const *zOriginTab = 0;
86626   char const *zOriginCol = 0;
86627   int j;
86628   if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
86629
86630   switch( pExpr->op ){
86631     case TK_AGG_COLUMN:
86632     case TK_COLUMN: {
86633       /* The expression is a column. Locate the table the column is being
86634       ** extracted from in NameContext.pSrcList. This table may be real
86635       ** database table or a subquery.
86636       */
86637       Table *pTab = 0;            /* Table structure column is extracted from */
86638       Select *pS = 0;             /* Select the column is extracted from */
86639       int iCol = pExpr->iColumn;  /* Index of column in pTab */
86640       testcase( pExpr->op==TK_AGG_COLUMN );
86641       testcase( pExpr->op==TK_COLUMN );
86642       while( pNC && !pTab ){
86643         SrcList *pTabList = pNC->pSrcList;
86644         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
86645         if( j<pTabList->nSrc ){
86646           pTab = pTabList->a[j].pTab;
86647           pS = pTabList->a[j].pSelect;
86648         }else{
86649           pNC = pNC->pNext;
86650         }
86651       }
86652
86653       if( pTab==0 ){
86654         /* At one time, code such as "SELECT new.x" within a trigger would
86655         ** cause this condition to run.  Since then, we have restructured how
86656         ** trigger code is generated and so this condition is no longer 
86657         ** possible. However, it can still be true for statements like
86658         ** the following:
86659         **
86660         **   CREATE TABLE t1(col INTEGER);
86661         **   SELECT (SELECT t1.col) FROM FROM t1;
86662         **
86663         ** when columnType() is called on the expression "t1.col" in the 
86664         ** sub-select. In this case, set the column type to NULL, even
86665         ** though it should really be "INTEGER".
86666         **
86667         ** This is not a problem, as the column type of "t1.col" is never
86668         ** used. When columnType() is called on the expression 
86669         ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
86670         ** branch below.  */
86671         break;
86672       }
86673
86674       assert( pTab && pExpr->pTab==pTab );
86675       if( pS ){
86676         /* The "table" is actually a sub-select or a view in the FROM clause
86677         ** of the SELECT statement. Return the declaration type and origin
86678         ** data for the result-set column of the sub-select.
86679         */
86680         if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
86681           /* If iCol is less than zero, then the expression requests the
86682           ** rowid of the sub-select or view. This expression is legal (see 
86683           ** test case misc2.2.2) - it always evaluates to NULL.
86684           */
86685           NameContext sNC;
86686           Expr *p = pS->pEList->a[iCol].pExpr;
86687           sNC.pSrcList = pS->pSrc;
86688           sNC.pNext = pNC;
86689           sNC.pParse = pNC->pParse;
86690           zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
86691         }
86692       }else if( ALWAYS(pTab->pSchema) ){
86693         /* A real table */
86694         assert( !pS );
86695         if( iCol<0 ) iCol = pTab->iPKey;
86696         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
86697         if( iCol<0 ){
86698           zType = "INTEGER";
86699           zOriginCol = "rowid";
86700         }else{
86701           zType = pTab->aCol[iCol].zType;
86702           zOriginCol = pTab->aCol[iCol].zName;
86703         }
86704         zOriginTab = pTab->zName;
86705         if( pNC->pParse ){
86706           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
86707           zOriginDb = pNC->pParse->db->aDb[iDb].zName;
86708         }
86709       }
86710       break;
86711     }
86712 #ifndef SQLITE_OMIT_SUBQUERY
86713     case TK_SELECT: {
86714       /* The expression is a sub-select. Return the declaration type and
86715       ** origin info for the single column in the result set of the SELECT
86716       ** statement.
86717       */
86718       NameContext sNC;
86719       Select *pS = pExpr->x.pSelect;
86720       Expr *p = pS->pEList->a[0].pExpr;
86721       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
86722       sNC.pSrcList = pS->pSrc;
86723       sNC.pNext = pNC;
86724       sNC.pParse = pNC->pParse;
86725       zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
86726       break;
86727     }
86728 #endif
86729   }
86730   
86731   if( pzOriginDb ){
86732     assert( pzOriginTab && pzOriginCol );
86733     *pzOriginDb = zOriginDb;
86734     *pzOriginTab = zOriginTab;
86735     *pzOriginCol = zOriginCol;
86736   }
86737   return zType;
86738 }
86739
86740 /*
86741 ** Generate code that will tell the VDBE the declaration types of columns
86742 ** in the result set.
86743 */
86744 static void generateColumnTypes(
86745   Parse *pParse,      /* Parser context */
86746   SrcList *pTabList,  /* List of tables */
86747   ExprList *pEList    /* Expressions defining the result set */
86748 ){
86749 #ifndef SQLITE_OMIT_DECLTYPE
86750   Vdbe *v = pParse->pVdbe;
86751   int i;
86752   NameContext sNC;
86753   sNC.pSrcList = pTabList;
86754   sNC.pParse = pParse;
86755   for(i=0; i<pEList->nExpr; i++){
86756     Expr *p = pEList->a[i].pExpr;
86757     const char *zType;
86758 #ifdef SQLITE_ENABLE_COLUMN_METADATA
86759     const char *zOrigDb = 0;
86760     const char *zOrigTab = 0;
86761     const char *zOrigCol = 0;
86762     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
86763
86764     /* The vdbe must make its own copy of the column-type and other 
86765     ** column specific strings, in case the schema is reset before this
86766     ** virtual machine is deleted.
86767     */
86768     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
86769     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
86770     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
86771 #else
86772     zType = columnType(&sNC, p, 0, 0, 0);
86773 #endif
86774     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
86775   }
86776 #endif /* SQLITE_OMIT_DECLTYPE */
86777 }
86778
86779 /*
86780 ** Generate code that will tell the VDBE the names of columns
86781 ** in the result set.  This information is used to provide the
86782 ** azCol[] values in the callback.
86783 */
86784 static void generateColumnNames(
86785   Parse *pParse,      /* Parser context */
86786   SrcList *pTabList,  /* List of tables */
86787   ExprList *pEList    /* Expressions defining the result set */
86788 ){
86789   Vdbe *v = pParse->pVdbe;
86790   int i, j;
86791   sqlite3 *db = pParse->db;
86792   int fullNames, shortNames;
86793
86794 #ifndef SQLITE_OMIT_EXPLAIN
86795   /* If this is an EXPLAIN, skip this step */
86796   if( pParse->explain ){
86797     return;
86798   }
86799 #endif
86800
86801   if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
86802   pParse->colNamesSet = 1;
86803   fullNames = (db->flags & SQLITE_FullColNames)!=0;
86804   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
86805   sqlite3VdbeSetNumCols(v, pEList->nExpr);
86806   for(i=0; i<pEList->nExpr; i++){
86807     Expr *p;
86808     p = pEList->a[i].pExpr;
86809     if( NEVER(p==0) ) continue;
86810     if( pEList->a[i].zName ){
86811       char *zName = pEList->a[i].zName;
86812       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
86813     }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
86814       Table *pTab;
86815       char *zCol;
86816       int iCol = p->iColumn;
86817       for(j=0; ALWAYS(j<pTabList->nSrc); j++){
86818         if( pTabList->a[j].iCursor==p->iTable ) break;
86819       }
86820       assert( j<pTabList->nSrc );
86821       pTab = pTabList->a[j].pTab;
86822       if( iCol<0 ) iCol = pTab->iPKey;
86823       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
86824       if( iCol<0 ){
86825         zCol = "rowid";
86826       }else{
86827         zCol = pTab->aCol[iCol].zName;
86828       }
86829       if( !shortNames && !fullNames ){
86830         sqlite3VdbeSetColName(v, i, COLNAME_NAME, 
86831             sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
86832       }else if( fullNames ){
86833         char *zName = 0;
86834         zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
86835         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
86836       }else{
86837         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
86838       }
86839     }else{
86840       sqlite3VdbeSetColName(v, i, COLNAME_NAME, 
86841           sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
86842     }
86843   }
86844   generateColumnTypes(pParse, pTabList, pEList);
86845 }
86846
86847 #ifndef SQLITE_OMIT_COMPOUND_SELECT
86848 /*
86849 ** Name of the connection operator, used for error messages.
86850 */
86851 static const char *selectOpName(int id){
86852   char *z;
86853   switch( id ){
86854     case TK_ALL:       z = "UNION ALL";   break;
86855     case TK_INTERSECT: z = "INTERSECT";   break;
86856     case TK_EXCEPT:    z = "EXCEPT";      break;
86857     default:           z = "UNION";       break;
86858   }
86859   return z;
86860 }
86861 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
86862
86863 /*
86864 ** Given a an expression list (which is really the list of expressions
86865 ** that form the result set of a SELECT statement) compute appropriate
86866 ** column names for a table that would hold the expression list.
86867 **
86868 ** All column names will be unique.
86869 **
86870 ** Only the column names are computed.  Column.zType, Column.zColl,
86871 ** and other fields of Column are zeroed.
86872 **
86873 ** Return SQLITE_OK on success.  If a memory allocation error occurs,
86874 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
86875 */
86876 static int selectColumnsFromExprList(
86877   Parse *pParse,          /* Parsing context */
86878   ExprList *pEList,       /* Expr list from which to derive column names */
86879   int *pnCol,             /* Write the number of columns here */
86880   Column **paCol          /* Write the new column list here */
86881 ){
86882   sqlite3 *db = pParse->db;   /* Database connection */
86883   int i, j;                   /* Loop counters */
86884   int cnt;                    /* Index added to make the name unique */
86885   Column *aCol, *pCol;        /* For looping over result columns */
86886   int nCol;                   /* Number of columns in the result set */
86887   Expr *p;                    /* Expression for a single result column */
86888   char *zName;                /* Column name */
86889   int nName;                  /* Size of name in zName[] */
86890
86891   *pnCol = nCol = pEList->nExpr;
86892   aCol = *paCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
86893   if( aCol==0 ) return SQLITE_NOMEM;
86894   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
86895     /* Get an appropriate name for the column
86896     */
86897     p = pEList->a[i].pExpr;
86898     assert( p->pRight==0 || ExprHasProperty(p->pRight, EP_IntValue)
86899                || p->pRight->u.zToken==0 || p->pRight->u.zToken[0]!=0 );
86900     if( (zName = pEList->a[i].zName)!=0 ){
86901       /* If the column contains an "AS <name>" phrase, use <name> as the name */
86902       zName = sqlite3DbStrDup(db, zName);
86903     }else{
86904       Expr *pColExpr = p;  /* The expression that is the result column name */
86905       Table *pTab;         /* Table associated with this expression */
86906       while( pColExpr->op==TK_DOT ) pColExpr = pColExpr->pRight;
86907       if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
86908         /* For columns use the column name name */
86909         int iCol = pColExpr->iColumn;
86910         pTab = pColExpr->pTab;
86911         if( iCol<0 ) iCol = pTab->iPKey;
86912         zName = sqlite3MPrintf(db, "%s",
86913                  iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
86914       }else if( pColExpr->op==TK_ID ){
86915         assert( !ExprHasProperty(pColExpr, EP_IntValue) );
86916         zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
86917       }else{
86918         /* Use the original text of the column expression as its name */
86919         zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
86920       }
86921     }
86922     if( db->mallocFailed ){
86923       sqlite3DbFree(db, zName);
86924       break;
86925     }
86926
86927     /* Make sure the column name is unique.  If the name is not unique,
86928     ** append a integer to the name so that it becomes unique.
86929     */
86930     nName = sqlite3Strlen30(zName);
86931     for(j=cnt=0; j<i; j++){
86932       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
86933         char *zNewName;
86934         zName[nName] = 0;
86935         zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
86936         sqlite3DbFree(db, zName);
86937         zName = zNewName;
86938         j = -1;
86939         if( zName==0 ) break;
86940       }
86941     }
86942     pCol->zName = zName;
86943   }
86944   if( db->mallocFailed ){
86945     for(j=0; j<i; j++){
86946       sqlite3DbFree(db, aCol[j].zName);
86947     }
86948     sqlite3DbFree(db, aCol);
86949     *paCol = 0;
86950     *pnCol = 0;
86951     return SQLITE_NOMEM;
86952   }
86953   return SQLITE_OK;
86954 }
86955
86956 /*
86957 ** Add type and collation information to a column list based on
86958 ** a SELECT statement.
86959 ** 
86960 ** The column list presumably came from selectColumnNamesFromExprList().
86961 ** The column list has only names, not types or collations.  This
86962 ** routine goes through and adds the types and collations.
86963 **
86964 ** This routine requires that all identifiers in the SELECT
86965 ** statement be resolved.
86966 */
86967 static void selectAddColumnTypeAndCollation(
86968   Parse *pParse,        /* Parsing contexts */
86969   int nCol,             /* Number of columns */
86970   Column *aCol,         /* List of columns */
86971   Select *pSelect       /* SELECT used to determine types and collations */
86972 ){
86973   sqlite3 *db = pParse->db;
86974   NameContext sNC;
86975   Column *pCol;
86976   CollSeq *pColl;
86977   int i;
86978   Expr *p;
86979   struct ExprList_item *a;
86980
86981   assert( pSelect!=0 );
86982   assert( (pSelect->selFlags & SF_Resolved)!=0 );
86983   assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
86984   if( db->mallocFailed ) return;
86985   memset(&sNC, 0, sizeof(sNC));
86986   sNC.pSrcList = pSelect->pSrc;
86987   a = pSelect->pEList->a;
86988   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
86989     p = a[i].pExpr;
86990     pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
86991     pCol->affinity = sqlite3ExprAffinity(p);
86992     if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
86993     pColl = sqlite3ExprCollSeq(pParse, p);
86994     if( pColl ){
86995       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
86996     }
86997   }
86998 }
86999
87000 /*
87001 ** Given a SELECT statement, generate a Table structure that describes
87002 ** the result set of that SELECT.
87003 */
87004 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
87005   Table *pTab;
87006   sqlite3 *db = pParse->db;
87007   int savedFlags;
87008
87009   savedFlags = db->flags;
87010   db->flags &= ~SQLITE_FullColNames;
87011   db->flags |= SQLITE_ShortColNames;
87012   sqlite3SelectPrep(pParse, pSelect, 0);
87013   if( pParse->nErr ) return 0;
87014   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
87015   db->flags = savedFlags;
87016   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
87017   if( pTab==0 ){
87018     return 0;
87019   }
87020   /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
87021   ** is disabled, so we might as well hard-code pTab->dbMem to NULL. */
87022   assert( db->lookaside.bEnabled==0 );
87023   pTab->dbMem = 0;
87024   pTab->nRef = 1;
87025   pTab->zName = 0;
87026   selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
87027   selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
87028   pTab->iPKey = -1;
87029   if( db->mallocFailed ){
87030     sqlite3DeleteTable(pTab);
87031     return 0;
87032   }
87033   return pTab;
87034 }
87035
87036 /*
87037 ** Get a VDBE for the given parser context.  Create a new one if necessary.
87038 ** If an error occurs, return NULL and leave a message in pParse.
87039 */
87040 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
87041   Vdbe *v = pParse->pVdbe;
87042   if( v==0 ){
87043     v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
87044 #ifndef SQLITE_OMIT_TRACE
87045     if( v ){
87046       sqlite3VdbeAddOp0(v, OP_Trace);
87047     }
87048 #endif
87049   }
87050   return v;
87051 }
87052
87053
87054 /*
87055 ** Compute the iLimit and iOffset fields of the SELECT based on the
87056 ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
87057 ** that appear in the original SQL statement after the LIMIT and OFFSET
87058 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset 
87059 ** are the integer memory register numbers for counters used to compute 
87060 ** the limit and offset.  If there is no limit and/or offset, then 
87061 ** iLimit and iOffset are negative.
87062 **
87063 ** This routine changes the values of iLimit and iOffset only if
87064 ** a limit or offset is defined by pLimit and pOffset.  iLimit and
87065 ** iOffset should have been preset to appropriate default values
87066 ** (usually but not always -1) prior to calling this routine.
87067 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
87068 ** redefined.  The UNION ALL operator uses this property to force
87069 ** the reuse of the same limit and offset registers across multiple
87070 ** SELECT statements.
87071 */
87072 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
87073   Vdbe *v = 0;
87074   int iLimit = 0;
87075   int iOffset;
87076   int addr1, n;
87077   if( p->iLimit ) return;
87078
87079   /* 
87080   ** "LIMIT -1" always shows all rows.  There is some
87081   ** contraversy about what the correct behavior should be.
87082   ** The current implementation interprets "LIMIT 0" to mean
87083   ** no rows.
87084   */
87085   sqlite3ExprCacheClear(pParse);
87086   assert( p->pOffset==0 || p->pLimit!=0 );
87087   if( p->pLimit ){
87088     p->iLimit = iLimit = ++pParse->nMem;
87089     v = sqlite3GetVdbe(pParse);
87090     if( NEVER(v==0) ) return;  /* VDBE should have already been allocated */
87091     if( sqlite3ExprIsInteger(p->pLimit, &n) ){
87092       sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
87093       VdbeComment((v, "LIMIT counter"));
87094       if( n==0 ){
87095         sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
87096       }
87097     }else{
87098       sqlite3ExprCode(pParse, p->pLimit, iLimit);
87099       sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
87100       VdbeComment((v, "LIMIT counter"));
87101       sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
87102     }
87103     if( p->pOffset ){
87104       p->iOffset = iOffset = ++pParse->nMem;
87105       pParse->nMem++;   /* Allocate an extra register for limit+offset */
87106       sqlite3ExprCode(pParse, p->pOffset, iOffset);
87107       sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
87108       VdbeComment((v, "OFFSET counter"));
87109       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
87110       sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
87111       sqlite3VdbeJumpHere(v, addr1);
87112       sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
87113       VdbeComment((v, "LIMIT+OFFSET"));
87114       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
87115       sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
87116       sqlite3VdbeJumpHere(v, addr1);
87117     }
87118   }
87119 }
87120
87121 #ifndef SQLITE_OMIT_COMPOUND_SELECT
87122 /*
87123 ** Return the appropriate collating sequence for the iCol-th column of
87124 ** the result set for the compound-select statement "p".  Return NULL if
87125 ** the column has no default collating sequence.
87126 **
87127 ** The collating sequence for the compound select is taken from the
87128 ** left-most term of the select that has a collating sequence.
87129 */
87130 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
87131   CollSeq *pRet;
87132   if( p->pPrior ){
87133     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
87134   }else{
87135     pRet = 0;
87136   }
87137   assert( iCol>=0 );
87138   if( pRet==0 && iCol<p->pEList->nExpr ){
87139     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
87140   }
87141   return pRet;
87142 }
87143 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
87144
87145 /* Forward reference */
87146 static int multiSelectOrderBy(
87147   Parse *pParse,        /* Parsing context */
87148   Select *p,            /* The right-most of SELECTs to be coded */
87149   SelectDest *pDest     /* What to do with query results */
87150 );
87151
87152
87153 #ifndef SQLITE_OMIT_COMPOUND_SELECT
87154 /*
87155 ** This routine is called to process a compound query form from
87156 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
87157 ** INTERSECT
87158 **
87159 ** "p" points to the right-most of the two queries.  the query on the
87160 ** left is p->pPrior.  The left query could also be a compound query
87161 ** in which case this routine will be called recursively. 
87162 **
87163 ** The results of the total query are to be written into a destination
87164 ** of type eDest with parameter iParm.
87165 **
87166 ** Example 1:  Consider a three-way compound SQL statement.
87167 **
87168 **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
87169 **
87170 ** This statement is parsed up as follows:
87171 **
87172 **     SELECT c FROM t3
87173 **      |
87174 **      `----->  SELECT b FROM t2
87175 **                |
87176 **                `------>  SELECT a FROM t1
87177 **
87178 ** The arrows in the diagram above represent the Select.pPrior pointer.
87179 ** So if this routine is called with p equal to the t3 query, then
87180 ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
87181 **
87182 ** Notice that because of the way SQLite parses compound SELECTs, the
87183 ** individual selects always group from left to right.
87184 */
87185 static int multiSelect(
87186   Parse *pParse,        /* Parsing context */
87187   Select *p,            /* The right-most of SELECTs to be coded */
87188   SelectDest *pDest     /* What to do with query results */
87189 ){
87190   int rc = SQLITE_OK;   /* Success code from a subroutine */
87191   Select *pPrior;       /* Another SELECT immediately to our left */
87192   Vdbe *v;              /* Generate code to this VDBE */
87193   SelectDest dest;      /* Alternative data destination */
87194   Select *pDelete = 0;  /* Chain of simple selects to delete */
87195   sqlite3 *db;          /* Database connection */
87196
87197   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
87198   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
87199   */
87200   assert( p && p->pPrior );  /* Calling function guarantees this much */
87201   db = pParse->db;
87202   pPrior = p->pPrior;
87203   assert( pPrior->pRightmost!=pPrior );
87204   assert( pPrior->pRightmost==p->pRightmost );
87205   dest = *pDest;
87206   if( pPrior->pOrderBy ){
87207     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
87208       selectOpName(p->op));
87209     rc = 1;
87210     goto multi_select_end;
87211   }
87212   if( pPrior->pLimit ){
87213     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
87214       selectOpName(p->op));
87215     rc = 1;
87216     goto multi_select_end;
87217   }
87218
87219   v = sqlite3GetVdbe(pParse);
87220   assert( v!=0 );  /* The VDBE already created by calling function */
87221
87222   /* Create the destination temporary table if necessary
87223   */
87224   if( dest.eDest==SRT_EphemTab ){
87225     assert( p->pEList );
87226     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr);
87227     dest.eDest = SRT_Table;
87228   }
87229
87230   /* Make sure all SELECTs in the statement have the same number of elements
87231   ** in their result sets.
87232   */
87233   assert( p->pEList && pPrior->pEList );
87234   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
87235     sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
87236       " do not have the same number of result columns", selectOpName(p->op));
87237     rc = 1;
87238     goto multi_select_end;
87239   }
87240
87241   /* Compound SELECTs that have an ORDER BY clause are handled separately.
87242   */
87243   if( p->pOrderBy ){
87244     return multiSelectOrderBy(pParse, p, pDest);
87245   }
87246
87247   /* Generate code for the left and right SELECT statements.
87248   */
87249   switch( p->op ){
87250     case TK_ALL: {
87251       int addr = 0;
87252       assert( !pPrior->pLimit );
87253       pPrior->pLimit = p->pLimit;
87254       pPrior->pOffset = p->pOffset;
87255       rc = sqlite3Select(pParse, pPrior, &dest);
87256       p->pLimit = 0;
87257       p->pOffset = 0;
87258       if( rc ){
87259         goto multi_select_end;
87260       }
87261       p->pPrior = 0;
87262       p->iLimit = pPrior->iLimit;
87263       p->iOffset = pPrior->iOffset;
87264       if( p->iLimit ){
87265         addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
87266         VdbeComment((v, "Jump ahead if LIMIT reached"));
87267       }
87268       rc = sqlite3Select(pParse, p, &dest);
87269       testcase( rc!=SQLITE_OK );
87270       pDelete = p->pPrior;
87271       p->pPrior = pPrior;
87272       if( addr ){
87273         sqlite3VdbeJumpHere(v, addr);
87274       }
87275       break;
87276     }
87277     case TK_EXCEPT:
87278     case TK_UNION: {
87279       int unionTab;    /* Cursor number of the temporary table holding result */
87280       u8 op = 0;       /* One of the SRT_ operations to apply to self */
87281       int priorOp;     /* The SRT_ operation to apply to prior selects */
87282       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
87283       int addr;
87284       SelectDest uniondest;
87285
87286       testcase( p->op==TK_EXCEPT );
87287       testcase( p->op==TK_UNION );
87288       priorOp = SRT_Union;
87289       if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
87290         /* We can reuse a temporary table generated by a SELECT to our
87291         ** right.
87292         */
87293         assert( p->pRightmost!=p );  /* Can only happen for leftward elements
87294                                      ** of a 3-way or more compound */
87295         assert( p->pLimit==0 );      /* Not allowed on leftward elements */
87296         assert( p->pOffset==0 );     /* Not allowed on leftward elements */
87297         unionTab = dest.iParm;
87298       }else{
87299         /* We will need to create our own temporary table to hold the
87300         ** intermediate results.
87301         */
87302         unionTab = pParse->nTab++;
87303         assert( p->pOrderBy==0 );
87304         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
87305         assert( p->addrOpenEphm[0] == -1 );
87306         p->addrOpenEphm[0] = addr;
87307         p->pRightmost->selFlags |= SF_UsesEphemeral;
87308         assert( p->pEList );
87309       }
87310
87311       /* Code the SELECT statements to our left
87312       */
87313       assert( !pPrior->pOrderBy );
87314       sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
87315       rc = sqlite3Select(pParse, pPrior, &uniondest);
87316       if( rc ){
87317         goto multi_select_end;
87318       }
87319
87320       /* Code the current SELECT statement
87321       */
87322       if( p->op==TK_EXCEPT ){
87323         op = SRT_Except;
87324       }else{
87325         assert( p->op==TK_UNION );
87326         op = SRT_Union;
87327       }
87328       p->pPrior = 0;
87329       pLimit = p->pLimit;
87330       p->pLimit = 0;
87331       pOffset = p->pOffset;
87332       p->pOffset = 0;
87333       uniondest.eDest = op;
87334       rc = sqlite3Select(pParse, p, &uniondest);
87335       testcase( rc!=SQLITE_OK );
87336       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
87337       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
87338       sqlite3ExprListDelete(db, p->pOrderBy);
87339       pDelete = p->pPrior;
87340       p->pPrior = pPrior;
87341       p->pOrderBy = 0;
87342       sqlite3ExprDelete(db, p->pLimit);
87343       p->pLimit = pLimit;
87344       p->pOffset = pOffset;
87345       p->iLimit = 0;
87346       p->iOffset = 0;
87347
87348       /* Convert the data in the temporary table into whatever form
87349       ** it is that we currently need.
87350       */
87351       assert( unionTab==dest.iParm || dest.eDest!=priorOp );
87352       if( dest.eDest!=priorOp ){
87353         int iCont, iBreak, iStart;
87354         assert( p->pEList );
87355         if( dest.eDest==SRT_Output ){
87356           Select *pFirst = p;
87357           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
87358           generateColumnNames(pParse, 0, pFirst->pEList);
87359         }
87360         iBreak = sqlite3VdbeMakeLabel(v);
87361         iCont = sqlite3VdbeMakeLabel(v);
87362         computeLimitRegisters(pParse, p, iBreak);
87363         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
87364         iStart = sqlite3VdbeCurrentAddr(v);
87365         selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
87366                         0, -1, &dest, iCont, iBreak);
87367         sqlite3VdbeResolveLabel(v, iCont);
87368         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
87369         sqlite3VdbeResolveLabel(v, iBreak);
87370         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
87371       }
87372       break;
87373     }
87374     default: assert( p->op==TK_INTERSECT ); {
87375       int tab1, tab2;
87376       int iCont, iBreak, iStart;
87377       Expr *pLimit, *pOffset;
87378       int addr;
87379       SelectDest intersectdest;
87380       int r1;
87381
87382       /* INTERSECT is different from the others since it requires
87383       ** two temporary tables.  Hence it has its own case.  Begin
87384       ** by allocating the tables we will need.
87385       */
87386       tab1 = pParse->nTab++;
87387       tab2 = pParse->nTab++;
87388       assert( p->pOrderBy==0 );
87389
87390       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
87391       assert( p->addrOpenEphm[0] == -1 );
87392       p->addrOpenEphm[0] = addr;
87393       p->pRightmost->selFlags |= SF_UsesEphemeral;
87394       assert( p->pEList );
87395
87396       /* Code the SELECTs to our left into temporary table "tab1".
87397       */
87398       sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
87399       rc = sqlite3Select(pParse, pPrior, &intersectdest);
87400       if( rc ){
87401         goto multi_select_end;
87402       }
87403
87404       /* Code the current SELECT into temporary table "tab2"
87405       */
87406       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
87407       assert( p->addrOpenEphm[1] == -1 );
87408       p->addrOpenEphm[1] = addr;
87409       p->pPrior = 0;
87410       pLimit = p->pLimit;
87411       p->pLimit = 0;
87412       pOffset = p->pOffset;
87413       p->pOffset = 0;
87414       intersectdest.iParm = tab2;
87415       rc = sqlite3Select(pParse, p, &intersectdest);
87416       testcase( rc!=SQLITE_OK );
87417       pDelete = p->pPrior;
87418       p->pPrior = pPrior;
87419       sqlite3ExprDelete(db, p->pLimit);
87420       p->pLimit = pLimit;
87421       p->pOffset = pOffset;
87422
87423       /* Generate code to take the intersection of the two temporary
87424       ** tables.
87425       */
87426       assert( p->pEList );
87427       if( dest.eDest==SRT_Output ){
87428         Select *pFirst = p;
87429         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
87430         generateColumnNames(pParse, 0, pFirst->pEList);
87431       }
87432       iBreak = sqlite3VdbeMakeLabel(v);
87433       iCont = sqlite3VdbeMakeLabel(v);
87434       computeLimitRegisters(pParse, p, iBreak);
87435       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
87436       r1 = sqlite3GetTempReg(pParse);
87437       iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
87438       sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
87439       sqlite3ReleaseTempReg(pParse, r1);
87440       selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
87441                       0, -1, &dest, iCont, iBreak);
87442       sqlite3VdbeResolveLabel(v, iCont);
87443       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
87444       sqlite3VdbeResolveLabel(v, iBreak);
87445       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
87446       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
87447       break;
87448     }
87449   }
87450
87451   /* Compute collating sequences used by 
87452   ** temporary tables needed to implement the compound select.
87453   ** Attach the KeyInfo structure to all temporary tables.
87454   **
87455   ** This section is run by the right-most SELECT statement only.
87456   ** SELECT statements to the left always skip this part.  The right-most
87457   ** SELECT might also skip this part if it has no ORDER BY clause and
87458   ** no temp tables are required.
87459   */
87460   if( p->selFlags & SF_UsesEphemeral ){
87461     int i;                        /* Loop counter */
87462     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
87463     Select *pLoop;                /* For looping through SELECT statements */
87464     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
87465     int nCol;                     /* Number of columns in result set */
87466
87467     assert( p->pRightmost==p );
87468     nCol = p->pEList->nExpr;
87469     pKeyInfo = sqlite3DbMallocZero(db,
87470                        sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
87471     if( !pKeyInfo ){
87472       rc = SQLITE_NOMEM;
87473       goto multi_select_end;
87474     }
87475
87476     pKeyInfo->enc = ENC(db);
87477     pKeyInfo->nField = (u16)nCol;
87478
87479     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
87480       *apColl = multiSelectCollSeq(pParse, p, i);
87481       if( 0==*apColl ){
87482         *apColl = db->pDfltColl;
87483       }
87484     }
87485
87486     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
87487       for(i=0; i<2; i++){
87488         int addr = pLoop->addrOpenEphm[i];
87489         if( addr<0 ){
87490           /* If [0] is unused then [1] is also unused.  So we can
87491           ** always safely abort as soon as the first unused slot is found */
87492           assert( pLoop->addrOpenEphm[1]<0 );
87493           break;
87494         }
87495         sqlite3VdbeChangeP2(v, addr, nCol);
87496         sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
87497         pLoop->addrOpenEphm[i] = -1;
87498       }
87499     }
87500     sqlite3DbFree(db, pKeyInfo);
87501   }
87502
87503 multi_select_end:
87504   pDest->iMem = dest.iMem;
87505   pDest->nMem = dest.nMem;
87506   sqlite3SelectDelete(db, pDelete);
87507   return rc;
87508 }
87509 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
87510
87511 /*
87512 ** Code an output subroutine for a coroutine implementation of a
87513 ** SELECT statment.
87514 **
87515 ** The data to be output is contained in pIn->iMem.  There are
87516 ** pIn->nMem columns to be output.  pDest is where the output should
87517 ** be sent.
87518 **
87519 ** regReturn is the number of the register holding the subroutine
87520 ** return address.
87521 **
87522 ** If regPrev>0 then it is a the first register in a vector that
87523 ** records the previous output.  mem[regPrev] is a flag that is false
87524 ** if there has been no previous output.  If regPrev>0 then code is
87525 ** generated to suppress duplicates.  pKeyInfo is used for comparing
87526 ** keys.
87527 **
87528 ** If the LIMIT found in p->iLimit is reached, jump immediately to
87529 ** iBreak.
87530 */
87531 static int generateOutputSubroutine(
87532   Parse *pParse,          /* Parsing context */
87533   Select *p,              /* The SELECT statement */
87534   SelectDest *pIn,        /* Coroutine supplying data */
87535   SelectDest *pDest,      /* Where to send the data */
87536   int regReturn,          /* The return address register */
87537   int regPrev,            /* Previous result register.  No uniqueness if 0 */
87538   KeyInfo *pKeyInfo,      /* For comparing with previous entry */
87539   int p4type,             /* The p4 type for pKeyInfo */
87540   int iBreak              /* Jump here if we hit the LIMIT */
87541 ){
87542   Vdbe *v = pParse->pVdbe;
87543   int iContinue;
87544   int addr;
87545
87546   addr = sqlite3VdbeCurrentAddr(v);
87547   iContinue = sqlite3VdbeMakeLabel(v);
87548
87549   /* Suppress duplicates for UNION, EXCEPT, and INTERSECT 
87550   */
87551   if( regPrev ){
87552     int j1, j2;
87553     j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
87554     j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iMem, regPrev+1, pIn->nMem,
87555                               (char*)pKeyInfo, p4type);
87556     sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
87557     sqlite3VdbeJumpHere(v, j1);
87558     sqlite3ExprCodeCopy(pParse, pIn->iMem, regPrev+1, pIn->nMem);
87559     sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
87560   }
87561   if( pParse->db->mallocFailed ) return 0;
87562
87563   /* Suppress the the first OFFSET entries if there is an OFFSET clause
87564   */
87565   codeOffset(v, p, iContinue);
87566
87567   switch( pDest->eDest ){
87568     /* Store the result as data using a unique key.
87569     */
87570     case SRT_Table:
87571     case SRT_EphemTab: {
87572       int r1 = sqlite3GetTempReg(pParse);
87573       int r2 = sqlite3GetTempReg(pParse);
87574       testcase( pDest->eDest==SRT_Table );
87575       testcase( pDest->eDest==SRT_EphemTab );
87576       sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iMem, pIn->nMem, r1);
87577       sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iParm, r2);
87578       sqlite3VdbeAddOp3(v, OP_Insert, pDest->iParm, r1, r2);
87579       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
87580       sqlite3ReleaseTempReg(pParse, r2);
87581       sqlite3ReleaseTempReg(pParse, r1);
87582       break;
87583     }
87584
87585 #ifndef SQLITE_OMIT_SUBQUERY
87586     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
87587     ** then there should be a single item on the stack.  Write this
87588     ** item into the set table with bogus data.
87589     */
87590     case SRT_Set: {
87591       int r1;
87592       assert( pIn->nMem==1 );
87593       p->affinity = 
87594          sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affinity);
87595       r1 = sqlite3GetTempReg(pParse);
87596       sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iMem, 1, r1, &p->affinity, 1);
87597       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, 1);
87598       sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iParm, r1);
87599       sqlite3ReleaseTempReg(pParse, r1);
87600       break;
87601     }
87602
87603 #if 0  /* Never occurs on an ORDER BY query */
87604     /* If any row exist in the result set, record that fact and abort.
87605     */
87606     case SRT_Exists: {
87607       sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iParm);
87608       /* The LIMIT clause will terminate the loop for us */
87609       break;
87610     }
87611 #endif
87612
87613     /* If this is a scalar select that is part of an expression, then
87614     ** store the results in the appropriate memory cell and break out
87615     ** of the scan loop.
87616     */
87617     case SRT_Mem: {
87618       assert( pIn->nMem==1 );
87619       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iParm, 1);
87620       /* The LIMIT clause will jump out of the loop for us */
87621       break;
87622     }
87623 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
87624
87625     /* The results are stored in a sequence of registers
87626     ** starting at pDest->iMem.  Then the co-routine yields.
87627     */
87628     case SRT_Coroutine: {
87629       if( pDest->iMem==0 ){
87630         pDest->iMem = sqlite3GetTempRange(pParse, pIn->nMem);
87631         pDest->nMem = pIn->nMem;
87632       }
87633       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iMem, pDest->nMem);
87634       sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
87635       break;
87636     }
87637
87638     /* If none of the above, then the result destination must be
87639     ** SRT_Output.  This routine is never called with any other
87640     ** destination other than the ones handled above or SRT_Output.
87641     **
87642     ** For SRT_Output, results are stored in a sequence of registers.  
87643     ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
87644     ** return the next row of result.
87645     */
87646     default: {
87647       assert( pDest->eDest==SRT_Output );
87648       sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iMem, pIn->nMem);
87649       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, pIn->nMem);
87650       break;
87651     }
87652   }
87653
87654   /* Jump to the end of the loop if the LIMIT is reached.
87655   */
87656   if( p->iLimit ){
87657     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
87658   }
87659
87660   /* Generate the subroutine return
87661   */
87662   sqlite3VdbeResolveLabel(v, iContinue);
87663   sqlite3VdbeAddOp1(v, OP_Return, regReturn);
87664
87665   return addr;
87666 }
87667
87668 /*
87669 ** Alternative compound select code generator for cases when there
87670 ** is an ORDER BY clause.
87671 **
87672 ** We assume a query of the following form:
87673 **
87674 **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
87675 **
87676 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
87677 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
87678 ** co-routines.  Then run the co-routines in parallel and merge the results
87679 ** into the output.  In addition to the two coroutines (called selectA and
87680 ** selectB) there are 7 subroutines:
87681 **
87682 **    outA:    Move the output of the selectA coroutine into the output
87683 **             of the compound query.
87684 **
87685 **    outB:    Move the output of the selectB coroutine into the output
87686 **             of the compound query.  (Only generated for UNION and
87687 **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
87688 **             appears only in B.)
87689 **
87690 **    AltB:    Called when there is data from both coroutines and A<B.
87691 **
87692 **    AeqB:    Called when there is data from both coroutines and A==B.
87693 **
87694 **    AgtB:    Called when there is data from both coroutines and A>B.
87695 **
87696 **    EofA:    Called when data is exhausted from selectA.
87697 **
87698 **    EofB:    Called when data is exhausted from selectB.
87699 **
87700 ** The implementation of the latter five subroutines depend on which 
87701 ** <operator> is used:
87702 **
87703 **
87704 **             UNION ALL         UNION            EXCEPT          INTERSECT
87705 **          -------------  -----------------  --------------  -----------------
87706 **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
87707 **
87708 **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
87709 **
87710 **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
87711 **
87712 **   EofA:   outB, nextB      outB, nextB          halt             halt
87713 **
87714 **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
87715 **
87716 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
87717 ** causes an immediate jump to EofA and an EOF on B following nextB causes
87718 ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
87719 ** following nextX causes a jump to the end of the select processing.
87720 **
87721 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
87722 ** within the output subroutine.  The regPrev register set holds the previously
87723 ** output value.  A comparison is made against this value and the output
87724 ** is skipped if the next results would be the same as the previous.
87725 **
87726 ** The implementation plan is to implement the two coroutines and seven
87727 ** subroutines first, then put the control logic at the bottom.  Like this:
87728 **
87729 **          goto Init
87730 **     coA: coroutine for left query (A)
87731 **     coB: coroutine for right query (B)
87732 **    outA: output one row of A
87733 **    outB: output one row of B (UNION and UNION ALL only)
87734 **    EofA: ...
87735 **    EofB: ...
87736 **    AltB: ...
87737 **    AeqB: ...
87738 **    AgtB: ...
87739 **    Init: initialize coroutine registers
87740 **          yield coA
87741 **          if eof(A) goto EofA
87742 **          yield coB
87743 **          if eof(B) goto EofB
87744 **    Cmpr: Compare A, B
87745 **          Jump AltB, AeqB, AgtB
87746 **     End: ...
87747 **
87748 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
87749 ** actually called using Gosub and they do not Return.  EofA and EofB loop
87750 ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
87751 ** and AgtB jump to either L2 or to one of EofA or EofB.
87752 */
87753 #ifndef SQLITE_OMIT_COMPOUND_SELECT
87754 static int multiSelectOrderBy(
87755   Parse *pParse,        /* Parsing context */
87756   Select *p,            /* The right-most of SELECTs to be coded */
87757   SelectDest *pDest     /* What to do with query results */
87758 ){
87759   int i, j;             /* Loop counters */
87760   Select *pPrior;       /* Another SELECT immediately to our left */
87761   Vdbe *v;              /* Generate code to this VDBE */
87762   SelectDest destA;     /* Destination for coroutine A */
87763   SelectDest destB;     /* Destination for coroutine B */
87764   int regAddrA;         /* Address register for select-A coroutine */
87765   int regEofA;          /* Flag to indicate when select-A is complete */
87766   int regAddrB;         /* Address register for select-B coroutine */
87767   int regEofB;          /* Flag to indicate when select-B is complete */
87768   int addrSelectA;      /* Address of the select-A coroutine */
87769   int addrSelectB;      /* Address of the select-B coroutine */
87770   int regOutA;          /* Address register for the output-A subroutine */
87771   int regOutB;          /* Address register for the output-B subroutine */
87772   int addrOutA;         /* Address of the output-A subroutine */
87773   int addrOutB = 0;     /* Address of the output-B subroutine */
87774   int addrEofA;         /* Address of the select-A-exhausted subroutine */
87775   int addrEofB;         /* Address of the select-B-exhausted subroutine */
87776   int addrAltB;         /* Address of the A<B subroutine */
87777   int addrAeqB;         /* Address of the A==B subroutine */
87778   int addrAgtB;         /* Address of the A>B subroutine */
87779   int regLimitA;        /* Limit register for select-A */
87780   int regLimitB;        /* Limit register for select-A */
87781   int regPrev;          /* A range of registers to hold previous output */
87782   int savedLimit;       /* Saved value of p->iLimit */
87783   int savedOffset;      /* Saved value of p->iOffset */
87784   int labelCmpr;        /* Label for the start of the merge algorithm */
87785   int labelEnd;         /* Label for the end of the overall SELECT stmt */
87786   int j1;               /* Jump instructions that get retargetted */
87787   int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
87788   KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
87789   KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
87790   sqlite3 *db;          /* Database connection */
87791   ExprList *pOrderBy;   /* The ORDER BY clause */
87792   int nOrderBy;         /* Number of terms in the ORDER BY clause */
87793   int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
87794
87795   assert( p->pOrderBy!=0 );
87796   assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
87797   db = pParse->db;
87798   v = pParse->pVdbe;
87799   assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
87800   labelEnd = sqlite3VdbeMakeLabel(v);
87801   labelCmpr = sqlite3VdbeMakeLabel(v);
87802
87803
87804   /* Patch up the ORDER BY clause
87805   */
87806   op = p->op;  
87807   pPrior = p->pPrior;
87808   assert( pPrior->pOrderBy==0 );
87809   pOrderBy = p->pOrderBy;
87810   assert( pOrderBy );
87811   nOrderBy = pOrderBy->nExpr;
87812
87813   /* For operators other than UNION ALL we have to make sure that
87814   ** the ORDER BY clause covers every term of the result set.  Add
87815   ** terms to the ORDER BY clause as necessary.
87816   */
87817   if( op!=TK_ALL ){
87818     for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
87819       struct ExprList_item *pItem;
87820       for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
87821         assert( pItem->iCol>0 );
87822         if( pItem->iCol==i ) break;
87823       }
87824       if( j==nOrderBy ){
87825         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
87826         if( pNew==0 ) return SQLITE_NOMEM;
87827         pNew->flags |= EP_IntValue;
87828         pNew->u.iValue = i;
87829         pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
87830         pOrderBy->a[nOrderBy++].iCol = (u16)i;
87831       }
87832     }
87833   }
87834
87835   /* Compute the comparison permutation and keyinfo that is used with
87836   ** the permutation used to determine if the next
87837   ** row of results comes from selectA or selectB.  Also add explicit
87838   ** collations to the ORDER BY clause terms so that when the subqueries
87839   ** to the right and the left are evaluated, they use the correct
87840   ** collation.
87841   */
87842   aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
87843   if( aPermute ){
87844     struct ExprList_item *pItem;
87845     for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
87846       assert( pItem->iCol>0  && pItem->iCol<=p->pEList->nExpr );
87847       aPermute[i] = pItem->iCol - 1;
87848     }
87849     pKeyMerge =
87850       sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
87851     if( pKeyMerge ){
87852       pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
87853       pKeyMerge->nField = (u16)nOrderBy;
87854       pKeyMerge->enc = ENC(db);
87855       for(i=0; i<nOrderBy; i++){
87856         CollSeq *pColl;
87857         Expr *pTerm = pOrderBy->a[i].pExpr;
87858         if( pTerm->flags & EP_ExpCollate ){
87859           pColl = pTerm->pColl;
87860         }else{
87861           pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
87862           pTerm->flags |= EP_ExpCollate;
87863           pTerm->pColl = pColl;
87864         }
87865         pKeyMerge->aColl[i] = pColl;
87866         pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
87867       }
87868     }
87869   }else{
87870     pKeyMerge = 0;
87871   }
87872
87873   /* Reattach the ORDER BY clause to the query.
87874   */
87875   p->pOrderBy = pOrderBy;
87876   pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
87877
87878   /* Allocate a range of temporary registers and the KeyInfo needed
87879   ** for the logic that removes duplicate result rows when the
87880   ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
87881   */
87882   if( op==TK_ALL ){
87883     regPrev = 0;
87884   }else{
87885     int nExpr = p->pEList->nExpr;
87886     assert( nOrderBy>=nExpr || db->mallocFailed );
87887     regPrev = sqlite3GetTempRange(pParse, nExpr+1);
87888     sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
87889     pKeyDup = sqlite3DbMallocZero(db,
87890                   sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
87891     if( pKeyDup ){
87892       pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
87893       pKeyDup->nField = (u16)nExpr;
87894       pKeyDup->enc = ENC(db);
87895       for(i=0; i<nExpr; i++){
87896         pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
87897         pKeyDup->aSortOrder[i] = 0;
87898       }
87899     }
87900   }
87901  
87902   /* Separate the left and the right query from one another
87903   */
87904   p->pPrior = 0;
87905   pPrior->pRightmost = 0;
87906   sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
87907   if( pPrior->pPrior==0 ){
87908     sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
87909   }
87910
87911   /* Compute the limit registers */
87912   computeLimitRegisters(pParse, p, labelEnd);
87913   if( p->iLimit && op==TK_ALL ){
87914     regLimitA = ++pParse->nMem;
87915     regLimitB = ++pParse->nMem;
87916     sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
87917                                   regLimitA);
87918     sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
87919   }else{
87920     regLimitA = regLimitB = 0;
87921   }
87922   sqlite3ExprDelete(db, p->pLimit);
87923   p->pLimit = 0;
87924   sqlite3ExprDelete(db, p->pOffset);
87925   p->pOffset = 0;
87926
87927   regAddrA = ++pParse->nMem;
87928   regEofA = ++pParse->nMem;
87929   regAddrB = ++pParse->nMem;
87930   regEofB = ++pParse->nMem;
87931   regOutA = ++pParse->nMem;
87932   regOutB = ++pParse->nMem;
87933   sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
87934   sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
87935
87936   /* Jump past the various subroutines and coroutines to the main
87937   ** merge loop
87938   */
87939   j1 = sqlite3VdbeAddOp0(v, OP_Goto);
87940   addrSelectA = sqlite3VdbeCurrentAddr(v);
87941
87942
87943   /* Generate a coroutine to evaluate the SELECT statement to the
87944   ** left of the compound operator - the "A" select.
87945   */
87946   VdbeNoopComment((v, "Begin coroutine for left SELECT"));
87947   pPrior->iLimit = regLimitA;
87948   sqlite3Select(pParse, pPrior, &destA);
87949   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
87950   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
87951   VdbeNoopComment((v, "End coroutine for left SELECT"));
87952
87953   /* Generate a coroutine to evaluate the SELECT statement on 
87954   ** the right - the "B" select
87955   */
87956   addrSelectB = sqlite3VdbeCurrentAddr(v);
87957   VdbeNoopComment((v, "Begin coroutine for right SELECT"));
87958   savedLimit = p->iLimit;
87959   savedOffset = p->iOffset;
87960   p->iLimit = regLimitB;
87961   p->iOffset = 0;  
87962   sqlite3Select(pParse, p, &destB);
87963   p->iLimit = savedLimit;
87964   p->iOffset = savedOffset;
87965   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
87966   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
87967   VdbeNoopComment((v, "End coroutine for right SELECT"));
87968
87969   /* Generate a subroutine that outputs the current row of the A
87970   ** select as the next output row of the compound select.
87971   */
87972   VdbeNoopComment((v, "Output routine for A"));
87973   addrOutA = generateOutputSubroutine(pParse,
87974                  p, &destA, pDest, regOutA,
87975                  regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
87976   
87977   /* Generate a subroutine that outputs the current row of the B
87978   ** select as the next output row of the compound select.
87979   */
87980   if( op==TK_ALL || op==TK_UNION ){
87981     VdbeNoopComment((v, "Output routine for B"));
87982     addrOutB = generateOutputSubroutine(pParse,
87983                  p, &destB, pDest, regOutB,
87984                  regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
87985   }
87986
87987   /* Generate a subroutine to run when the results from select A
87988   ** are exhausted and only data in select B remains.
87989   */
87990   VdbeNoopComment((v, "eof-A subroutine"));
87991   if( op==TK_EXCEPT || op==TK_INTERSECT ){
87992     addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
87993   }else{  
87994     addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
87995     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
87996     sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
87997     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
87998   }
87999
88000   /* Generate a subroutine to run when the results from select B
88001   ** are exhausted and only data in select A remains.
88002   */
88003   if( op==TK_INTERSECT ){
88004     addrEofB = addrEofA;
88005   }else{  
88006     VdbeNoopComment((v, "eof-B subroutine"));
88007     addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
88008     sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
88009     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
88010     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
88011   }
88012
88013   /* Generate code to handle the case of A<B
88014   */
88015   VdbeNoopComment((v, "A-lt-B subroutine"));
88016   addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
88017   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
88018   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
88019   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
88020
88021   /* Generate code to handle the case of A==B
88022   */
88023   if( op==TK_ALL ){
88024     addrAeqB = addrAltB;
88025   }else if( op==TK_INTERSECT ){
88026     addrAeqB = addrAltB;
88027     addrAltB++;
88028   }else{
88029     VdbeNoopComment((v, "A-eq-B subroutine"));
88030     addrAeqB =
88031     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
88032     sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
88033     sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
88034   }
88035
88036   /* Generate code to handle the case of A>B
88037   */
88038   VdbeNoopComment((v, "A-gt-B subroutine"));
88039   addrAgtB = sqlite3VdbeCurrentAddr(v);
88040   if( op==TK_ALL || op==TK_UNION ){
88041     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
88042   }
88043   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
88044   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
88045   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
88046
88047   /* This code runs once to initialize everything.
88048   */
88049   sqlite3VdbeJumpHere(v, j1);
88050   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
88051   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
88052   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
88053   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
88054   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
88055   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
88056
88057   /* Implement the main merge loop
88058   */
88059   sqlite3VdbeResolveLabel(v, labelCmpr);
88060   sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
88061   sqlite3VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy,
88062                          (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
88063   sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
88064
88065   /* Release temporary registers
88066   */
88067   if( regPrev ){
88068     sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1);
88069   }
88070
88071   /* Jump to the this point in order to terminate the query.
88072   */
88073   sqlite3VdbeResolveLabel(v, labelEnd);
88074
88075   /* Set the number of output columns
88076   */
88077   if( pDest->eDest==SRT_Output ){
88078     Select *pFirst = pPrior;
88079     while( pFirst->pPrior ) pFirst = pFirst->pPrior;
88080     generateColumnNames(pParse, 0, pFirst->pEList);
88081   }
88082
88083   /* Reassembly the compound query so that it will be freed correctly
88084   ** by the calling function */
88085   if( p->pPrior ){
88086     sqlite3SelectDelete(db, p->pPrior);
88087   }
88088   p->pPrior = pPrior;
88089
88090   /*** TBD:  Insert subroutine calls to close cursors on incomplete
88091   **** subqueries ****/
88092   return SQLITE_OK;
88093 }
88094 #endif
88095
88096 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
88097 /* Forward Declarations */
88098 static void substExprList(sqlite3*, ExprList*, int, ExprList*);
88099 static void substSelect(sqlite3*, Select *, int, ExprList *);
88100
88101 /*
88102 ** Scan through the expression pExpr.  Replace every reference to
88103 ** a column in table number iTable with a copy of the iColumn-th
88104 ** entry in pEList.  (But leave references to the ROWID column 
88105 ** unchanged.)
88106 **
88107 ** This routine is part of the flattening procedure.  A subquery
88108 ** whose result set is defined by pEList appears as entry in the
88109 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
88110 ** FORM clause entry is iTable.  This routine make the necessary 
88111 ** changes to pExpr so that it refers directly to the source table
88112 ** of the subquery rather the result set of the subquery.
88113 */
88114 static Expr *substExpr(
88115   sqlite3 *db,        /* Report malloc errors to this connection */
88116   Expr *pExpr,        /* Expr in which substitution occurs */
88117   int iTable,         /* Table to be substituted */
88118   ExprList *pEList    /* Substitute expressions */
88119 ){
88120   if( pExpr==0 ) return 0;
88121   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
88122     if( pExpr->iColumn<0 ){
88123       pExpr->op = TK_NULL;
88124     }else{
88125       Expr *pNew;
88126       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
88127       assert( pExpr->pLeft==0 && pExpr->pRight==0 );
88128       pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
88129       if( pNew && pExpr->pColl ){
88130         pNew->pColl = pExpr->pColl;
88131       }
88132       sqlite3ExprDelete(db, pExpr);
88133       pExpr = pNew;
88134     }
88135   }else{
88136     pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
88137     pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
88138     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
88139       substSelect(db, pExpr->x.pSelect, iTable, pEList);
88140     }else{
88141       substExprList(db, pExpr->x.pList, iTable, pEList);
88142     }
88143   }
88144   return pExpr;
88145 }
88146 static void substExprList(
88147   sqlite3 *db,         /* Report malloc errors here */
88148   ExprList *pList,     /* List to scan and in which to make substitutes */
88149   int iTable,          /* Table to be substituted */
88150   ExprList *pEList     /* Substitute values */
88151 ){
88152   int i;
88153   if( pList==0 ) return;
88154   for(i=0; i<pList->nExpr; i++){
88155     pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
88156   }
88157 }
88158 static void substSelect(
88159   sqlite3 *db,         /* Report malloc errors here */
88160   Select *p,           /* SELECT statement in which to make substitutions */
88161   int iTable,          /* Table to be replaced */
88162   ExprList *pEList     /* Substitute values */
88163 ){
88164   SrcList *pSrc;
88165   struct SrcList_item *pItem;
88166   int i;
88167   if( !p ) return;
88168   substExprList(db, p->pEList, iTable, pEList);
88169   substExprList(db, p->pGroupBy, iTable, pEList);
88170   substExprList(db, p->pOrderBy, iTable, pEList);
88171   p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
88172   p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
88173   substSelect(db, p->pPrior, iTable, pEList);
88174   pSrc = p->pSrc;
88175   assert( pSrc );  /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
88176   if( ALWAYS(pSrc) ){
88177     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
88178       substSelect(db, pItem->pSelect, iTable, pEList);
88179     }
88180   }
88181 }
88182 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
88183
88184 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
88185 /*
88186 ** This routine attempts to flatten subqueries in order to speed
88187 ** execution.  It returns 1 if it makes changes and 0 if no flattening
88188 ** occurs.
88189 **
88190 ** To understand the concept of flattening, consider the following
88191 ** query:
88192 **
88193 **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
88194 **
88195 ** The default way of implementing this query is to execute the
88196 ** subquery first and store the results in a temporary table, then
88197 ** run the outer query on that temporary table.  This requires two
88198 ** passes over the data.  Furthermore, because the temporary table
88199 ** has no indices, the WHERE clause on the outer query cannot be
88200 ** optimized.
88201 **
88202 ** This routine attempts to rewrite queries such as the above into
88203 ** a single flat select, like this:
88204 **
88205 **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
88206 **
88207 ** The code generated for this simpification gives the same result
88208 ** but only has to scan the data once.  And because indices might 
88209 ** exist on the table t1, a complete scan of the data might be
88210 ** avoided.
88211 **
88212 ** Flattening is only attempted if all of the following are true:
88213 **
88214 **   (1)  The subquery and the outer query do not both use aggregates.
88215 **
88216 **   (2)  The subquery is not an aggregate or the outer query is not a join.
88217 **
88218 **   (3)  The subquery is not the right operand of a left outer join
88219 **        (Originally ticket #306.  Strenghtened by ticket #3300)
88220 **
88221 **   (4)  The subquery is not DISTINCT or the outer query is not a join.
88222 **
88223 **   (5)  The subquery is not DISTINCT or the outer query does not use
88224 **        aggregates.
88225 **
88226 **   (6)  The subquery does not use aggregates or the outer query is not
88227 **        DISTINCT.
88228 **
88229 **   (7)  The subquery has a FROM clause.
88230 **
88231 **   (8)  The subquery does not use LIMIT or the outer query is not a join.
88232 **
88233 **   (9)  The subquery does not use LIMIT or the outer query does not use
88234 **        aggregates.
88235 **
88236 **  (10)  The subquery does not use aggregates or the outer query does not
88237 **        use LIMIT.
88238 **
88239 **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
88240 **
88241 **  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
88242 **        a separate restriction deriving from ticket #350.
88243 **
88244 **  (13)  The subquery and outer query do not both use LIMIT
88245 **
88246 **  (14)  The subquery does not use OFFSET
88247 **
88248 **  (15)  The outer query is not part of a compound select or the
88249 **        subquery does not have a LIMIT clause.
88250 **        (See ticket #2339 and ticket [02a8e81d44]).
88251 **
88252 **  (16)  The outer query is not an aggregate or the subquery does
88253 **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
88254 **        until we introduced the group_concat() function.  
88255 **
88256 **  (17)  The sub-query is not a compound select, or it is a UNION ALL 
88257 **        compound clause made up entirely of non-aggregate queries, and 
88258 **        the parent query:
88259 **
88260 **          * is not itself part of a compound select,
88261 **          * is not an aggregate or DISTINCT query, and
88262 **          * has no other tables or sub-selects in the FROM clause.
88263 **
88264 **        The parent and sub-query may contain WHERE clauses. Subject to
88265 **        rules (11), (13) and (14), they may also contain ORDER BY,
88266 **        LIMIT and OFFSET clauses.
88267 **
88268 **  (18)  If the sub-query is a compound select, then all terms of the
88269 **        ORDER by clause of the parent must be simple references to 
88270 **        columns of the sub-query.
88271 **
88272 **  (19)  The subquery does not use LIMIT or the outer query does not
88273 **        have a WHERE clause.
88274 **
88275 **  (20)  If the sub-query is a compound select, then it must not use
88276 **        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
88277 **        somewhat by saying that the terms of the ORDER BY clause must
88278 **        appear as unmodified result columns in the outer query.  But
88279 **        have other optimizations in mind to deal with that case.
88280 **
88281 ** In this routine, the "p" parameter is a pointer to the outer query.
88282 ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
88283 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
88284 **
88285 ** If flattening is not attempted, this routine is a no-op and returns 0.
88286 ** If flattening is attempted this routine returns 1.
88287 **
88288 ** All of the expression analysis must occur on both the outer query and
88289 ** the subquery before this routine runs.
88290 */
88291 static int flattenSubquery(
88292   Parse *pParse,       /* Parsing context */
88293   Select *p,           /* The parent or outer SELECT statement */
88294   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
88295   int isAgg,           /* True if outer SELECT uses aggregate functions */
88296   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
88297 ){
88298   const char *zSavedAuthContext = pParse->zAuthContext;
88299   Select *pParent;
88300   Select *pSub;       /* The inner query or "subquery" */
88301   Select *pSub1;      /* Pointer to the rightmost select in sub-query */
88302   SrcList *pSrc;      /* The FROM clause of the outer query */
88303   SrcList *pSubSrc;   /* The FROM clause of the subquery */
88304   ExprList *pList;    /* The result set of the outer query */
88305   int iParent;        /* VDBE cursor number of the pSub result set temp table */
88306   int i;              /* Loop counter */
88307   Expr *pWhere;                    /* The WHERE clause */
88308   struct SrcList_item *pSubitem;   /* The subquery */
88309   sqlite3 *db = pParse->db;
88310
88311   /* Check to see if flattening is permitted.  Return 0 if not.
88312   */
88313   assert( p!=0 );
88314   assert( p->pPrior==0 );  /* Unable to flatten compound queries */
88315   if( db->flags & SQLITE_QueryFlattener ) return 0;
88316   pSrc = p->pSrc;
88317   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
88318   pSubitem = &pSrc->a[iFrom];
88319   iParent = pSubitem->iCursor;
88320   pSub = pSubitem->pSelect;
88321   assert( pSub!=0 );
88322   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
88323   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
88324   pSubSrc = pSub->pSrc;
88325   assert( pSubSrc );
88326   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
88327   ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
88328   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
88329   ** became arbitrary expressions, we were forced to add restrictions (13)
88330   ** and (14). */
88331   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
88332   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
88333   if( p->pRightmost && pSub->pLimit ){
88334     return 0;                                            /* Restriction (15) */
88335   }
88336   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
88337   if( ((pSub->selFlags & SF_Distinct)!=0 || pSub->pLimit) 
88338          && (pSrc->nSrc>1 || isAgg) ){          /* Restrictions (4)(5)(8)(9) */
88339      return 0;       
88340   }
88341   if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
88342      return 0;         /* Restriction (6)  */
88343   }
88344   if( p->pOrderBy && pSub->pOrderBy ){
88345      return 0;                                           /* Restriction (11) */
88346   }
88347   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
88348   if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
88349
88350   /* OBSOLETE COMMENT 1:
88351   ** Restriction 3:  If the subquery is a join, make sure the subquery is 
88352   ** not used as the right operand of an outer join.  Examples of why this
88353   ** is not allowed:
88354   **
88355   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
88356   **
88357   ** If we flatten the above, we would get
88358   **
88359   **         (t1 LEFT OUTER JOIN t2) JOIN t3
88360   **
88361   ** which is not at all the same thing.
88362   **
88363   ** OBSOLETE COMMENT 2:
88364   ** Restriction 12:  If the subquery is the right operand of a left outer
88365   ** join, make sure the subquery has no WHERE clause.
88366   ** An examples of why this is not allowed:
88367   **
88368   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
88369   **
88370   ** If we flatten the above, we would get
88371   **
88372   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
88373   **
88374   ** But the t2.x>0 test will always fail on a NULL row of t2, which
88375   ** effectively converts the OUTER JOIN into an INNER JOIN.
88376   **
88377   ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
88378   ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
88379   ** is fraught with danger.  Best to avoid the whole thing.  If the
88380   ** subquery is the right term of a LEFT JOIN, then do not flatten.
88381   */
88382   if( (pSubitem->jointype & JT_OUTER)!=0 ){
88383     return 0;
88384   }
88385
88386   /* Restriction 17: If the sub-query is a compound SELECT, then it must
88387   ** use only the UNION ALL operator. And none of the simple select queries
88388   ** that make up the compound SELECT are allowed to be aggregate or distinct
88389   ** queries.
88390   */
88391   if( pSub->pPrior ){
88392     if( pSub->pOrderBy ){
88393       return 0;  /* Restriction 20 */
88394     }
88395     if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
88396       return 0;
88397     }
88398     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
88399       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
88400       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
88401       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
88402        || (pSub1->pPrior && pSub1->op!=TK_ALL) 
88403        || NEVER(pSub1->pSrc==0) || pSub1->pSrc->nSrc!=1
88404       ){
88405         return 0;
88406       }
88407     }
88408
88409     /* Restriction 18. */
88410     if( p->pOrderBy ){
88411       int ii;
88412       for(ii=0; ii<p->pOrderBy->nExpr; ii++){
88413         if( p->pOrderBy->a[ii].iCol==0 ) return 0;
88414       }
88415     }
88416   }
88417
88418   /***** If we reach this point, flattening is permitted. *****/
88419
88420   /* Authorize the subquery */
88421   pParse->zAuthContext = pSubitem->zName;
88422   sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
88423   pParse->zAuthContext = zSavedAuthContext;
88424
88425   /* If the sub-query is a compound SELECT statement, then (by restrictions
88426   ** 17 and 18 above) it must be a UNION ALL and the parent query must 
88427   ** be of the form:
88428   **
88429   **     SELECT <expr-list> FROM (<sub-query>) <where-clause> 
88430   **
88431   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
88432   ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or 
88433   ** OFFSET clauses and joins them to the left-hand-side of the original
88434   ** using UNION ALL operators. In this case N is the number of simple
88435   ** select statements in the compound sub-query.
88436   **
88437   ** Example:
88438   **
88439   **     SELECT a+1 FROM (
88440   **        SELECT x FROM tab
88441   **        UNION ALL
88442   **        SELECT y FROM tab
88443   **        UNION ALL
88444   **        SELECT abs(z*2) FROM tab2
88445   **     ) WHERE a!=5 ORDER BY 1
88446   **
88447   ** Transformed into:
88448   **
88449   **     SELECT x+1 FROM tab WHERE x+1!=5
88450   **     UNION ALL
88451   **     SELECT y+1 FROM tab WHERE y+1!=5
88452   **     UNION ALL
88453   **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
88454   **     ORDER BY 1
88455   **
88456   ** We call this the "compound-subquery flattening".
88457   */
88458   for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
88459     Select *pNew;
88460     ExprList *pOrderBy = p->pOrderBy;
88461     Expr *pLimit = p->pLimit;
88462     Select *pPrior = p->pPrior;
88463     p->pOrderBy = 0;
88464     p->pSrc = 0;
88465     p->pPrior = 0;
88466     p->pLimit = 0;
88467     pNew = sqlite3SelectDup(db, p, 0);
88468     p->pLimit = pLimit;
88469     p->pOrderBy = pOrderBy;
88470     p->pSrc = pSrc;
88471     p->op = TK_ALL;
88472     p->pRightmost = 0;
88473     if( pNew==0 ){
88474       pNew = pPrior;
88475     }else{
88476       pNew->pPrior = pPrior;
88477       pNew->pRightmost = 0;
88478     }
88479     p->pPrior = pNew;
88480     if( db->mallocFailed ) return 1;
88481   }
88482
88483   /* Begin flattening the iFrom-th entry of the FROM clause 
88484   ** in the outer query.
88485   */
88486   pSub = pSub1 = pSubitem->pSelect;
88487
88488   /* Delete the transient table structure associated with the
88489   ** subquery
88490   */
88491   sqlite3DbFree(db, pSubitem->zDatabase);
88492   sqlite3DbFree(db, pSubitem->zName);
88493   sqlite3DbFree(db, pSubitem->zAlias);
88494   pSubitem->zDatabase = 0;
88495   pSubitem->zName = 0;
88496   pSubitem->zAlias = 0;
88497   pSubitem->pSelect = 0;
88498
88499   /* Defer deleting the Table object associated with the
88500   ** subquery until code generation is
88501   ** complete, since there may still exist Expr.pTab entries that
88502   ** refer to the subquery even after flattening.  Ticket #3346.
88503   **
88504   ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
88505   */
88506   if( ALWAYS(pSubitem->pTab!=0) ){
88507     Table *pTabToDel = pSubitem->pTab;
88508     if( pTabToDel->nRef==1 ){
88509       Parse *pToplevel = sqlite3ParseToplevel(pParse);
88510       pTabToDel->pNextZombie = pToplevel->pZombieTab;
88511       pToplevel->pZombieTab = pTabToDel;
88512     }else{
88513       pTabToDel->nRef--;
88514     }
88515     pSubitem->pTab = 0;
88516   }
88517
88518   /* The following loop runs once for each term in a compound-subquery
88519   ** flattening (as described above).  If we are doing a different kind
88520   ** of flattening - a flattening other than a compound-subquery flattening -
88521   ** then this loop only runs once.
88522   **
88523   ** This loop moves all of the FROM elements of the subquery into the
88524   ** the FROM clause of the outer query.  Before doing this, remember
88525   ** the cursor number for the original outer query FROM element in
88526   ** iParent.  The iParent cursor will never be used.  Subsequent code
88527   ** will scan expressions looking for iParent references and replace
88528   ** those references with expressions that resolve to the subquery FROM
88529   ** elements we are now copying in.
88530   */
88531   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
88532     int nSubSrc;
88533     u8 jointype = 0;
88534     pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
88535     nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
88536     pSrc = pParent->pSrc;     /* FROM clause of the outer query */
88537
88538     if( pSrc ){
88539       assert( pParent==p );  /* First time through the loop */
88540       jointype = pSubitem->jointype;
88541     }else{
88542       assert( pParent!=p );  /* 2nd and subsequent times through the loop */
88543       pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
88544       if( pSrc==0 ){
88545         assert( db->mallocFailed );
88546         break;
88547       }
88548     }
88549
88550     /* The subquery uses a single slot of the FROM clause of the outer
88551     ** query.  If the subquery has more than one element in its FROM clause,
88552     ** then expand the outer query to make space for it to hold all elements
88553     ** of the subquery.
88554     **
88555     ** Example:
88556     **
88557     **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
88558     **
88559     ** The outer query has 3 slots in its FROM clause.  One slot of the
88560     ** outer query (the middle slot) is used by the subquery.  The next
88561     ** block of code will expand the out query to 4 slots.  The middle
88562     ** slot is expanded to two slots in order to make space for the
88563     ** two elements in the FROM clause of the subquery.
88564     */
88565     if( nSubSrc>1 ){
88566       pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
88567       if( db->mallocFailed ){
88568         break;
88569       }
88570     }
88571
88572     /* Transfer the FROM clause terms from the subquery into the
88573     ** outer query.
88574     */
88575     for(i=0; i<nSubSrc; i++){
88576       sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
88577       pSrc->a[i+iFrom] = pSubSrc->a[i];
88578       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
88579     }
88580     pSrc->a[iFrom].jointype = jointype;
88581   
88582     /* Now begin substituting subquery result set expressions for 
88583     ** references to the iParent in the outer query.
88584     ** 
88585     ** Example:
88586     **
88587     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
88588     **   \                     \_____________ subquery __________/          /
88589     **    \_____________________ outer query ______________________________/
88590     **
88591     ** We look at every expression in the outer query and every place we see
88592     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
88593     */
88594     pList = pParent->pEList;
88595     for(i=0; i<pList->nExpr; i++){
88596       if( pList->a[i].zName==0 ){
88597         const char *zSpan = pList->a[i].zSpan;
88598         if( ALWAYS(zSpan) ){
88599           pList->a[i].zName = sqlite3DbStrDup(db, zSpan);
88600         }
88601       }
88602     }
88603     substExprList(db, pParent->pEList, iParent, pSub->pEList);
88604     if( isAgg ){
88605       substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
88606       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
88607     }
88608     if( pSub->pOrderBy ){
88609       assert( pParent->pOrderBy==0 );
88610       pParent->pOrderBy = pSub->pOrderBy;
88611       pSub->pOrderBy = 0;
88612     }else if( pParent->pOrderBy ){
88613       substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
88614     }
88615     if( pSub->pWhere ){
88616       pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
88617     }else{
88618       pWhere = 0;
88619     }
88620     if( subqueryIsAgg ){
88621       assert( pParent->pHaving==0 );
88622       pParent->pHaving = pParent->pWhere;
88623       pParent->pWhere = pWhere;
88624       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
88625       pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving, 
88626                                   sqlite3ExprDup(db, pSub->pHaving, 0));
88627       assert( pParent->pGroupBy==0 );
88628       pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
88629     }else{
88630       pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
88631       pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
88632     }
88633   
88634     /* The flattened query is distinct if either the inner or the
88635     ** outer query is distinct. 
88636     */
88637     pParent->selFlags |= pSub->selFlags & SF_Distinct;
88638   
88639     /*
88640     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
88641     **
88642     ** One is tempted to try to add a and b to combine the limits.  But this
88643     ** does not work if either limit is negative.
88644     */
88645     if( pSub->pLimit ){
88646       pParent->pLimit = pSub->pLimit;
88647       pSub->pLimit = 0;
88648     }
88649   }
88650
88651   /* Finially, delete what is left of the subquery and return
88652   ** success.
88653   */
88654   sqlite3SelectDelete(db, pSub1);
88655
88656   return 1;
88657 }
88658 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
88659
88660 /*
88661 ** Analyze the SELECT statement passed as an argument to see if it
88662 ** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if 
88663 ** it is, or 0 otherwise. At present, a query is considered to be
88664 ** a min()/max() query if:
88665 **
88666 **   1. There is a single object in the FROM clause.
88667 **
88668 **   2. There is a single expression in the result set, and it is
88669 **      either min(x) or max(x), where x is a column reference.
88670 */
88671 static u8 minMaxQuery(Select *p){
88672   Expr *pExpr;
88673   ExprList *pEList = p->pEList;
88674
88675   if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
88676   pExpr = pEList->a[0].pExpr;
88677   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
88678   if( NEVER(ExprHasProperty(pExpr, EP_xIsSelect)) ) return 0;
88679   pEList = pExpr->x.pList;
88680   if( pEList==0 || pEList->nExpr!=1 ) return 0;
88681   if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
88682   assert( !ExprHasProperty(pExpr, EP_IntValue) );
88683   if( sqlite3StrICmp(pExpr->u.zToken,"min")==0 ){
88684     return WHERE_ORDERBY_MIN;
88685   }else if( sqlite3StrICmp(pExpr->u.zToken,"max")==0 ){
88686     return WHERE_ORDERBY_MAX;
88687   }
88688   return WHERE_ORDERBY_NORMAL;
88689 }
88690
88691 /*
88692 ** The select statement passed as the first argument is an aggregate query.
88693 ** The second argment is the associated aggregate-info object. This 
88694 ** function tests if the SELECT is of the form:
88695 **
88696 **   SELECT count(*) FROM <tbl>
88697 **
88698 ** where table is a database table, not a sub-select or view. If the query
88699 ** does match this pattern, then a pointer to the Table object representing
88700 ** <tbl> is returned. Otherwise, 0 is returned.
88701 */
88702 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
88703   Table *pTab;
88704   Expr *pExpr;
88705
88706   assert( !p->pGroupBy );
88707
88708   if( p->pWhere || p->pEList->nExpr!=1 
88709    || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
88710   ){
88711     return 0;
88712   }
88713   pTab = p->pSrc->a[0].pTab;
88714   pExpr = p->pEList->a[0].pExpr;
88715   assert( pTab && !pTab->pSelect && pExpr );
88716
88717   if( IsVirtual(pTab) ) return 0;
88718   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
88719   if( (pAggInfo->aFunc[0].pFunc->flags&SQLITE_FUNC_COUNT)==0 ) return 0;
88720   if( pExpr->flags&EP_Distinct ) return 0;
88721
88722   return pTab;
88723 }
88724
88725 /*
88726 ** If the source-list item passed as an argument was augmented with an
88727 ** INDEXED BY clause, then try to locate the specified index. If there
88728 ** was such a clause and the named index cannot be found, return 
88729 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate 
88730 ** pFrom->pIndex and return SQLITE_OK.
88731 */
88732 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
88733   if( pFrom->pTab && pFrom->zIndex ){
88734     Table *pTab = pFrom->pTab;
88735     char *zIndex = pFrom->zIndex;
88736     Index *pIdx;
88737     for(pIdx=pTab->pIndex; 
88738         pIdx && sqlite3StrICmp(pIdx->zName, zIndex); 
88739         pIdx=pIdx->pNext
88740     );
88741     if( !pIdx ){
88742       sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
88743       pParse->checkSchema = 1;
88744       return SQLITE_ERROR;
88745     }
88746     pFrom->pIndex = pIdx;
88747   }
88748   return SQLITE_OK;
88749 }
88750
88751 /*
88752 ** This routine is a Walker callback for "expanding" a SELECT statement.
88753 ** "Expanding" means to do the following:
88754 **
88755 **    (1)  Make sure VDBE cursor numbers have been assigned to every
88756 **         element of the FROM clause.
88757 **
88758 **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that 
88759 **         defines FROM clause.  When views appear in the FROM clause,
88760 **         fill pTabList->a[].pSelect with a copy of the SELECT statement
88761 **         that implements the view.  A copy is made of the view's SELECT
88762 **         statement so that we can freely modify or delete that statement
88763 **         without worrying about messing up the presistent representation
88764 **         of the view.
88765 **
88766 **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
88767 **         on joins and the ON and USING clause of joins.
88768 **
88769 **    (4)  Scan the list of columns in the result set (pEList) looking
88770 **         for instances of the "*" operator or the TABLE.* operator.
88771 **         If found, expand each "*" to be every column in every table
88772 **         and TABLE.* to be every column in TABLE.
88773 **
88774 */
88775 static int selectExpander(Walker *pWalker, Select *p){
88776   Parse *pParse = pWalker->pParse;
88777   int i, j, k;
88778   SrcList *pTabList;
88779   ExprList *pEList;
88780   struct SrcList_item *pFrom;
88781   sqlite3 *db = pParse->db;
88782
88783   if( db->mallocFailed  ){
88784     return WRC_Abort;
88785   }
88786   if( NEVER(p->pSrc==0) || (p->selFlags & SF_Expanded)!=0 ){
88787     return WRC_Prune;
88788   }
88789   p->selFlags |= SF_Expanded;
88790   pTabList = p->pSrc;
88791   pEList = p->pEList;
88792
88793   /* Make sure cursor numbers have been assigned to all entries in
88794   ** the FROM clause of the SELECT statement.
88795   */
88796   sqlite3SrcListAssignCursors(pParse, pTabList);
88797
88798   /* Look up every table named in the FROM clause of the select.  If
88799   ** an entry of the FROM clause is a subquery instead of a table or view,
88800   ** then create a transient table structure to describe the subquery.
88801   */
88802   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
88803     Table *pTab;
88804     if( pFrom->pTab!=0 ){
88805       /* This statement has already been prepared.  There is no need
88806       ** to go further. */
88807       assert( i==0 );
88808       return WRC_Prune;
88809     }
88810     if( pFrom->zName==0 ){
88811 #ifndef SQLITE_OMIT_SUBQUERY
88812       Select *pSel = pFrom->pSelect;
88813       /* A sub-query in the FROM clause of a SELECT */
88814       assert( pSel!=0 );
88815       assert( pFrom->pTab==0 );
88816       sqlite3WalkSelect(pWalker, pSel);
88817       pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
88818       if( pTab==0 ) return WRC_Abort;
88819       pTab->dbMem = db->lookaside.bEnabled ? db : 0;
88820       pTab->nRef = 1;
88821       pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
88822       while( pSel->pPrior ){ pSel = pSel->pPrior; }
88823       selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
88824       pTab->iPKey = -1;
88825       pTab->tabFlags |= TF_Ephemeral;
88826 #endif
88827     }else{
88828       /* An ordinary table or view name in the FROM clause */
88829       assert( pFrom->pTab==0 );
88830       pFrom->pTab = pTab = 
88831         sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);
88832       if( pTab==0 ) return WRC_Abort;
88833       pTab->nRef++;
88834 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
88835       if( pTab->pSelect || IsVirtual(pTab) ){
88836         /* We reach here if the named table is a really a view */
88837         if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
88838         assert( pFrom->pSelect==0 );
88839         pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
88840         sqlite3WalkSelect(pWalker, pFrom->pSelect);
88841       }
88842 #endif
88843     }
88844
88845     /* Locate the index named by the INDEXED BY clause, if any. */
88846     if( sqlite3IndexedByLookup(pParse, pFrom) ){
88847       return WRC_Abort;
88848     }
88849   }
88850
88851   /* Process NATURAL keywords, and ON and USING clauses of joins.
88852   */
88853   if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
88854     return WRC_Abort;
88855   }
88856
88857   /* For every "*" that occurs in the column list, insert the names of
88858   ** all columns in all tables.  And for every TABLE.* insert the names
88859   ** of all columns in TABLE.  The parser inserted a special expression
88860   ** with the TK_ALL operator for each "*" that it found in the column list.
88861   ** The following code just has to locate the TK_ALL expressions and expand
88862   ** each one to the list of all columns in all tables.
88863   **
88864   ** The first loop just checks to see if there are any "*" operators
88865   ** that need expanding.
88866   */
88867   for(k=0; k<pEList->nExpr; k++){
88868     Expr *pE = pEList->a[k].pExpr;
88869     if( pE->op==TK_ALL ) break;
88870     assert( pE->op!=TK_DOT || pE->pRight!=0 );
88871     assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
88872     if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
88873   }
88874   if( k<pEList->nExpr ){
88875     /*
88876     ** If we get here it means the result set contains one or more "*"
88877     ** operators that need to be expanded.  Loop through each expression
88878     ** in the result set and expand them one by one.
88879     */
88880     struct ExprList_item *a = pEList->a;
88881     ExprList *pNew = 0;
88882     int flags = pParse->db->flags;
88883     int longNames = (flags & SQLITE_FullColNames)!=0
88884                       && (flags & SQLITE_ShortColNames)==0;
88885
88886     for(k=0; k<pEList->nExpr; k++){
88887       Expr *pE = a[k].pExpr;
88888       assert( pE->op!=TK_DOT || pE->pRight!=0 );
88889       if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pE->pRight->op!=TK_ALL) ){
88890         /* This particular expression does not need to be expanded.
88891         */
88892         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
88893         if( pNew ){
88894           pNew->a[pNew->nExpr-1].zName = a[k].zName;
88895           pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
88896           a[k].zName = 0;
88897           a[k].zSpan = 0;
88898         }
88899         a[k].pExpr = 0;
88900       }else{
88901         /* This expression is a "*" or a "TABLE.*" and needs to be
88902         ** expanded. */
88903         int tableSeen = 0;      /* Set to 1 when TABLE matches */
88904         char *zTName;            /* text of name of TABLE */
88905         if( pE->op==TK_DOT ){
88906           assert( pE->pLeft!=0 );
88907           assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
88908           zTName = pE->pLeft->u.zToken;
88909         }else{
88910           zTName = 0;
88911         }
88912         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
88913           Table *pTab = pFrom->pTab;
88914           char *zTabName = pFrom->zAlias;
88915           if( zTabName==0 ){
88916             zTabName = pTab->zName;
88917           }
88918           if( db->mallocFailed ) break;
88919           if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
88920             continue;
88921           }
88922           tableSeen = 1;
88923           for(j=0; j<pTab->nCol; j++){
88924             Expr *pExpr, *pRight;
88925             char *zName = pTab->aCol[j].zName;
88926             char *zColname;  /* The computed column name */
88927             char *zToFree;   /* Malloced string that needs to be freed */
88928             Token sColname;  /* Computed column name as a token */
88929
88930             /* If a column is marked as 'hidden' (currently only possible
88931             ** for virtual tables), do not include it in the expanded
88932             ** result-set list.
88933             */
88934             if( IsHiddenColumn(&pTab->aCol[j]) ){
88935               assert(IsVirtual(pTab));
88936               continue;
88937             }
88938
88939             if( i>0 && zTName==0 ){
88940               if( (pFrom->jointype & JT_NATURAL)!=0
88941                 && tableAndColumnIndex(pTabList, i, zName, 0, 0)
88942               ){
88943                 /* In a NATURAL join, omit the join columns from the 
88944                 ** table to the right of the join */
88945                 continue;
88946               }
88947               if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
88948                 /* In a join with a USING clause, omit columns in the
88949                 ** using clause from the table on the right. */
88950                 continue;
88951               }
88952             }
88953             pRight = sqlite3Expr(db, TK_ID, zName);
88954             zColname = zName;
88955             zToFree = 0;
88956             if( longNames || pTabList->nSrc>1 ){
88957               Expr *pLeft;
88958               pLeft = sqlite3Expr(db, TK_ID, zTabName);
88959               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
88960               if( longNames ){
88961                 zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
88962                 zToFree = zColname;
88963               }
88964             }else{
88965               pExpr = pRight;
88966             }
88967             pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
88968             sColname.z = zColname;
88969             sColname.n = sqlite3Strlen30(zColname);
88970             sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
88971             sqlite3DbFree(db, zToFree);
88972           }
88973         }
88974         if( !tableSeen ){
88975           if( zTName ){
88976             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
88977           }else{
88978             sqlite3ErrorMsg(pParse, "no tables specified");
88979           }
88980         }
88981       }
88982     }
88983     sqlite3ExprListDelete(db, pEList);
88984     p->pEList = pNew;
88985   }
88986 #if SQLITE_MAX_COLUMN
88987   if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
88988     sqlite3ErrorMsg(pParse, "too many columns in result set");
88989   }
88990 #endif
88991   return WRC_Continue;
88992 }
88993
88994 /*
88995 ** No-op routine for the parse-tree walker.
88996 **
88997 ** When this routine is the Walker.xExprCallback then expression trees
88998 ** are walked without any actions being taken at each node.  Presumably,
88999 ** when this routine is used for Walker.xExprCallback then 
89000 ** Walker.xSelectCallback is set to do something useful for every 
89001 ** subquery in the parser tree.
89002 */
89003 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
89004   UNUSED_PARAMETER2(NotUsed, NotUsed2);
89005   return WRC_Continue;
89006 }
89007
89008 /*
89009 ** This routine "expands" a SELECT statement and all of its subqueries.
89010 ** For additional information on what it means to "expand" a SELECT
89011 ** statement, see the comment on the selectExpand worker callback above.
89012 **
89013 ** Expanding a SELECT statement is the first step in processing a
89014 ** SELECT statement.  The SELECT statement must be expanded before
89015 ** name resolution is performed.
89016 **
89017 ** If anything goes wrong, an error message is written into pParse.
89018 ** The calling function can detect the problem by looking at pParse->nErr
89019 ** and/or pParse->db->mallocFailed.
89020 */
89021 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
89022   Walker w;
89023   w.xSelectCallback = selectExpander;
89024   w.xExprCallback = exprWalkNoop;
89025   w.pParse = pParse;
89026   sqlite3WalkSelect(&w, pSelect);
89027 }
89028
89029
89030 #ifndef SQLITE_OMIT_SUBQUERY
89031 /*
89032 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
89033 ** interface.
89034 **
89035 ** For each FROM-clause subquery, add Column.zType and Column.zColl
89036 ** information to the Table structure that represents the result set
89037 ** of that subquery.
89038 **
89039 ** The Table structure that represents the result set was constructed
89040 ** by selectExpander() but the type and collation information was omitted
89041 ** at that point because identifiers had not yet been resolved.  This
89042 ** routine is called after identifier resolution.
89043 */
89044 static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
89045   Parse *pParse;
89046   int i;
89047   SrcList *pTabList;
89048   struct SrcList_item *pFrom;
89049
89050   assert( p->selFlags & SF_Resolved );
89051   if( (p->selFlags & SF_HasTypeInfo)==0 ){
89052     p->selFlags |= SF_HasTypeInfo;
89053     pParse = pWalker->pParse;
89054     pTabList = p->pSrc;
89055     for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
89056       Table *pTab = pFrom->pTab;
89057       if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
89058         /* A sub-query in the FROM clause of a SELECT */
89059         Select *pSel = pFrom->pSelect;
89060         assert( pSel );
89061         while( pSel->pPrior ) pSel = pSel->pPrior;
89062         selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
89063       }
89064     }
89065   }
89066   return WRC_Continue;
89067 }
89068 #endif
89069
89070
89071 /*
89072 ** This routine adds datatype and collating sequence information to
89073 ** the Table structures of all FROM-clause subqueries in a
89074 ** SELECT statement.
89075 **
89076 ** Use this routine after name resolution.
89077 */
89078 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
89079 #ifndef SQLITE_OMIT_SUBQUERY
89080   Walker w;
89081   w.xSelectCallback = selectAddSubqueryTypeInfo;
89082   w.xExprCallback = exprWalkNoop;
89083   w.pParse = pParse;
89084   sqlite3WalkSelect(&w, pSelect);
89085 #endif
89086 }
89087
89088
89089 /*
89090 ** This routine sets of a SELECT statement for processing.  The
89091 ** following is accomplished:
89092 **
89093 **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
89094 **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
89095 **     *  ON and USING clauses are shifted into WHERE statements
89096 **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
89097 **     *  Identifiers in expression are matched to tables.
89098 **
89099 ** This routine acts recursively on all subqueries within the SELECT.
89100 */
89101 SQLITE_PRIVATE void sqlite3SelectPrep(
89102   Parse *pParse,         /* The parser context */
89103   Select *p,             /* The SELECT statement being coded. */
89104   NameContext *pOuterNC  /* Name context for container */
89105 ){
89106   sqlite3 *db;
89107   if( NEVER(p==0) ) return;
89108   db = pParse->db;
89109   if( p->selFlags & SF_HasTypeInfo ) return;
89110   sqlite3SelectExpand(pParse, p);
89111   if( pParse->nErr || db->mallocFailed ) return;
89112   sqlite3ResolveSelectNames(pParse, p, pOuterNC);
89113   if( pParse->nErr || db->mallocFailed ) return;
89114   sqlite3SelectAddTypeInfo(pParse, p);
89115 }
89116
89117 /*
89118 ** Reset the aggregate accumulator.
89119 **
89120 ** The aggregate accumulator is a set of memory cells that hold
89121 ** intermediate results while calculating an aggregate.  This
89122 ** routine simply stores NULLs in all of those memory cells.
89123 */
89124 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
89125   Vdbe *v = pParse->pVdbe;
89126   int i;
89127   struct AggInfo_func *pFunc;
89128   if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
89129     return;
89130   }
89131   for(i=0; i<pAggInfo->nColumn; i++){
89132     sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
89133   }
89134   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
89135     sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
89136     if( pFunc->iDistinct>=0 ){
89137       Expr *pE = pFunc->pExpr;
89138       assert( !ExprHasProperty(pE, EP_xIsSelect) );
89139       if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
89140         sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
89141            "argument");
89142         pFunc->iDistinct = -1;
89143       }else{
89144         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
89145         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
89146                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
89147       }
89148     }
89149   }
89150 }
89151
89152 /*
89153 ** Invoke the OP_AggFinalize opcode for every aggregate function
89154 ** in the AggInfo structure.
89155 */
89156 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
89157   Vdbe *v = pParse->pVdbe;
89158   int i;
89159   struct AggInfo_func *pF;
89160   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
89161     ExprList *pList = pF->pExpr->x.pList;
89162     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
89163     sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
89164                       (void*)pF->pFunc, P4_FUNCDEF);
89165   }
89166 }
89167
89168 /*
89169 ** Update the accumulator memory cells for an aggregate based on
89170 ** the current cursor position.
89171 */
89172 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
89173   Vdbe *v = pParse->pVdbe;
89174   int i;
89175   struct AggInfo_func *pF;
89176   struct AggInfo_col *pC;
89177
89178   pAggInfo->directMode = 1;
89179   sqlite3ExprCacheClear(pParse);
89180   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
89181     int nArg;
89182     int addrNext = 0;
89183     int regAgg;
89184     ExprList *pList = pF->pExpr->x.pList;
89185     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
89186     if( pList ){
89187       nArg = pList->nExpr;
89188       regAgg = sqlite3GetTempRange(pParse, nArg);
89189       sqlite3ExprCodeExprList(pParse, pList, regAgg, 0);
89190     }else{
89191       nArg = 0;
89192       regAgg = 0;
89193     }
89194     if( pF->iDistinct>=0 ){
89195       addrNext = sqlite3VdbeMakeLabel(v);
89196       assert( nArg==1 );
89197       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
89198     }
89199     if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
89200       CollSeq *pColl = 0;
89201       struct ExprList_item *pItem;
89202       int j;
89203       assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
89204       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
89205         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
89206       }
89207       if( !pColl ){
89208         pColl = pParse->db->pDfltColl;
89209       }
89210       sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
89211     }
89212     sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
89213                       (void*)pF->pFunc, P4_FUNCDEF);
89214     sqlite3VdbeChangeP5(v, (u8)nArg);
89215     sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
89216     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
89217     if( addrNext ){
89218       sqlite3VdbeResolveLabel(v, addrNext);
89219       sqlite3ExprCacheClear(pParse);
89220     }
89221   }
89222
89223   /* Before populating the accumulator registers, clear the column cache.
89224   ** Otherwise, if any of the required column values are already present 
89225   ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
89226   ** to pC->iMem. But by the time the value is used, the original register
89227   ** may have been used, invalidating the underlying buffer holding the
89228   ** text or blob value. See ticket [883034dcb5].
89229   **
89230   ** Another solution would be to change the OP_SCopy used to copy cached
89231   ** values to an OP_Copy.
89232   */
89233   sqlite3ExprCacheClear(pParse);
89234   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
89235     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
89236   }
89237   pAggInfo->directMode = 0;
89238   sqlite3ExprCacheClear(pParse);
89239 }
89240
89241 /*
89242 ** Generate code for the SELECT statement given in the p argument.  
89243 **
89244 ** The results are distributed in various ways depending on the
89245 ** contents of the SelectDest structure pointed to by argument pDest
89246 ** as follows:
89247 **
89248 **     pDest->eDest    Result
89249 **     ------------    -------------------------------------------
89250 **     SRT_Output      Generate a row of output (using the OP_ResultRow
89251 **                     opcode) for each row in the result set.
89252 **
89253 **     SRT_Mem         Only valid if the result is a single column.
89254 **                     Store the first column of the first result row
89255 **                     in register pDest->iParm then abandon the rest
89256 **                     of the query.  This destination implies "LIMIT 1".
89257 **
89258 **     SRT_Set         The result must be a single column.  Store each
89259 **                     row of result as the key in table pDest->iParm. 
89260 **                     Apply the affinity pDest->affinity before storing
89261 **                     results.  Used to implement "IN (SELECT ...)".
89262 **
89263 **     SRT_Union       Store results as a key in a temporary table pDest->iParm.
89264 **
89265 **     SRT_Except      Remove results from the temporary table pDest->iParm.
89266 **
89267 **     SRT_Table       Store results in temporary table pDest->iParm.
89268 **                     This is like SRT_EphemTab except that the table
89269 **                     is assumed to already be open.
89270 **
89271 **     SRT_EphemTab    Create an temporary table pDest->iParm and store
89272 **                     the result there. The cursor is left open after
89273 **                     returning.  This is like SRT_Table except that
89274 **                     this destination uses OP_OpenEphemeral to create
89275 **                     the table first.
89276 **
89277 **     SRT_Coroutine   Generate a co-routine that returns a new row of
89278 **                     results each time it is invoked.  The entry point
89279 **                     of the co-routine is stored in register pDest->iParm.
89280 **
89281 **     SRT_Exists      Store a 1 in memory cell pDest->iParm if the result
89282 **                     set is not empty.
89283 **
89284 **     SRT_Discard     Throw the results away.  This is used by SELECT
89285 **                     statements within triggers whose only purpose is
89286 **                     the side-effects of functions.
89287 **
89288 ** This routine returns the number of errors.  If any errors are
89289 ** encountered, then an appropriate error message is left in
89290 ** pParse->zErrMsg.
89291 **
89292 ** This routine does NOT free the Select structure passed in.  The
89293 ** calling function needs to do that.
89294 */
89295 SQLITE_PRIVATE int sqlite3Select(
89296   Parse *pParse,         /* The parser context */
89297   Select *p,             /* The SELECT statement being coded. */
89298   SelectDest *pDest      /* What to do with the query results */
89299 ){
89300   int i, j;              /* Loop counters */
89301   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
89302   Vdbe *v;               /* The virtual machine under construction */
89303   int isAgg;             /* True for select lists like "count(*)" */
89304   ExprList *pEList;      /* List of columns to extract. */
89305   SrcList *pTabList;     /* List of tables to select from */
89306   Expr *pWhere;          /* The WHERE clause.  May be NULL */
89307   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
89308   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
89309   Expr *pHaving;         /* The HAVING clause.  May be NULL */
89310   int isDistinct;        /* True if the DISTINCT keyword is present */
89311   int distinct;          /* Table to use for the distinct set */
89312   int rc = 1;            /* Value to return from this function */
89313   int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
89314   AggInfo sAggInfo;      /* Information used by aggregate queries */
89315   int iEnd;              /* Address of the end of the query */
89316   sqlite3 *db;           /* The database connection */
89317
89318   db = pParse->db;
89319   if( p==0 || db->mallocFailed || pParse->nErr ){
89320     return 1;
89321   }
89322   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
89323   memset(&sAggInfo, 0, sizeof(sAggInfo));
89324
89325   if( IgnorableOrderby(pDest) ){
89326     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || 
89327            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
89328     /* If ORDER BY makes no difference in the output then neither does
89329     ** DISTINCT so it can be removed too. */
89330     sqlite3ExprListDelete(db, p->pOrderBy);
89331     p->pOrderBy = 0;
89332     p->selFlags &= ~SF_Distinct;
89333   }
89334   sqlite3SelectPrep(pParse, p, 0);
89335   pOrderBy = p->pOrderBy;
89336   pTabList = p->pSrc;
89337   pEList = p->pEList;
89338   if( pParse->nErr || db->mallocFailed ){
89339     goto select_end;
89340   }
89341   isAgg = (p->selFlags & SF_Aggregate)!=0;
89342   assert( pEList!=0 );
89343
89344   /* Begin generating code.
89345   */
89346   v = sqlite3GetVdbe(pParse);
89347   if( v==0 ) goto select_end;
89348
89349   /* Generate code for all sub-queries in the FROM clause
89350   */
89351 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
89352   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
89353     struct SrcList_item *pItem = &pTabList->a[i];
89354     SelectDest dest;
89355     Select *pSub = pItem->pSelect;
89356     int isAggSub;
89357
89358     if( pSub==0 || pItem->isPopulated ) continue;
89359
89360     /* Increment Parse.nHeight by the height of the largest expression
89361     ** tree refered to by this, the parent select. The child select
89362     ** may contain expression trees of at most
89363     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
89364     ** more conservative than necessary, but much easier than enforcing
89365     ** an exact limit.
89366     */
89367     pParse->nHeight += sqlite3SelectExprHeight(p);
89368
89369     /* Check to see if the subquery can be absorbed into the parent. */
89370     isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
89371     if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
89372       if( isAggSub ){
89373         isAgg = 1;
89374         p->selFlags |= SF_Aggregate;
89375       }
89376       i = -1;
89377     }else{
89378       sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
89379       assert( pItem->isPopulated==0 );
89380       sqlite3Select(pParse, pSub, &dest);
89381       pItem->isPopulated = 1;
89382     }
89383     if( /*pParse->nErr ||*/ db->mallocFailed ){
89384       goto select_end;
89385     }
89386     pParse->nHeight -= sqlite3SelectExprHeight(p);
89387     pTabList = p->pSrc;
89388     if( !IgnorableOrderby(pDest) ){
89389       pOrderBy = p->pOrderBy;
89390     }
89391   }
89392   pEList = p->pEList;
89393 #endif
89394   pWhere = p->pWhere;
89395   pGroupBy = p->pGroupBy;
89396   pHaving = p->pHaving;
89397   isDistinct = (p->selFlags & SF_Distinct)!=0;
89398
89399 #ifndef SQLITE_OMIT_COMPOUND_SELECT
89400   /* If there is are a sequence of queries, do the earlier ones first.
89401   */
89402   if( p->pPrior ){
89403     if( p->pRightmost==0 ){
89404       Select *pLoop, *pRight = 0;
89405       int cnt = 0;
89406       int mxSelect;
89407       for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
89408         pLoop->pRightmost = p;
89409         pLoop->pNext = pRight;
89410         pRight = pLoop;
89411       }
89412       mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
89413       if( mxSelect && cnt>mxSelect ){
89414         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
89415         return 1;
89416       }
89417     }
89418     return multiSelect(pParse, p, pDest);
89419   }
89420 #endif
89421
89422   /* If writing to memory or generating a set
89423   ** only a single column may be output.
89424   */
89425 #ifndef SQLITE_OMIT_SUBQUERY
89426   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
89427     goto select_end;
89428   }
89429 #endif
89430
89431   /* If possible, rewrite the query to use GROUP BY instead of DISTINCT.
89432   ** GROUP BY might use an index, DISTINCT never does.
89433   */
89434   assert( p->pGroupBy==0 || (p->selFlags & SF_Aggregate)!=0 );
89435   if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ){
89436     p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
89437     pGroupBy = p->pGroupBy;
89438     p->selFlags &= ~SF_Distinct;
89439     isDistinct = 0;
89440   }
89441
89442   /* If there is both a GROUP BY and an ORDER BY clause and they are
89443   ** identical, then disable the ORDER BY clause since the GROUP BY
89444   ** will cause elements to come out in the correct order.  This is
89445   ** an optimization - the correct answer should result regardless.
89446   ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER
89447   ** to disable this optimization for testing purposes.
89448   */
89449   if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy)==0
89450          && (db->flags & SQLITE_GroupByOrder)==0 ){
89451     pOrderBy = 0;
89452   }
89453
89454   /* If there is an ORDER BY clause, then this sorting
89455   ** index might end up being unused if the data can be 
89456   ** extracted in pre-sorted order.  If that is the case, then the
89457   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
89458   ** we figure out that the sorting index is not needed.  The addrSortIndex
89459   ** variable is used to facilitate that change.
89460   */
89461   if( pOrderBy ){
89462     KeyInfo *pKeyInfo;
89463     pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
89464     pOrderBy->iECursor = pParse->nTab++;
89465     p->addrOpenEphm[2] = addrSortIndex =
89466       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
89467                            pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
89468                            (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
89469   }else{
89470     addrSortIndex = -1;
89471   }
89472
89473   /* If the output is destined for a temporary table, open that table.
89474   */
89475   if( pDest->eDest==SRT_EphemTab ){
89476     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr);
89477   }
89478
89479   /* Set the limiter.
89480   */
89481   iEnd = sqlite3VdbeMakeLabel(v);
89482   computeLimitRegisters(pParse, p, iEnd);
89483
89484   /* Open a virtual index to use for the distinct set.
89485   */
89486   if( isDistinct ){
89487     KeyInfo *pKeyInfo;
89488     assert( isAgg || pGroupBy );
89489     distinct = pParse->nTab++;
89490     pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
89491     sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
89492                         (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
89493   }else{
89494     distinct = -1;
89495   }
89496
89497   /* Aggregate and non-aggregate queries are handled differently */
89498   if( !isAgg && pGroupBy==0 ){
89499     /* This case is for non-aggregate queries
89500     ** Begin the database scan
89501     */
89502     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, 0);
89503     if( pWInfo==0 ) goto select_end;
89504
89505     /* If sorting index that was created by a prior OP_OpenEphemeral 
89506     ** instruction ended up not being needed, then change the OP_OpenEphemeral
89507     ** into an OP_Noop.
89508     */
89509     if( addrSortIndex>=0 && pOrderBy==0 ){
89510       sqlite3VdbeChangeToNoop(v, addrSortIndex, 1);
89511       p->addrOpenEphm[2] = -1;
89512     }
89513
89514     /* Use the standard inner loop
89515     */
89516     assert(!isDistinct);
89517     selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, pDest,
89518                     pWInfo->iContinue, pWInfo->iBreak);
89519
89520     /* End the database scan loop.
89521     */
89522     sqlite3WhereEnd(pWInfo);
89523   }else{
89524     /* This is the processing for aggregate queries */
89525     NameContext sNC;    /* Name context for processing aggregate information */
89526     int iAMem;          /* First Mem address for storing current GROUP BY */
89527     int iBMem;          /* First Mem address for previous GROUP BY */
89528     int iUseFlag;       /* Mem address holding flag indicating that at least
89529                         ** one row of the input to the aggregator has been
89530                         ** processed */
89531     int iAbortFlag;     /* Mem address which causes query abort if positive */
89532     int groupBySort;    /* Rows come from source in GROUP BY order */
89533     int addrEnd;        /* End of processing for this SELECT */
89534
89535     /* Remove any and all aliases between the result set and the
89536     ** GROUP BY clause.
89537     */
89538     if( pGroupBy ){
89539       int k;                        /* Loop counter */
89540       struct ExprList_item *pItem;  /* For looping over expression in a list */
89541
89542       for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
89543         pItem->iAlias = 0;
89544       }
89545       for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
89546         pItem->iAlias = 0;
89547       }
89548     }
89549
89550  
89551     /* Create a label to jump to when we want to abort the query */
89552     addrEnd = sqlite3VdbeMakeLabel(v);
89553
89554     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
89555     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
89556     ** SELECT statement.
89557     */
89558     memset(&sNC, 0, sizeof(sNC));
89559     sNC.pParse = pParse;
89560     sNC.pSrcList = pTabList;
89561     sNC.pAggInfo = &sAggInfo;
89562     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
89563     sAggInfo.pGroupBy = pGroupBy;
89564     sqlite3ExprAnalyzeAggList(&sNC, pEList);
89565     sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
89566     if( pHaving ){
89567       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
89568     }
89569     sAggInfo.nAccumulator = sAggInfo.nColumn;
89570     for(i=0; i<sAggInfo.nFunc; i++){
89571       assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
89572       sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
89573     }
89574     if( db->mallocFailed ) goto select_end;
89575
89576     /* Processing for aggregates with GROUP BY is very different and
89577     ** much more complex than aggregates without a GROUP BY.
89578     */
89579     if( pGroupBy ){
89580       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
89581       int j1;             /* A-vs-B comparision jump */
89582       int addrOutputRow;  /* Start of subroutine that outputs a result row */
89583       int regOutputRow;   /* Return address register for output subroutine */
89584       int addrSetAbort;   /* Set the abort flag and return */
89585       int addrTopOfLoop;  /* Top of the input loop */
89586       int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
89587       int addrReset;      /* Subroutine for resetting the accumulator */
89588       int regReset;       /* Return address register for reset subroutine */
89589
89590       /* If there is a GROUP BY clause we might need a sorting index to
89591       ** implement it.  Allocate that sorting index now.  If it turns out
89592       ** that we do not need it after all, the OpenEphemeral instruction
89593       ** will be converted into a Noop.  
89594       */
89595       sAggInfo.sortingIdx = pParse->nTab++;
89596       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
89597       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, 
89598           sAggInfo.sortingIdx, sAggInfo.nSortingColumn, 
89599           0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
89600
89601       /* Initialize memory locations used by GROUP BY aggregate processing
89602       */
89603       iUseFlag = ++pParse->nMem;
89604       iAbortFlag = ++pParse->nMem;
89605       regOutputRow = ++pParse->nMem;
89606       addrOutputRow = sqlite3VdbeMakeLabel(v);
89607       regReset = ++pParse->nMem;
89608       addrReset = sqlite3VdbeMakeLabel(v);
89609       iAMem = pParse->nMem + 1;
89610       pParse->nMem += pGroupBy->nExpr;
89611       iBMem = pParse->nMem + 1;
89612       pParse->nMem += pGroupBy->nExpr;
89613       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
89614       VdbeComment((v, "clear abort flag"));
89615       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
89616       VdbeComment((v, "indicate accumulator empty"));
89617
89618       /* Begin a loop that will extract all source rows in GROUP BY order.
89619       ** This might involve two separate loops with an OP_Sort in between, or
89620       ** it might be a single loop that uses an index to extract information
89621       ** in the right order to begin with.
89622       */
89623       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
89624       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0);
89625       if( pWInfo==0 ) goto select_end;
89626       if( pGroupBy==0 ){
89627         /* The optimizer is able to deliver rows in group by order so
89628         ** we do not have to sort.  The OP_OpenEphemeral table will be
89629         ** cancelled later because we still need to use the pKeyInfo
89630         */
89631         pGroupBy = p->pGroupBy;
89632         groupBySort = 0;
89633       }else{
89634         /* Rows are coming out in undetermined order.  We have to push
89635         ** each row into a sorting index, terminate the first loop,
89636         ** then loop over the sorting index in order to get the output
89637         ** in sorted order
89638         */
89639         int regBase;
89640         int regRecord;
89641         int nCol;
89642         int nGroupBy;
89643
89644         groupBySort = 1;
89645         nGroupBy = pGroupBy->nExpr;
89646         nCol = nGroupBy + 1;
89647         j = nGroupBy+1;
89648         for(i=0; i<sAggInfo.nColumn; i++){
89649           if( sAggInfo.aCol[i].iSorterColumn>=j ){
89650             nCol++;
89651             j++;
89652           }
89653         }
89654         regBase = sqlite3GetTempRange(pParse, nCol);
89655         sqlite3ExprCacheClear(pParse);
89656         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
89657         sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
89658         j = nGroupBy+1;
89659         for(i=0; i<sAggInfo.nColumn; i++){
89660           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
89661           if( pCol->iSorterColumn>=j ){
89662             int r1 = j + regBase;
89663             int r2;
89664
89665             r2 = sqlite3ExprCodeGetColumn(pParse, 
89666                                pCol->pTab, pCol->iColumn, pCol->iTable, r1);
89667             if( r1!=r2 ){
89668               sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
89669             }
89670             j++;
89671           }
89672         }
89673         regRecord = sqlite3GetTempReg(pParse);
89674         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
89675         sqlite3VdbeAddOp2(v, OP_IdxInsert, sAggInfo.sortingIdx, regRecord);
89676         sqlite3ReleaseTempReg(pParse, regRecord);
89677         sqlite3ReleaseTempRange(pParse, regBase, nCol);
89678         sqlite3WhereEnd(pWInfo);
89679         sqlite3VdbeAddOp2(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
89680         VdbeComment((v, "GROUP BY sort"));
89681         sAggInfo.useSortingIdx = 1;
89682         sqlite3ExprCacheClear(pParse);
89683       }
89684
89685       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
89686       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
89687       ** Then compare the current GROUP BY terms against the GROUP BY terms
89688       ** from the previous row currently stored in a0, a1, a2...
89689       */
89690       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
89691       sqlite3ExprCacheClear(pParse);
89692       for(j=0; j<pGroupBy->nExpr; j++){
89693         if( groupBySort ){
89694           sqlite3VdbeAddOp3(v, OP_Column, sAggInfo.sortingIdx, j, iBMem+j);
89695         }else{
89696           sAggInfo.directMode = 1;
89697           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
89698         }
89699       }
89700       sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
89701                           (char*)pKeyInfo, P4_KEYINFO);
89702       j1 = sqlite3VdbeCurrentAddr(v);
89703       sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
89704
89705       /* Generate code that runs whenever the GROUP BY changes.
89706       ** Changes in the GROUP BY are detected by the previous code
89707       ** block.  If there were no changes, this block is skipped.
89708       **
89709       ** This code copies current group by terms in b0,b1,b2,...
89710       ** over to a0,a1,a2.  It then calls the output subroutine
89711       ** and resets the aggregate accumulator registers in preparation
89712       ** for the next GROUP BY batch.
89713       */
89714       sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
89715       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
89716       VdbeComment((v, "output one row"));
89717       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
89718       VdbeComment((v, "check abort flag"));
89719       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
89720       VdbeComment((v, "reset accumulator"));
89721
89722       /* Update the aggregate accumulators based on the content of
89723       ** the current row
89724       */
89725       sqlite3VdbeJumpHere(v, j1);
89726       updateAccumulator(pParse, &sAggInfo);
89727       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
89728       VdbeComment((v, "indicate data in accumulator"));
89729
89730       /* End of the loop
89731       */
89732       if( groupBySort ){
89733         sqlite3VdbeAddOp2(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
89734       }else{
89735         sqlite3WhereEnd(pWInfo);
89736         sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1);
89737       }
89738
89739       /* Output the final row of result
89740       */
89741       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
89742       VdbeComment((v, "output final row"));
89743
89744       /* Jump over the subroutines
89745       */
89746       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
89747
89748       /* Generate a subroutine that outputs a single row of the result
89749       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
89750       ** is less than or equal to zero, the subroutine is a no-op.  If
89751       ** the processing calls for the query to abort, this subroutine
89752       ** increments the iAbortFlag memory location before returning in
89753       ** order to signal the caller to abort.
89754       */
89755       addrSetAbort = sqlite3VdbeCurrentAddr(v);
89756       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
89757       VdbeComment((v, "set abort flag"));
89758       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
89759       sqlite3VdbeResolveLabel(v, addrOutputRow);
89760       addrOutputRow = sqlite3VdbeCurrentAddr(v);
89761       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
89762       VdbeComment((v, "Groupby result generator entry point"));
89763       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
89764       finalizeAggFunctions(pParse, &sAggInfo);
89765       sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
89766       selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
89767                       distinct, pDest,
89768                       addrOutputRow+1, addrSetAbort);
89769       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
89770       VdbeComment((v, "end groupby result generator"));
89771
89772       /* Generate a subroutine that will reset the group-by accumulator
89773       */
89774       sqlite3VdbeResolveLabel(v, addrReset);
89775       resetAccumulator(pParse, &sAggInfo);
89776       sqlite3VdbeAddOp1(v, OP_Return, regReset);
89777      
89778     } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
89779     else {
89780       ExprList *pDel = 0;
89781 #ifndef SQLITE_OMIT_BTREECOUNT
89782       Table *pTab;
89783       if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
89784         /* If isSimpleCount() returns a pointer to a Table structure, then
89785         ** the SQL statement is of the form:
89786         **
89787         **   SELECT count(*) FROM <tbl>
89788         **
89789         ** where the Table structure returned represents table <tbl>.
89790         **
89791         ** This statement is so common that it is optimized specially. The
89792         ** OP_Count instruction is executed either on the intkey table that
89793         ** contains the data for table <tbl> or on one of its indexes. It
89794         ** is better to execute the op on an index, as indexes are almost
89795         ** always spread across less pages than their corresponding tables.
89796         */
89797         const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
89798         const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
89799         Index *pIdx;                         /* Iterator variable */
89800         KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
89801         Index *pBest = 0;                    /* Best index found so far */
89802         int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
89803
89804         sqlite3CodeVerifySchema(pParse, iDb);
89805         sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
89806
89807         /* Search for the index that has the least amount of columns. If
89808         ** there is such an index, and it has less columns than the table
89809         ** does, then we can assume that it consumes less space on disk and
89810         ** will therefore be cheaper to scan to determine the query result.
89811         ** In this case set iRoot to the root page number of the index b-tree
89812         ** and pKeyInfo to the KeyInfo structure required to navigate the
89813         ** index.
89814         **
89815         ** In practice the KeyInfo structure will not be used. It is only 
89816         ** passed to keep OP_OpenRead happy.
89817         */
89818         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
89819           if( !pBest || pIdx->nColumn<pBest->nColumn ){
89820             pBest = pIdx;
89821           }
89822         }
89823         if( pBest && pBest->nColumn<pTab->nCol ){
89824           iRoot = pBest->tnum;
89825           pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
89826         }
89827
89828         /* Open a read-only cursor, execute the OP_Count, close the cursor. */
89829         sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
89830         if( pKeyInfo ){
89831           sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
89832         }
89833         sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
89834         sqlite3VdbeAddOp1(v, OP_Close, iCsr);
89835       }else
89836 #endif /* SQLITE_OMIT_BTREECOUNT */
89837       {
89838         /* Check if the query is of one of the following forms:
89839         **
89840         **   SELECT min(x) FROM ...
89841         **   SELECT max(x) FROM ...
89842         **
89843         ** If it is, then ask the code in where.c to attempt to sort results
89844         ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause. 
89845         ** If where.c is able to produce results sorted in this order, then
89846         ** add vdbe code to break out of the processing loop after the 
89847         ** first iteration (since the first iteration of the loop is 
89848         ** guaranteed to operate on the row with the minimum or maximum 
89849         ** value of x, the only row required).
89850         **
89851         ** A special flag must be passed to sqlite3WhereBegin() to slightly
89852         ** modify behaviour as follows:
89853         **
89854         **   + If the query is a "SELECT min(x)", then the loop coded by
89855         **     where.c should not iterate over any values with a NULL value
89856         **     for x.
89857         **
89858         **   + The optimizer code in where.c (the thing that decides which
89859         **     index or indices to use) should place a different priority on 
89860         **     satisfying the 'ORDER BY' clause than it does in other cases.
89861         **     Refer to code and comments in where.c for details.
89862         */
89863         ExprList *pMinMax = 0;
89864         u8 flag = minMaxQuery(p);
89865         if( flag ){
89866           assert( !ExprHasProperty(p->pEList->a[0].pExpr, EP_xIsSelect) );
89867           pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->x.pList,0);
89868           pDel = pMinMax;
89869           if( pMinMax && !db->mallocFailed ){
89870             pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
89871             pMinMax->a[0].pExpr->op = TK_COLUMN;
89872           }
89873         }
89874   
89875         /* This case runs if the aggregate has no GROUP BY clause.  The
89876         ** processing is much simpler since there is only a single row
89877         ** of output.
89878         */
89879         resetAccumulator(pParse, &sAggInfo);
89880         pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, flag);
89881         if( pWInfo==0 ){
89882           sqlite3ExprListDelete(db, pDel);
89883           goto select_end;
89884         }
89885         updateAccumulator(pParse, &sAggInfo);
89886         if( !pMinMax && flag ){
89887           sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
89888           VdbeComment((v, "%s() by index",
89889                 (flag==WHERE_ORDERBY_MIN?"min":"max")));
89890         }
89891         sqlite3WhereEnd(pWInfo);
89892         finalizeAggFunctions(pParse, &sAggInfo);
89893       }
89894
89895       pOrderBy = 0;
89896       sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
89897       selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1, 
89898                       pDest, addrEnd, addrEnd);
89899       sqlite3ExprListDelete(db, pDel);
89900     }
89901     sqlite3VdbeResolveLabel(v, addrEnd);
89902     
89903   } /* endif aggregate query */
89904
89905   /* If there is an ORDER BY clause, then we need to sort the results
89906   ** and send them to the callback one by one.
89907   */
89908   if( pOrderBy ){
89909     generateSortTail(pParse, p, v, pEList->nExpr, pDest);
89910   }
89911
89912   /* Jump here to skip this query
89913   */
89914   sqlite3VdbeResolveLabel(v, iEnd);
89915
89916   /* The SELECT was successfully coded.   Set the return code to 0
89917   ** to indicate no errors.
89918   */
89919   rc = 0;
89920
89921   /* Control jumps to here if an error is encountered above, or upon
89922   ** successful coding of the SELECT.
89923   */
89924 select_end:
89925
89926   /* Identify column names if results of the SELECT are to be output.
89927   */
89928   if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
89929     generateColumnNames(pParse, pTabList, pEList);
89930   }
89931
89932   sqlite3DbFree(db, sAggInfo.aCol);
89933   sqlite3DbFree(db, sAggInfo.aFunc);
89934   return rc;
89935 }
89936
89937 #if defined(SQLITE_DEBUG)
89938 /*
89939 *******************************************************************************
89940 ** The following code is used for testing and debugging only.  The code
89941 ** that follows does not appear in normal builds.
89942 **
89943 ** These routines are used to print out the content of all or part of a 
89944 ** parse structures such as Select or Expr.  Such printouts are useful
89945 ** for helping to understand what is happening inside the code generator
89946 ** during the execution of complex SELECT statements.
89947 **
89948 ** These routine are not called anywhere from within the normal
89949 ** code base.  Then are intended to be called from within the debugger
89950 ** or from temporary "printf" statements inserted for debugging.
89951 */
89952 SQLITE_PRIVATE void sqlite3PrintExpr(Expr *p){
89953   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
89954     sqlite3DebugPrintf("(%s", p->u.zToken);
89955   }else{
89956     sqlite3DebugPrintf("(%d", p->op);
89957   }
89958   if( p->pLeft ){
89959     sqlite3DebugPrintf(" ");
89960     sqlite3PrintExpr(p->pLeft);
89961   }
89962   if( p->pRight ){
89963     sqlite3DebugPrintf(" ");
89964     sqlite3PrintExpr(p->pRight);
89965   }
89966   sqlite3DebugPrintf(")");
89967 }
89968 SQLITE_PRIVATE void sqlite3PrintExprList(ExprList *pList){
89969   int i;
89970   for(i=0; i<pList->nExpr; i++){
89971     sqlite3PrintExpr(pList->a[i].pExpr);
89972     if( i<pList->nExpr-1 ){
89973       sqlite3DebugPrintf(", ");
89974     }
89975   }
89976 }
89977 SQLITE_PRIVATE void sqlite3PrintSelect(Select *p, int indent){
89978   sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
89979   sqlite3PrintExprList(p->pEList);
89980   sqlite3DebugPrintf("\n");
89981   if( p->pSrc ){
89982     char *zPrefix;
89983     int i;
89984     zPrefix = "FROM";
89985     for(i=0; i<p->pSrc->nSrc; i++){
89986       struct SrcList_item *pItem = &p->pSrc->a[i];
89987       sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
89988       zPrefix = "";
89989       if( pItem->pSelect ){
89990         sqlite3DebugPrintf("(\n");
89991         sqlite3PrintSelect(pItem->pSelect, indent+10);
89992         sqlite3DebugPrintf("%*s)", indent+8, "");
89993       }else if( pItem->zName ){
89994         sqlite3DebugPrintf("%s", pItem->zName);
89995       }
89996       if( pItem->pTab ){
89997         sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
89998       }
89999       if( pItem->zAlias ){
90000         sqlite3DebugPrintf(" AS %s", pItem->zAlias);
90001       }
90002       if( i<p->pSrc->nSrc-1 ){
90003         sqlite3DebugPrintf(",");
90004       }
90005       sqlite3DebugPrintf("\n");
90006     }
90007   }
90008   if( p->pWhere ){
90009     sqlite3DebugPrintf("%*s WHERE ", indent, "");
90010     sqlite3PrintExpr(p->pWhere);
90011     sqlite3DebugPrintf("\n");
90012   }
90013   if( p->pGroupBy ){
90014     sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
90015     sqlite3PrintExprList(p->pGroupBy);
90016     sqlite3DebugPrintf("\n");
90017   }
90018   if( p->pHaving ){
90019     sqlite3DebugPrintf("%*s HAVING ", indent, "");
90020     sqlite3PrintExpr(p->pHaving);
90021     sqlite3DebugPrintf("\n");
90022   }
90023   if( p->pOrderBy ){
90024     sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
90025     sqlite3PrintExprList(p->pOrderBy);
90026     sqlite3DebugPrintf("\n");
90027   }
90028 }
90029 /* End of the structure debug printing code
90030 *****************************************************************************/
90031 #endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
90032
90033 /************** End of select.c **********************************************/
90034 /************** Begin file table.c *******************************************/
90035 /*
90036 ** 2001 September 15
90037 **
90038 ** The author disclaims copyright to this source code.  In place of
90039 ** a legal notice, here is a blessing:
90040 **
90041 **    May you do good and not evil.
90042 **    May you find forgiveness for yourself and forgive others.
90043 **    May you share freely, never taking more than you give.
90044 **
90045 *************************************************************************
90046 ** This file contains the sqlite3_get_table() and sqlite3_free_table()
90047 ** interface routines.  These are just wrappers around the main
90048 ** interface routine of sqlite3_exec().
90049 **
90050 ** These routines are in a separate files so that they will not be linked
90051 ** if they are not used.
90052 */
90053
90054 #ifndef SQLITE_OMIT_GET_TABLE
90055
90056 /*
90057 ** This structure is used to pass data from sqlite3_get_table() through
90058 ** to the callback function is uses to build the result.
90059 */
90060 typedef struct TabResult {
90061   char **azResult;   /* Accumulated output */
90062   char *zErrMsg;     /* Error message text, if an error occurs */
90063   int nAlloc;        /* Slots allocated for azResult[] */
90064   int nRow;          /* Number of rows in the result */
90065   int nColumn;       /* Number of columns in the result */
90066   int nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
90067   int rc;            /* Return code from sqlite3_exec() */
90068 } TabResult;
90069
90070 /*
90071 ** This routine is called once for each row in the result table.  Its job
90072 ** is to fill in the TabResult structure appropriately, allocating new
90073 ** memory as necessary.
90074 */
90075 static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
90076   TabResult *p = (TabResult*)pArg;  /* Result accumulator */
90077   int need;                         /* Slots needed in p->azResult[] */
90078   int i;                            /* Loop counter */
90079   char *z;                          /* A single column of result */
90080
90081   /* Make sure there is enough space in p->azResult to hold everything
90082   ** we need to remember from this invocation of the callback.
90083   */
90084   if( p->nRow==0 && argv!=0 ){
90085     need = nCol*2;
90086   }else{
90087     need = nCol;
90088   }
90089   if( p->nData + need > p->nAlloc ){
90090     char **azNew;
90091     p->nAlloc = p->nAlloc*2 + need;
90092     azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
90093     if( azNew==0 ) goto malloc_failed;
90094     p->azResult = azNew;
90095   }
90096
90097   /* If this is the first row, then generate an extra row containing
90098   ** the names of all columns.
90099   */
90100   if( p->nRow==0 ){
90101     p->nColumn = nCol;
90102     for(i=0; i<nCol; i++){
90103       z = sqlite3_mprintf("%s", colv[i]);
90104       if( z==0 ) goto malloc_failed;
90105       p->azResult[p->nData++] = z;
90106     }
90107   }else if( p->nColumn!=nCol ){
90108     sqlite3_free(p->zErrMsg);
90109     p->zErrMsg = sqlite3_mprintf(
90110        "sqlite3_get_table() called with two or more incompatible queries"
90111     );
90112     p->rc = SQLITE_ERROR;
90113     return 1;
90114   }
90115
90116   /* Copy over the row data
90117   */
90118   if( argv!=0 ){
90119     for(i=0; i<nCol; i++){
90120       if( argv[i]==0 ){
90121         z = 0;
90122       }else{
90123         int n = sqlite3Strlen30(argv[i])+1;
90124         z = sqlite3_malloc( n );
90125         if( z==0 ) goto malloc_failed;
90126         memcpy(z, argv[i], n);
90127       }
90128       p->azResult[p->nData++] = z;
90129     }
90130     p->nRow++;
90131   }
90132   return 0;
90133
90134 malloc_failed:
90135   p->rc = SQLITE_NOMEM;
90136   return 1;
90137 }
90138
90139 /*
90140 ** Query the database.  But instead of invoking a callback for each row,
90141 ** malloc() for space to hold the result and return the entire results
90142 ** at the conclusion of the call.
90143 **
90144 ** The result that is written to ***pazResult is held in memory obtained
90145 ** from malloc().  But the caller cannot free this memory directly.  
90146 ** Instead, the entire table should be passed to sqlite3_free_table() when
90147 ** the calling procedure is finished using it.
90148 */
90149 SQLITE_API int sqlite3_get_table(
90150   sqlite3 *db,                /* The database on which the SQL executes */
90151   const char *zSql,           /* The SQL to be executed */
90152   char ***pazResult,          /* Write the result table here */
90153   int *pnRow,                 /* Write the number of rows in the result here */
90154   int *pnColumn,              /* Write the number of columns of result here */
90155   char **pzErrMsg             /* Write error messages here */
90156 ){
90157   int rc;
90158   TabResult res;
90159
90160   *pazResult = 0;
90161   if( pnColumn ) *pnColumn = 0;
90162   if( pnRow ) *pnRow = 0;
90163   if( pzErrMsg ) *pzErrMsg = 0;
90164   res.zErrMsg = 0;
90165   res.nRow = 0;
90166   res.nColumn = 0;
90167   res.nData = 1;
90168   res.nAlloc = 20;
90169   res.rc = SQLITE_OK;
90170   res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
90171   if( res.azResult==0 ){
90172      db->errCode = SQLITE_NOMEM;
90173      return SQLITE_NOMEM;
90174   }
90175   res.azResult[0] = 0;
90176   rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
90177   assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
90178   res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
90179   if( (rc&0xff)==SQLITE_ABORT ){
90180     sqlite3_free_table(&res.azResult[1]);
90181     if( res.zErrMsg ){
90182       if( pzErrMsg ){
90183         sqlite3_free(*pzErrMsg);
90184         *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
90185       }
90186       sqlite3_free(res.zErrMsg);
90187     }
90188     db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
90189     return res.rc;
90190   }
90191   sqlite3_free(res.zErrMsg);
90192   if( rc!=SQLITE_OK ){
90193     sqlite3_free_table(&res.azResult[1]);
90194     return rc;
90195   }
90196   if( res.nAlloc>res.nData ){
90197     char **azNew;
90198     azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
90199     if( azNew==0 ){
90200       sqlite3_free_table(&res.azResult[1]);
90201       db->errCode = SQLITE_NOMEM;
90202       return SQLITE_NOMEM;
90203     }
90204     res.azResult = azNew;
90205   }
90206   *pazResult = &res.azResult[1];
90207   if( pnColumn ) *pnColumn = res.nColumn;
90208   if( pnRow ) *pnRow = res.nRow;
90209   return rc;
90210 }
90211
90212 /*
90213 ** This routine frees the space the sqlite3_get_table() malloced.
90214 */
90215 SQLITE_API void sqlite3_free_table(
90216   char **azResult            /* Result returned from from sqlite3_get_table() */
90217 ){
90218   if( azResult ){
90219     int i, n;
90220     azResult--;
90221     assert( azResult!=0 );
90222     n = SQLITE_PTR_TO_INT(azResult[0]);
90223     for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
90224     sqlite3_free(azResult);
90225   }
90226 }
90227
90228 #endif /* SQLITE_OMIT_GET_TABLE */
90229
90230 /************** End of table.c ***********************************************/
90231 /************** Begin file trigger.c *****************************************/
90232 /*
90233 **
90234 ** The author disclaims copyright to this source code.  In place of
90235 ** a legal notice, here is a blessing:
90236 **
90237 **    May you do good and not evil.
90238 **    May you find forgiveness for yourself and forgive others.
90239 **    May you share freely, never taking more than you give.
90240 **
90241 *************************************************************************
90242 ** This file contains the implementation for TRIGGERs
90243 */
90244
90245 #ifndef SQLITE_OMIT_TRIGGER
90246 /*
90247 ** Delete a linked list of TriggerStep structures.
90248 */
90249 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
90250   while( pTriggerStep ){
90251     TriggerStep * pTmp = pTriggerStep;
90252     pTriggerStep = pTriggerStep->pNext;
90253
90254     sqlite3ExprDelete(db, pTmp->pWhere);
90255     sqlite3ExprListDelete(db, pTmp->pExprList);
90256     sqlite3SelectDelete(db, pTmp->pSelect);
90257     sqlite3IdListDelete(db, pTmp->pIdList);
90258
90259     sqlite3DbFree(db, pTmp);
90260   }
90261 }
90262
90263 /*
90264 ** Given table pTab, return a list of all the triggers attached to 
90265 ** the table. The list is connected by Trigger.pNext pointers.
90266 **
90267 ** All of the triggers on pTab that are in the same database as pTab
90268 ** are already attached to pTab->pTrigger.  But there might be additional
90269 ** triggers on pTab in the TEMP schema.  This routine prepends all
90270 ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
90271 ** and returns the combined list.
90272 **
90273 ** To state it another way:  This routine returns a list of all triggers
90274 ** that fire off of pTab.  The list will include any TEMP triggers on
90275 ** pTab as well as the triggers lised in pTab->pTrigger.
90276 */
90277 SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
90278   Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
90279   Trigger *pList = 0;                  /* List of triggers to return */
90280
90281   if( pParse->disableTriggers ){
90282     return 0;
90283   }
90284
90285   if( pTmpSchema!=pTab->pSchema ){
90286     HashElem *p;
90287     for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
90288       Trigger *pTrig = (Trigger *)sqliteHashData(p);
90289       if( pTrig->pTabSchema==pTab->pSchema
90290        && 0==sqlite3StrICmp(pTrig->table, pTab->zName) 
90291       ){
90292         pTrig->pNext = (pList ? pList : pTab->pTrigger);
90293         pList = pTrig;
90294       }
90295     }
90296   }
90297
90298   return (pList ? pList : pTab->pTrigger);
90299 }
90300
90301 /*
90302 ** This is called by the parser when it sees a CREATE TRIGGER statement
90303 ** up to the point of the BEGIN before the trigger actions.  A Trigger
90304 ** structure is generated based on the information available and stored
90305 ** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
90306 ** sqlite3FinishTrigger() function is called to complete the trigger
90307 ** construction process.
90308 */
90309 SQLITE_PRIVATE void sqlite3BeginTrigger(
90310   Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
90311   Token *pName1,      /* The name of the trigger */
90312   Token *pName2,      /* The name of the trigger */
90313   int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
90314   int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
90315   IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
90316   SrcList *pTableName,/* The name of the table/view the trigger applies to */
90317   Expr *pWhen,        /* WHEN clause */
90318   int isTemp,         /* True if the TEMPORARY keyword is present */
90319   int noErr           /* Suppress errors if the trigger already exists */
90320 ){
90321   Trigger *pTrigger = 0;  /* The new trigger */
90322   Table *pTab;            /* Table that the trigger fires off of */
90323   char *zName = 0;        /* Name of the trigger */
90324   sqlite3 *db = pParse->db;  /* The database connection */
90325   int iDb;                /* The database to store the trigger in */
90326   Token *pName;           /* The unqualified db name */
90327   DbFixer sFix;           /* State vector for the DB fixer */
90328   int iTabDb;             /* Index of the database holding pTab */
90329
90330   assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
90331   assert( pName2!=0 );
90332   assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
90333   assert( op>0 && op<0xff );
90334   if( isTemp ){
90335     /* If TEMP was specified, then the trigger name may not be qualified. */
90336     if( pName2->n>0 ){
90337       sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
90338       goto trigger_cleanup;
90339     }
90340     iDb = 1;
90341     pName = pName1;
90342   }else{
90343     /* Figure out the db that the the trigger will be created in */
90344     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
90345     if( iDb<0 ){
90346       goto trigger_cleanup;
90347     }
90348   }
90349
90350   /* If the trigger name was unqualified, and the table is a temp table,
90351   ** then set iDb to 1 to create the trigger in the temporary database.
90352   ** If sqlite3SrcListLookup() returns 0, indicating the table does not
90353   ** exist, the error is caught by the block below.
90354   */
90355   if( !pTableName || db->mallocFailed ){
90356     goto trigger_cleanup;
90357   }
90358   pTab = sqlite3SrcListLookup(pParse, pTableName);
90359   if( db->init.busy==0 && pName2->n==0 && pTab
90360         && pTab->pSchema==db->aDb[1].pSchema ){
90361     iDb = 1;
90362   }
90363
90364   /* Ensure the table name matches database name and that the table exists */
90365   if( db->mallocFailed ) goto trigger_cleanup;
90366   assert( pTableName->nSrc==1 );
90367   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) && 
90368       sqlite3FixSrcList(&sFix, pTableName) ){
90369     goto trigger_cleanup;
90370   }
90371   pTab = sqlite3SrcListLookup(pParse, pTableName);
90372   if( !pTab ){
90373     /* The table does not exist. */
90374     if( db->init.iDb==1 ){
90375       /* Ticket #3810.
90376       ** Normally, whenever a table is dropped, all associated triggers are
90377       ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
90378       ** and the table is dropped by a different database connection, the
90379       ** trigger is not visible to the database connection that does the
90380       ** drop so the trigger cannot be dropped.  This results in an
90381       ** "orphaned trigger" - a trigger whose associated table is missing.
90382       */
90383       db->init.orphanTrigger = 1;
90384     }
90385     goto trigger_cleanup;
90386   }
90387   if( IsVirtual(pTab) ){
90388     sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
90389     goto trigger_cleanup;
90390   }
90391
90392   /* Check that the trigger name is not reserved and that no trigger of the
90393   ** specified name exists */
90394   zName = sqlite3NameFromToken(db, pName);
90395   if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
90396     goto trigger_cleanup;
90397   }
90398   if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
90399                       zName, sqlite3Strlen30(zName)) ){
90400     if( !noErr ){
90401       sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
90402     }
90403     goto trigger_cleanup;
90404   }
90405
90406   /* Do not create a trigger on a system table */
90407   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
90408     sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
90409     pParse->nErr++;
90410     goto trigger_cleanup;
90411   }
90412
90413   /* INSTEAD of triggers are only for views and views only support INSTEAD
90414   ** of triggers.
90415   */
90416   if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
90417     sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S", 
90418         (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
90419     goto trigger_cleanup;
90420   }
90421   if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
90422     sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
90423         " trigger on table: %S", pTableName, 0);
90424     goto trigger_cleanup;
90425   }
90426   iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
90427
90428 #ifndef SQLITE_OMIT_AUTHORIZATION
90429   {
90430     int code = SQLITE_CREATE_TRIGGER;
90431     const char *zDb = db->aDb[iTabDb].zName;
90432     const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
90433     if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
90434     if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
90435       goto trigger_cleanup;
90436     }
90437     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
90438       goto trigger_cleanup;
90439     }
90440   }
90441 #endif
90442
90443   /* INSTEAD OF triggers can only appear on views and BEFORE triggers
90444   ** cannot appear on views.  So we might as well translate every
90445   ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
90446   ** elsewhere.
90447   */
90448   if (tr_tm == TK_INSTEAD){
90449     tr_tm = TK_BEFORE;
90450   }
90451
90452   /* Build the Trigger object */
90453   pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
90454   if( pTrigger==0 ) goto trigger_cleanup;
90455   pTrigger->zName = zName;
90456   zName = 0;
90457   pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
90458   pTrigger->pSchema = db->aDb[iDb].pSchema;
90459   pTrigger->pTabSchema = pTab->pSchema;
90460   pTrigger->op = (u8)op;
90461   pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
90462   pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
90463   pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
90464   assert( pParse->pNewTrigger==0 );
90465   pParse->pNewTrigger = pTrigger;
90466
90467 trigger_cleanup:
90468   sqlite3DbFree(db, zName);
90469   sqlite3SrcListDelete(db, pTableName);
90470   sqlite3IdListDelete(db, pColumns);
90471   sqlite3ExprDelete(db, pWhen);
90472   if( !pParse->pNewTrigger ){
90473     sqlite3DeleteTrigger(db, pTrigger);
90474   }else{
90475     assert( pParse->pNewTrigger==pTrigger );
90476   }
90477 }
90478
90479 /*
90480 ** This routine is called after all of the trigger actions have been parsed
90481 ** in order to complete the process of building the trigger.
90482 */
90483 SQLITE_PRIVATE void sqlite3FinishTrigger(
90484   Parse *pParse,          /* Parser context */
90485   TriggerStep *pStepList, /* The triggered program */
90486   Token *pAll             /* Token that describes the complete CREATE TRIGGER */
90487 ){
90488   Trigger *pTrig = pParse->pNewTrigger;   /* Trigger being finished */
90489   char *zName;                            /* Name of trigger */
90490   sqlite3 *db = pParse->db;               /* The database */
90491   DbFixer sFix;                           /* Fixer object */
90492   int iDb;                                /* Database containing the trigger */
90493   Token nameToken;                        /* Trigger name for error reporting */
90494
90495   pTrig = pParse->pNewTrigger;
90496   pParse->pNewTrigger = 0;
90497   if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
90498   zName = pTrig->zName;
90499   iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
90500   pTrig->step_list = pStepList;
90501   while( pStepList ){
90502     pStepList->pTrig = pTrig;
90503     pStepList = pStepList->pNext;
90504   }
90505   nameToken.z = pTrig->zName;
90506   nameToken.n = sqlite3Strlen30(nameToken.z);
90507   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken) 
90508           && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
90509     goto triggerfinish_cleanup;
90510   }
90511
90512   /* if we are not initializing,
90513   ** build the sqlite_master entry
90514   */
90515   if( !db->init.busy ){
90516     Vdbe *v;
90517     char *z;
90518
90519     /* Make an entry in the sqlite_master table */
90520     v = sqlite3GetVdbe(pParse);
90521     if( v==0 ) goto triggerfinish_cleanup;
90522     sqlite3BeginWriteOperation(pParse, 0, iDb);
90523     z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
90524     sqlite3NestedParse(pParse,
90525        "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
90526        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
90527        pTrig->table, z);
90528     sqlite3DbFree(db, z);
90529     sqlite3ChangeCookie(pParse, iDb);
90530     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, sqlite3MPrintf(
90531         db, "type='trigger' AND name='%q'", zName), P4_DYNAMIC
90532     );
90533   }
90534
90535   if( db->init.busy ){
90536     Trigger *pLink = pTrig;
90537     Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
90538     pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
90539     if( pTrig ){
90540       db->mallocFailed = 1;
90541     }else if( pLink->pSchema==pLink->pTabSchema ){
90542       Table *pTab;
90543       int n = sqlite3Strlen30(pLink->table);
90544       pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
90545       assert( pTab!=0 );
90546       pLink->pNext = pTab->pTrigger;
90547       pTab->pTrigger = pLink;
90548     }
90549   }
90550
90551 triggerfinish_cleanup:
90552   sqlite3DeleteTrigger(db, pTrig);
90553   assert( !pParse->pNewTrigger );
90554   sqlite3DeleteTriggerStep(db, pStepList);
90555 }
90556
90557 /*
90558 ** Turn a SELECT statement (that the pSelect parameter points to) into
90559 ** a trigger step.  Return a pointer to a TriggerStep structure.
90560 **
90561 ** The parser calls this routine when it finds a SELECT statement in
90562 ** body of a TRIGGER.  
90563 */
90564 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
90565   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
90566   if( pTriggerStep==0 ) {
90567     sqlite3SelectDelete(db, pSelect);
90568     return 0;
90569   }
90570   pTriggerStep->op = TK_SELECT;
90571   pTriggerStep->pSelect = pSelect;
90572   pTriggerStep->orconf = OE_Default;
90573   return pTriggerStep;
90574 }
90575
90576 /*
90577 ** Allocate space to hold a new trigger step.  The allocated space
90578 ** holds both the TriggerStep object and the TriggerStep.target.z string.
90579 **
90580 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
90581 */
90582 static TriggerStep *triggerStepAllocate(
90583   sqlite3 *db,                /* Database connection */
90584   u8 op,                      /* Trigger opcode */
90585   Token *pName                /* The target name */
90586 ){
90587   TriggerStep *pTriggerStep;
90588
90589   pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
90590   if( pTriggerStep ){
90591     char *z = (char*)&pTriggerStep[1];
90592     memcpy(z, pName->z, pName->n);
90593     pTriggerStep->target.z = z;
90594     pTriggerStep->target.n = pName->n;
90595     pTriggerStep->op = op;
90596   }
90597   return pTriggerStep;
90598 }
90599
90600 /*
90601 ** Build a trigger step out of an INSERT statement.  Return a pointer
90602 ** to the new trigger step.
90603 **
90604 ** The parser calls this routine when it sees an INSERT inside the
90605 ** body of a trigger.
90606 */
90607 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
90608   sqlite3 *db,        /* The database connection */
90609   Token *pTableName,  /* Name of the table into which we insert */
90610   IdList *pColumn,    /* List of columns in pTableName to insert into */
90611   ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
90612   Select *pSelect,    /* A SELECT statement that supplies values */
90613   u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
90614 ){
90615   TriggerStep *pTriggerStep;
90616
90617   assert(pEList == 0 || pSelect == 0);
90618   assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
90619
90620   pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
90621   if( pTriggerStep ){
90622     pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
90623     pTriggerStep->pIdList = pColumn;
90624     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
90625     pTriggerStep->orconf = orconf;
90626   }else{
90627     sqlite3IdListDelete(db, pColumn);
90628   }
90629   sqlite3ExprListDelete(db, pEList);
90630   sqlite3SelectDelete(db, pSelect);
90631
90632   return pTriggerStep;
90633 }
90634
90635 /*
90636 ** Construct a trigger step that implements an UPDATE statement and return
90637 ** a pointer to that trigger step.  The parser calls this routine when it
90638 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
90639 */
90640 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
90641   sqlite3 *db,         /* The database connection */
90642   Token *pTableName,   /* Name of the table to be updated */
90643   ExprList *pEList,    /* The SET clause: list of column and new values */
90644   Expr *pWhere,        /* The WHERE clause */
90645   u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
90646 ){
90647   TriggerStep *pTriggerStep;
90648
90649   pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
90650   if( pTriggerStep ){
90651     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
90652     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
90653     pTriggerStep->orconf = orconf;
90654   }
90655   sqlite3ExprListDelete(db, pEList);
90656   sqlite3ExprDelete(db, pWhere);
90657   return pTriggerStep;
90658 }
90659
90660 /*
90661 ** Construct a trigger step that implements a DELETE statement and return
90662 ** a pointer to that trigger step.  The parser calls this routine when it
90663 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
90664 */
90665 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
90666   sqlite3 *db,            /* Database connection */
90667   Token *pTableName,      /* The table from which rows are deleted */
90668   Expr *pWhere            /* The WHERE clause */
90669 ){
90670   TriggerStep *pTriggerStep;
90671
90672   pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
90673   if( pTriggerStep ){
90674     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
90675     pTriggerStep->orconf = OE_Default;
90676   }
90677   sqlite3ExprDelete(db, pWhere);
90678   return pTriggerStep;
90679 }
90680
90681 /* 
90682 ** Recursively delete a Trigger structure
90683 */
90684 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
90685   if( pTrigger==0 ) return;
90686   sqlite3DeleteTriggerStep(db, pTrigger->step_list);
90687   sqlite3DbFree(db, pTrigger->zName);
90688   sqlite3DbFree(db, pTrigger->table);
90689   sqlite3ExprDelete(db, pTrigger->pWhen);
90690   sqlite3IdListDelete(db, pTrigger->pColumns);
90691   sqlite3DbFree(db, pTrigger);
90692 }
90693
90694 /*
90695 ** This function is called to drop a trigger from the database schema. 
90696 **
90697 ** This may be called directly from the parser and therefore identifies
90698 ** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
90699 ** same job as this routine except it takes a pointer to the trigger
90700 ** instead of the trigger name.
90701 **/
90702 SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
90703   Trigger *pTrigger = 0;
90704   int i;
90705   const char *zDb;
90706   const char *zName;
90707   int nName;
90708   sqlite3 *db = pParse->db;
90709
90710   if( db->mallocFailed ) goto drop_trigger_cleanup;
90711   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
90712     goto drop_trigger_cleanup;
90713   }
90714
90715   assert( pName->nSrc==1 );
90716   zDb = pName->a[0].zDatabase;
90717   zName = pName->a[0].zName;
90718   nName = sqlite3Strlen30(zName);
90719   for(i=OMIT_TEMPDB; i<db->nDb; i++){
90720     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
90721     if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
90722     pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
90723     if( pTrigger ) break;
90724   }
90725   if( !pTrigger ){
90726     if( !noErr ){
90727       sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
90728     }
90729     pParse->checkSchema = 1;
90730     goto drop_trigger_cleanup;
90731   }
90732   sqlite3DropTriggerPtr(pParse, pTrigger);
90733
90734 drop_trigger_cleanup:
90735   sqlite3SrcListDelete(db, pName);
90736 }
90737
90738 /*
90739 ** Return a pointer to the Table structure for the table that a trigger
90740 ** is set on.
90741 */
90742 static Table *tableOfTrigger(Trigger *pTrigger){
90743   int n = sqlite3Strlen30(pTrigger->table);
90744   return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
90745 }
90746
90747
90748 /*
90749 ** Drop a trigger given a pointer to that trigger. 
90750 */
90751 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
90752   Table   *pTable;
90753   Vdbe *v;
90754   sqlite3 *db = pParse->db;
90755   int iDb;
90756
90757   iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
90758   assert( iDb>=0 && iDb<db->nDb );
90759   pTable = tableOfTrigger(pTrigger);
90760   assert( pTable );
90761   assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
90762 #ifndef SQLITE_OMIT_AUTHORIZATION
90763   {
90764     int code = SQLITE_DROP_TRIGGER;
90765     const char *zDb = db->aDb[iDb].zName;
90766     const char *zTab = SCHEMA_TABLE(iDb);
90767     if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
90768     if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
90769       sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
90770       return;
90771     }
90772   }
90773 #endif
90774
90775   /* Generate code to destroy the database record of the trigger.
90776   */
90777   assert( pTable!=0 );
90778   if( (v = sqlite3GetVdbe(pParse))!=0 ){
90779     int base;
90780     static const VdbeOpList dropTrigger[] = {
90781       { OP_Rewind,     0, ADDR(9),  0},
90782       { OP_String8,    0, 1,        0}, /* 1 */
90783       { OP_Column,     0, 1,        2},
90784       { OP_Ne,         2, ADDR(8),  1},
90785       { OP_String8,    0, 1,        0}, /* 4: "trigger" */
90786       { OP_Column,     0, 0,        2},
90787       { OP_Ne,         2, ADDR(8),  1},
90788       { OP_Delete,     0, 0,        0},
90789       { OP_Next,       0, ADDR(1),  0}, /* 8 */
90790     };
90791
90792     sqlite3BeginWriteOperation(pParse, 0, iDb);
90793     sqlite3OpenMasterTable(pParse, iDb);
90794     base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
90795     sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, 0);
90796     sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
90797     sqlite3ChangeCookie(pParse, iDb);
90798     sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
90799     sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
90800     if( pParse->nMem<3 ){
90801       pParse->nMem = 3;
90802     }
90803   }
90804 }
90805
90806 /*
90807 ** Remove a trigger from the hash tables of the sqlite* pointer.
90808 */
90809 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
90810   Hash *pHash = &(db->aDb[iDb].pSchema->trigHash);
90811   Trigger *pTrigger;
90812   pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
90813   if( ALWAYS(pTrigger) ){
90814     if( pTrigger->pSchema==pTrigger->pTabSchema ){
90815       Table *pTab = tableOfTrigger(pTrigger);
90816       Trigger **pp;
90817       for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
90818       *pp = (*pp)->pNext;
90819     }
90820     sqlite3DeleteTrigger(db, pTrigger);
90821     db->flags |= SQLITE_InternChanges;
90822   }
90823 }
90824
90825 /*
90826 ** pEList is the SET clause of an UPDATE statement.  Each entry
90827 ** in pEList is of the format <id>=<expr>.  If any of the entries
90828 ** in pEList have an <id> which matches an identifier in pIdList,
90829 ** then return TRUE.  If pIdList==NULL, then it is considered a
90830 ** wildcard that matches anything.  Likewise if pEList==NULL then
90831 ** it matches anything so always return true.  Return false only
90832 ** if there is no match.
90833 */
90834 static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
90835   int e;
90836   if( pIdList==0 || NEVER(pEList==0) ) return 1;
90837   for(e=0; e<pEList->nExpr; e++){
90838     if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
90839   }
90840   return 0; 
90841 }
90842
90843 /*
90844 ** Return a list of all triggers on table pTab if there exists at least
90845 ** one trigger that must be fired when an operation of type 'op' is 
90846 ** performed on the table, and, if that operation is an UPDATE, if at
90847 ** least one of the columns in pChanges is being modified.
90848 */
90849 SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
90850   Parse *pParse,          /* Parse context */
90851   Table *pTab,            /* The table the contains the triggers */
90852   int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
90853   ExprList *pChanges,     /* Columns that change in an UPDATE statement */
90854   int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
90855 ){
90856   int mask = 0;
90857   Trigger *pList = sqlite3TriggerList(pParse, pTab);
90858   Trigger *p;
90859   assert( pList==0 || IsVirtual(pTab)==0 );
90860   for(p=pList; p; p=p->pNext){
90861     if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
90862       mask |= p->tr_tm;
90863     }
90864   }
90865   if( pMask ){
90866     *pMask = mask;
90867   }
90868   return (mask ? pList : 0);
90869 }
90870
90871 /*
90872 ** Convert the pStep->target token into a SrcList and return a pointer
90873 ** to that SrcList.
90874 **
90875 ** This routine adds a specific database name, if needed, to the target when
90876 ** forming the SrcList.  This prevents a trigger in one database from
90877 ** referring to a target in another database.  An exception is when the
90878 ** trigger is in TEMP in which case it can refer to any other database it
90879 ** wants.
90880 */
90881 static SrcList *targetSrcList(
90882   Parse *pParse,       /* The parsing context */
90883   TriggerStep *pStep   /* The trigger containing the target token */
90884 ){
90885   int iDb;             /* Index of the database to use */
90886   SrcList *pSrc;       /* SrcList to be returned */
90887
90888   pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
90889   if( pSrc ){
90890     assert( pSrc->nSrc>0 );
90891     assert( pSrc->a!=0 );
90892     iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
90893     if( iDb==0 || iDb>=2 ){
90894       sqlite3 *db = pParse->db;
90895       assert( iDb<pParse->db->nDb );
90896       pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
90897     }
90898   }
90899   return pSrc;
90900 }
90901
90902 /*
90903 ** Generate VDBE code for the statements inside the body of a single 
90904 ** trigger.
90905 */
90906 static int codeTriggerProgram(
90907   Parse *pParse,            /* The parser context */
90908   TriggerStep *pStepList,   /* List of statements inside the trigger body */
90909   int orconf                /* Conflict algorithm. (OE_Abort, etc) */  
90910 ){
90911   TriggerStep *pStep;
90912   Vdbe *v = pParse->pVdbe;
90913   sqlite3 *db = pParse->db;
90914
90915   assert( pParse->pTriggerTab && pParse->pToplevel );
90916   assert( pStepList );
90917   assert( v!=0 );
90918   for(pStep=pStepList; pStep; pStep=pStep->pNext){
90919     /* Figure out the ON CONFLICT policy that will be used for this step
90920     ** of the trigger program. If the statement that caused this trigger
90921     ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
90922     ** the ON CONFLICT policy that was specified as part of the trigger
90923     ** step statement. Example:
90924     **
90925     **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
90926     **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
90927     **   END;
90928     **
90929     **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
90930     **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
90931     */
90932     pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
90933
90934     switch( pStep->op ){
90935       case TK_UPDATE: {
90936         sqlite3Update(pParse, 
90937           targetSrcList(pParse, pStep),
90938           sqlite3ExprListDup(db, pStep->pExprList, 0), 
90939           sqlite3ExprDup(db, pStep->pWhere, 0), 
90940           pParse->eOrconf
90941         );
90942         break;
90943       }
90944       case TK_INSERT: {
90945         sqlite3Insert(pParse, 
90946           targetSrcList(pParse, pStep),
90947           sqlite3ExprListDup(db, pStep->pExprList, 0), 
90948           sqlite3SelectDup(db, pStep->pSelect, 0), 
90949           sqlite3IdListDup(db, pStep->pIdList), 
90950           pParse->eOrconf
90951         );
90952         break;
90953       }
90954       case TK_DELETE: {
90955         sqlite3DeleteFrom(pParse, 
90956           targetSrcList(pParse, pStep),
90957           sqlite3ExprDup(db, pStep->pWhere, 0)
90958         );
90959         break;
90960       }
90961       default: assert( pStep->op==TK_SELECT ); {
90962         SelectDest sDest;
90963         Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
90964         sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
90965         sqlite3Select(pParse, pSelect, &sDest);
90966         sqlite3SelectDelete(db, pSelect);
90967         break;
90968       }
90969     } 
90970     if( pStep->op!=TK_SELECT ){
90971       sqlite3VdbeAddOp0(v, OP_ResetCount);
90972     }
90973   }
90974
90975   return 0;
90976 }
90977
90978 #ifdef SQLITE_DEBUG
90979 /*
90980 ** This function is used to add VdbeComment() annotations to a VDBE
90981 ** program. It is not used in production code, only for debugging.
90982 */
90983 static const char *onErrorText(int onError){
90984   switch( onError ){
90985     case OE_Abort:    return "abort";
90986     case OE_Rollback: return "rollback";
90987     case OE_Fail:     return "fail";
90988     case OE_Replace:  return "replace";
90989     case OE_Ignore:   return "ignore";
90990     case OE_Default:  return "default";
90991   }
90992   return "n/a";
90993 }
90994 #endif
90995
90996 /*
90997 ** Parse context structure pFrom has just been used to create a sub-vdbe
90998 ** (trigger program). If an error has occurred, transfer error information
90999 ** from pFrom to pTo.
91000 */
91001 static void transferParseError(Parse *pTo, Parse *pFrom){
91002   assert( pFrom->zErrMsg==0 || pFrom->nErr );
91003   assert( pTo->zErrMsg==0 || pTo->nErr );
91004   if( pTo->nErr==0 ){
91005     pTo->zErrMsg = pFrom->zErrMsg;
91006     pTo->nErr = pFrom->nErr;
91007   }else{
91008     sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
91009   }
91010 }
91011
91012 /*
91013 ** Create and populate a new TriggerPrg object with a sub-program 
91014 ** implementing trigger pTrigger with ON CONFLICT policy orconf.
91015 */
91016 static TriggerPrg *codeRowTrigger(
91017   Parse *pParse,       /* Current parse context */
91018   Trigger *pTrigger,   /* Trigger to code */
91019   Table *pTab,         /* The table pTrigger is attached to */
91020   int orconf           /* ON CONFLICT policy to code trigger program with */
91021 ){
91022   Parse *pTop = sqlite3ParseToplevel(pParse);
91023   sqlite3 *db = pParse->db;   /* Database handle */
91024   TriggerPrg *pPrg;           /* Value to return */
91025   Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
91026   Vdbe *v;                    /* Temporary VM */
91027   NameContext sNC;            /* Name context for sub-vdbe */
91028   SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
91029   Parse *pSubParse;           /* Parse context for sub-vdbe */
91030   int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
91031
91032   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
91033
91034   /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
91035   ** are freed if an error occurs, link them into the Parse.pTriggerPrg 
91036   ** list of the top-level Parse object sooner rather than later.  */
91037   pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
91038   if( !pPrg ) return 0;
91039   pPrg->pNext = pTop->pTriggerPrg;
91040   pTop->pTriggerPrg = pPrg;
91041   pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
91042   if( !pProgram ) return 0;
91043   pProgram->nRef = 1;
91044   pPrg->pTrigger = pTrigger;
91045   pPrg->orconf = orconf;
91046   pPrg->aColmask[0] = 0xffffffff;
91047   pPrg->aColmask[1] = 0xffffffff;
91048
91049   /* Allocate and populate a new Parse context to use for coding the 
91050   ** trigger sub-program.  */
91051   pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
91052   if( !pSubParse ) return 0;
91053   memset(&sNC, 0, sizeof(sNC));
91054   sNC.pParse = pSubParse;
91055   pSubParse->db = db;
91056   pSubParse->pTriggerTab = pTab;
91057   pSubParse->pToplevel = pTop;
91058   pSubParse->zAuthContext = pTrigger->zName;
91059   pSubParse->eTriggerOp = pTrigger->op;
91060   pSubParse->nQueryLoop = pParse->nQueryLoop;
91061
91062   v = sqlite3GetVdbe(pSubParse);
91063   if( v ){
91064     VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)", 
91065       pTrigger->zName, onErrorText(orconf),
91066       (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
91067         (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
91068         (pTrigger->op==TK_INSERT ? "INSERT" : ""),
91069         (pTrigger->op==TK_DELETE ? "DELETE" : ""),
91070       pTab->zName
91071     ));
91072 #ifndef SQLITE_OMIT_TRACE
91073     sqlite3VdbeChangeP4(v, -1, 
91074       sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
91075     );
91076 #endif
91077
91078     /* If one was specified, code the WHEN clause. If it evaluates to false
91079     ** (or NULL) the sub-vdbe is immediately halted by jumping to the 
91080     ** OP_Halt inserted at the end of the program.  */
91081     if( pTrigger->pWhen ){
91082       pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
91083       if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen) 
91084        && db->mallocFailed==0 
91085       ){
91086         iEndTrigger = sqlite3VdbeMakeLabel(v);
91087         sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
91088       }
91089       sqlite3ExprDelete(db, pWhen);
91090     }
91091
91092     /* Code the trigger program into the sub-vdbe. */
91093     codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
91094
91095     /* Insert an OP_Halt at the end of the sub-program. */
91096     if( iEndTrigger ){
91097       sqlite3VdbeResolveLabel(v, iEndTrigger);
91098     }
91099     sqlite3VdbeAddOp0(v, OP_Halt);
91100     VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
91101
91102     transferParseError(pParse, pSubParse);
91103     if( db->mallocFailed==0 ){
91104       pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
91105     }
91106     pProgram->nMem = pSubParse->nMem;
91107     pProgram->nCsr = pSubParse->nTab;
91108     pProgram->token = (void *)pTrigger;
91109     pPrg->aColmask[0] = pSubParse->oldmask;
91110     pPrg->aColmask[1] = pSubParse->newmask;
91111     sqlite3VdbeDelete(v);
91112   }
91113
91114   assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
91115   assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
91116   sqlite3StackFree(db, pSubParse);
91117
91118   return pPrg;
91119 }
91120     
91121 /*
91122 ** Return a pointer to a TriggerPrg object containing the sub-program for
91123 ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
91124 ** TriggerPrg object exists, a new object is allocated and populated before
91125 ** being returned.
91126 */
91127 static TriggerPrg *getRowTrigger(
91128   Parse *pParse,       /* Current parse context */
91129   Trigger *pTrigger,   /* Trigger to code */
91130   Table *pTab,         /* The table trigger pTrigger is attached to */
91131   int orconf           /* ON CONFLICT algorithm. */
91132 ){
91133   Parse *pRoot = sqlite3ParseToplevel(pParse);
91134   TriggerPrg *pPrg;
91135
91136   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
91137
91138   /* It may be that this trigger has already been coded (or is in the
91139   ** process of being coded). If this is the case, then an entry with
91140   ** a matching TriggerPrg.pTrigger field will be present somewhere
91141   ** in the Parse.pTriggerPrg list. Search for such an entry.  */
91142   for(pPrg=pRoot->pTriggerPrg; 
91143       pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf); 
91144       pPrg=pPrg->pNext
91145   );
91146
91147   /* If an existing TriggerPrg could not be located, create a new one. */
91148   if( !pPrg ){
91149     pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
91150   }
91151
91152   return pPrg;
91153 }
91154
91155 /*
91156 ** Generate code for the trigger program associated with trigger p on 
91157 ** table pTab. The reg, orconf and ignoreJump parameters passed to this
91158 ** function are the same as those described in the header function for
91159 ** sqlite3CodeRowTrigger()
91160 */
91161 SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
91162   Parse *pParse,       /* Parse context */
91163   Trigger *p,          /* Trigger to code */
91164   Table *pTab,         /* The table to code triggers from */
91165   int reg,             /* Reg array containing OLD.* and NEW.* values */
91166   int orconf,          /* ON CONFLICT policy */
91167   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
91168 ){
91169   Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
91170   TriggerPrg *pPrg;
91171   pPrg = getRowTrigger(pParse, p, pTab, orconf);
91172   assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
91173
91174   /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program 
91175   ** is a pointer to the sub-vdbe containing the trigger program.  */
91176   if( pPrg ){
91177     sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
91178     pPrg->pProgram->nRef++;
91179     sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
91180     VdbeComment(
91181         (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
91182
91183     /* Set the P5 operand of the OP_Program instruction to non-zero if
91184     ** recursive invocation of this trigger program is disallowed. Recursive
91185     ** invocation is disallowed if (a) the sub-program is really a trigger,
91186     ** not a foreign key action, and (b) the flag to enable recursive triggers
91187     ** is clear.  */
91188     sqlite3VdbeChangeP5(v, (u8)(p->zName && !(pParse->db->flags&SQLITE_RecTriggers)));
91189   }
91190 }
91191
91192 /*
91193 ** This is called to code the required FOR EACH ROW triggers for an operation
91194 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
91195 ** is given by the op paramater. The tr_tm parameter determines whether the
91196 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
91197 ** parameter pChanges is passed the list of columns being modified.
91198 **
91199 ** If there are no triggers that fire at the specified time for the specified
91200 ** operation on pTab, this function is a no-op.
91201 **
91202 ** The reg argument is the address of the first in an array of registers 
91203 ** that contain the values substituted for the new.* and old.* references
91204 ** in the trigger program. If N is the number of columns in table pTab
91205 ** (a copy of pTab->nCol), then registers are populated as follows:
91206 **
91207 **   Register       Contains
91208 **   ------------------------------------------------------
91209 **   reg+0          OLD.rowid
91210 **   reg+1          OLD.* value of left-most column of pTab
91211 **   ...            ...
91212 **   reg+N          OLD.* value of right-most column of pTab
91213 **   reg+N+1        NEW.rowid
91214 **   reg+N+2        OLD.* value of left-most column of pTab
91215 **   ...            ...
91216 **   reg+N+N+1      NEW.* value of right-most column of pTab
91217 **
91218 ** For ON DELETE triggers, the registers containing the NEW.* values will
91219 ** never be accessed by the trigger program, so they are not allocated or 
91220 ** populated by the caller (there is no data to populate them with anyway). 
91221 ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
91222 ** are never accessed, and so are not allocated by the caller. So, for an
91223 ** ON INSERT trigger, the value passed to this function as parameter reg
91224 ** is not a readable register, although registers (reg+N) through 
91225 ** (reg+N+N+1) are.
91226 **
91227 ** Parameter orconf is the default conflict resolution algorithm for the
91228 ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
91229 ** is the instruction that control should jump to if a trigger program
91230 ** raises an IGNORE exception.
91231 */
91232 SQLITE_PRIVATE void sqlite3CodeRowTrigger(
91233   Parse *pParse,       /* Parse context */
91234   Trigger *pTrigger,   /* List of triggers on table pTab */
91235   int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
91236   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
91237   int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
91238   Table *pTab,         /* The table to code triggers from */
91239   int reg,             /* The first in an array of registers (see above) */
91240   int orconf,          /* ON CONFLICT policy */
91241   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
91242 ){
91243   Trigger *p;          /* Used to iterate through pTrigger list */
91244
91245   assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
91246   assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
91247   assert( (op==TK_UPDATE)==(pChanges!=0) );
91248
91249   for(p=pTrigger; p; p=p->pNext){
91250
91251     /* Sanity checking:  The schema for the trigger and for the table are
91252     ** always defined.  The trigger must be in the same schema as the table
91253     ** or else it must be a TEMP trigger. */
91254     assert( p->pSchema!=0 );
91255     assert( p->pTabSchema!=0 );
91256     assert( p->pSchema==p->pTabSchema 
91257          || p->pSchema==pParse->db->aDb[1].pSchema );
91258
91259     /* Determine whether we should code this trigger */
91260     if( p->op==op 
91261      && p->tr_tm==tr_tm 
91262      && checkColumnOverlap(p->pColumns, pChanges)
91263     ){
91264       sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
91265     }
91266   }
91267 }
91268
91269 /*
91270 ** Triggers may access values stored in the old.* or new.* pseudo-table. 
91271 ** This function returns a 32-bit bitmask indicating which columns of the 
91272 ** old.* or new.* tables actually are used by triggers. This information 
91273 ** may be used by the caller, for example, to avoid having to load the entire
91274 ** old.* record into memory when executing an UPDATE or DELETE command.
91275 **
91276 ** Bit 0 of the returned mask is set if the left-most column of the
91277 ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
91278 ** the second leftmost column value is required, and so on. If there
91279 ** are more than 32 columns in the table, and at least one of the columns
91280 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
91281 **
91282 ** It is not possible to determine if the old.rowid or new.rowid column is 
91283 ** accessed by triggers. The caller must always assume that it is.
91284 **
91285 ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
91286 ** applies to the old.* table. If 1, the new.* table.
91287 **
91288 ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
91289 ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
91290 ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
91291 ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
91292 ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
91293 */
91294 SQLITE_PRIVATE u32 sqlite3TriggerColmask(
91295   Parse *pParse,       /* Parse context */
91296   Trigger *pTrigger,   /* List of triggers on table pTab */
91297   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
91298   int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
91299   int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
91300   Table *pTab,         /* The table to code triggers from */
91301   int orconf           /* Default ON CONFLICT policy for trigger steps */
91302 ){
91303   const int op = pChanges ? TK_UPDATE : TK_DELETE;
91304   u32 mask = 0;
91305   Trigger *p;
91306
91307   assert( isNew==1 || isNew==0 );
91308   for(p=pTrigger; p; p=p->pNext){
91309     if( p->op==op && (tr_tm&p->tr_tm)
91310      && checkColumnOverlap(p->pColumns,pChanges)
91311     ){
91312       TriggerPrg *pPrg;
91313       pPrg = getRowTrigger(pParse, p, pTab, orconf);
91314       if( pPrg ){
91315         mask |= pPrg->aColmask[isNew];
91316       }
91317     }
91318   }
91319
91320   return mask;
91321 }
91322
91323 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
91324
91325 /************** End of trigger.c *********************************************/
91326 /************** Begin file update.c ******************************************/
91327 /*
91328 ** 2001 September 15
91329 **
91330 ** The author disclaims copyright to this source code.  In place of
91331 ** a legal notice, here is a blessing:
91332 **
91333 **    May you do good and not evil.
91334 **    May you find forgiveness for yourself and forgive others.
91335 **    May you share freely, never taking more than you give.
91336 **
91337 sqlite*************************************************************************
91338 ** This file contains C code routines that are called by the parser
91339 ** to handle UPDATE statements.
91340 */
91341
91342 #ifndef SQLITE_OMIT_VIRTUALTABLE
91343 /* Forward declaration */
91344 static void updateVirtualTable(
91345   Parse *pParse,       /* The parsing context */
91346   SrcList *pSrc,       /* The virtual table to be modified */
91347   Table *pTab,         /* The virtual table */
91348   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
91349   Expr *pRowidExpr,    /* Expression used to recompute the rowid */
91350   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
91351   Expr *pWhere         /* WHERE clause of the UPDATE statement */
91352 );
91353 #endif /* SQLITE_OMIT_VIRTUALTABLE */
91354
91355 /*
91356 ** The most recently coded instruction was an OP_Column to retrieve the
91357 ** i-th column of table pTab. This routine sets the P4 parameter of the 
91358 ** OP_Column to the default value, if any.
91359 **
91360 ** The default value of a column is specified by a DEFAULT clause in the 
91361 ** column definition. This was either supplied by the user when the table
91362 ** was created, or added later to the table definition by an ALTER TABLE
91363 ** command. If the latter, then the row-records in the table btree on disk
91364 ** may not contain a value for the column and the default value, taken
91365 ** from the P4 parameter of the OP_Column instruction, is returned instead.
91366 ** If the former, then all row-records are guaranteed to include a value
91367 ** for the column and the P4 value is not required.
91368 **
91369 ** Column definitions created by an ALTER TABLE command may only have 
91370 ** literal default values specified: a number, null or a string. (If a more
91371 ** complicated default expression value was provided, it is evaluated 
91372 ** when the ALTER TABLE is executed and one of the literal values written
91373 ** into the sqlite_master table.)
91374 **
91375 ** Therefore, the P4 parameter is only required if the default value for
91376 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
91377 ** function is capable of transforming these types of expressions into
91378 ** sqlite3_value objects.
91379 **
91380 ** If parameter iReg is not negative, code an OP_RealAffinity instruction
91381 ** on register iReg. This is used when an equivalent integer value is 
91382 ** stored in place of an 8-byte floating point value in order to save 
91383 ** space.
91384 */
91385 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
91386   assert( pTab!=0 );
91387   if( !pTab->pSelect ){
91388     sqlite3_value *pValue;
91389     u8 enc = ENC(sqlite3VdbeDb(v));
91390     Column *pCol = &pTab->aCol[i];
91391     VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
91392     assert( i<pTab->nCol );
91393     sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc, 
91394                          pCol->affinity, &pValue);
91395     if( pValue ){
91396       sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
91397     }
91398 #ifndef SQLITE_OMIT_FLOATING_POINT
91399     if( iReg>=0 && pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
91400       sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
91401     }
91402 #endif
91403   }
91404 }
91405
91406 /*
91407 ** Process an UPDATE statement.
91408 **
91409 **   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
91410 **          \_______/ \________/     \______/       \________________/
91411 *            onError   pTabList      pChanges             pWhere
91412 */
91413 SQLITE_PRIVATE void sqlite3Update(
91414   Parse *pParse,         /* The parser context */
91415   SrcList *pTabList,     /* The table in which we should change things */
91416   ExprList *pChanges,    /* Things to be changed */
91417   Expr *pWhere,          /* The WHERE clause.  May be null */
91418   int onError            /* How to handle constraint errors */
91419 ){
91420   int i, j;              /* Loop counters */
91421   Table *pTab;           /* The table to be updated */
91422   int addr = 0;          /* VDBE instruction address of the start of the loop */
91423   WhereInfo *pWInfo;     /* Information about the WHERE clause */
91424   Vdbe *v;               /* The virtual database engine */
91425   Index *pIdx;           /* For looping over indices */
91426   int nIdx;              /* Number of indices that need updating */
91427   int iCur;              /* VDBE Cursor number of pTab */
91428   sqlite3 *db;           /* The database structure */
91429   int *aRegIdx = 0;      /* One register assigned to each index to be updated */
91430   int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
91431                          ** an expression for the i-th column of the table.
91432                          ** aXRef[i]==-1 if the i-th column is not changed. */
91433   int chngRowid;         /* True if the record number is being changed */
91434   Expr *pRowidExpr = 0;  /* Expression defining the new record number */
91435   int openAll = 0;       /* True if all indices need to be opened */
91436   AuthContext sContext;  /* The authorization context */
91437   NameContext sNC;       /* The name-context to resolve expressions in */
91438   int iDb;               /* Database containing the table being updated */
91439   int okOnePass;         /* True for one-pass algorithm without the FIFO */
91440   int hasFK;             /* True if foreign key processing is required */
91441
91442 #ifndef SQLITE_OMIT_TRIGGER
91443   int isView;            /* True when updating a view (INSTEAD OF trigger) */
91444   Trigger *pTrigger;     /* List of triggers on pTab, if required */
91445   int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
91446 #endif
91447   int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
91448
91449   /* Register Allocations */
91450   int regRowCount = 0;   /* A count of rows changed */
91451   int regOldRowid;       /* The old rowid */
91452   int regNewRowid;       /* The new rowid */
91453   int regNew;
91454   int regOld = 0;
91455   int regRowSet = 0;     /* Rowset of rows to be updated */
91456   int regRec;            /* Register used for new table record to insert */
91457
91458   memset(&sContext, 0, sizeof(sContext));
91459   db = pParse->db;
91460   if( pParse->nErr || db->mallocFailed ){
91461     goto update_cleanup;
91462   }
91463   assert( pTabList->nSrc==1 );
91464
91465   /* Locate the table which we want to update. 
91466   */
91467   pTab = sqlite3SrcListLookup(pParse, pTabList);
91468   if( pTab==0 ) goto update_cleanup;
91469   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
91470
91471   /* Figure out if we have any triggers and if the table being
91472   ** updated is a view.
91473   */
91474 #ifndef SQLITE_OMIT_TRIGGER
91475   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
91476   isView = pTab->pSelect!=0;
91477   assert( pTrigger || tmask==0 );
91478 #else
91479 # define pTrigger 0
91480 # define isView 0
91481 # define tmask 0
91482 #endif
91483 #ifdef SQLITE_OMIT_VIEW
91484 # undef isView
91485 # define isView 0
91486 #endif
91487
91488   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
91489     goto update_cleanup;
91490   }
91491   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
91492     goto update_cleanup;
91493   }
91494   aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
91495   if( aXRef==0 ) goto update_cleanup;
91496   for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
91497
91498   /* Allocate a cursors for the main database table and for all indices.
91499   ** The index cursors might not be used, but if they are used they
91500   ** need to occur right after the database cursor.  So go ahead and
91501   ** allocate enough space, just in case.
91502   */
91503   pTabList->a[0].iCursor = iCur = pParse->nTab++;
91504   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
91505     pParse->nTab++;
91506   }
91507
91508   /* Initialize the name-context */
91509   memset(&sNC, 0, sizeof(sNC));
91510   sNC.pParse = pParse;
91511   sNC.pSrcList = pTabList;
91512
91513   /* Resolve the column names in all the expressions of the
91514   ** of the UPDATE statement.  Also find the column index
91515   ** for each column to be updated in the pChanges array.  For each
91516   ** column to be updated, make sure we have authorization to change
91517   ** that column.
91518   */
91519   chngRowid = 0;
91520   for(i=0; i<pChanges->nExpr; i++){
91521     if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
91522       goto update_cleanup;
91523     }
91524     for(j=0; j<pTab->nCol; j++){
91525       if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
91526         if( j==pTab->iPKey ){
91527           chngRowid = 1;
91528           pRowidExpr = pChanges->a[i].pExpr;
91529         }
91530         aXRef[j] = i;
91531         break;
91532       }
91533     }
91534     if( j>=pTab->nCol ){
91535       if( sqlite3IsRowid(pChanges->a[i].zName) ){
91536         chngRowid = 1;
91537         pRowidExpr = pChanges->a[i].pExpr;
91538       }else{
91539         sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
91540         pParse->checkSchema = 1;
91541         goto update_cleanup;
91542       }
91543     }
91544 #ifndef SQLITE_OMIT_AUTHORIZATION
91545     {
91546       int rc;
91547       rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
91548                            pTab->aCol[j].zName, db->aDb[iDb].zName);
91549       if( rc==SQLITE_DENY ){
91550         goto update_cleanup;
91551       }else if( rc==SQLITE_IGNORE ){
91552         aXRef[j] = -1;
91553       }
91554     }
91555 #endif
91556   }
91557
91558   hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid);
91559
91560   /* Allocate memory for the array aRegIdx[].  There is one entry in the
91561   ** array for each index associated with table being updated.  Fill in
91562   ** the value with a register number for indices that are to be used
91563   ** and with zero for unused indices.
91564   */
91565   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
91566   if( nIdx>0 ){
91567     aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
91568     if( aRegIdx==0 ) goto update_cleanup;
91569   }
91570   for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
91571     int reg;
91572     if( chngRowid ){
91573       reg = ++pParse->nMem;
91574     }else{
91575       reg = 0;
91576       for(i=0; i<pIdx->nColumn; i++){
91577         if( aXRef[pIdx->aiColumn[i]]>=0 ){
91578           reg = ++pParse->nMem;
91579           break;
91580         }
91581       }
91582     }
91583     aRegIdx[j] = reg;
91584   }
91585
91586   /* Begin generating code. */
91587   v = sqlite3GetVdbe(pParse);
91588   if( v==0 ) goto update_cleanup;
91589   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
91590   sqlite3BeginWriteOperation(pParse, 1, iDb);
91591
91592 #ifndef SQLITE_OMIT_VIRTUALTABLE
91593   /* Virtual tables must be handled separately */
91594   if( IsVirtual(pTab) ){
91595     updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
91596                        pWhere);
91597     pWhere = 0;
91598     pTabList = 0;
91599     goto update_cleanup;
91600   }
91601 #endif
91602
91603   /* Allocate required registers. */
91604   regOldRowid = regNewRowid = ++pParse->nMem;
91605   if( pTrigger || hasFK ){
91606     regOld = pParse->nMem + 1;
91607     pParse->nMem += pTab->nCol;
91608   }
91609   if( chngRowid || pTrigger || hasFK ){
91610     regNewRowid = ++pParse->nMem;
91611   }
91612   regNew = pParse->nMem + 1;
91613   pParse->nMem += pTab->nCol;
91614   regRec = ++pParse->nMem;
91615
91616   /* Start the view context. */
91617   if( isView ){
91618     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
91619   }
91620
91621   /* If we are trying to update a view, realize that view into
91622   ** a ephemeral table.
91623   */
91624 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
91625   if( isView ){
91626     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
91627   }
91628 #endif
91629
91630   /* Resolve the column names in all the expressions in the
91631   ** WHERE clause.
91632   */
91633   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
91634     goto update_cleanup;
91635   }
91636
91637   /* Begin the database scan
91638   */
91639   sqlite3VdbeAddOp2(v, OP_Null, 0, regOldRowid);
91640   pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0, WHERE_ONEPASS_DESIRED);
91641   if( pWInfo==0 ) goto update_cleanup;
91642   okOnePass = pWInfo->okOnePass;
91643
91644   /* Remember the rowid of every item to be updated.
91645   */
91646   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
91647   if( !okOnePass ){
91648     regRowSet = ++pParse->nMem;
91649     sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
91650   }
91651
91652   /* End the database scan loop.
91653   */
91654   sqlite3WhereEnd(pWInfo);
91655
91656   /* Initialize the count of updated rows
91657   */
91658   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
91659     regRowCount = ++pParse->nMem;
91660     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
91661   }
91662
91663   if( !isView ){
91664     /* 
91665     ** Open every index that needs updating.  Note that if any
91666     ** index could potentially invoke a REPLACE conflict resolution 
91667     ** action, then we need to open all indices because we might need
91668     ** to be deleting some records.
91669     */
91670     if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite); 
91671     if( onError==OE_Replace ){
91672       openAll = 1;
91673     }else{
91674       openAll = 0;
91675       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
91676         if( pIdx->onError==OE_Replace ){
91677           openAll = 1;
91678           break;
91679         }
91680       }
91681     }
91682     for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
91683       if( openAll || aRegIdx[i]>0 ){
91684         KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
91685         sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
91686                        (char*)pKey, P4_KEYINFO_HANDOFF);
91687         assert( pParse->nTab>iCur+i+1 );
91688       }
91689     }
91690   }
91691
91692   /* Top of the update loop */
91693   if( okOnePass ){
91694     int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
91695     addr = sqlite3VdbeAddOp0(v, OP_Goto);
91696     sqlite3VdbeJumpHere(v, a1);
91697   }else{
91698     addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
91699   }
91700
91701   /* Make cursor iCur point to the record that is being updated. If
91702   ** this record does not exist for some reason (deleted by a trigger,
91703   ** for example, then jump to the next iteration of the RowSet loop.  */
91704   sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
91705
91706   /* If the record number will change, set register regNewRowid to
91707   ** contain the new value. If the record number is not being modified,
91708   ** then regNewRowid is the same register as regOldRowid, which is
91709   ** already populated.  */
91710   assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );
91711   if( chngRowid ){
91712     sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
91713     sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
91714   }
91715
91716   /* If there are triggers on this table, populate an array of registers 
91717   ** with the required old.* column data.  */
91718   if( hasFK || pTrigger ){
91719     u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
91720     oldmask |= sqlite3TriggerColmask(pParse, 
91721         pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
91722     );
91723     for(i=0; i<pTab->nCol; i++){
91724       if( aXRef[i]<0 || oldmask==0xffffffff || (oldmask & (1<<i)) ){
91725         sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOld+i);
91726       }else{
91727         sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
91728       }
91729     }
91730     if( chngRowid==0 ){
91731       sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
91732     }
91733   }
91734
91735   /* Populate the array of registers beginning at regNew with the new
91736   ** row data. This array is used to check constaints, create the new
91737   ** table and index records, and as the values for any new.* references
91738   ** made by triggers.
91739   **
91740   ** If there are one or more BEFORE triggers, then do not populate the
91741   ** registers associated with columns that are (a) not modified by
91742   ** this UPDATE statement and (b) not accessed by new.* references. The
91743   ** values for registers not modified by the UPDATE must be reloaded from 
91744   ** the database after the BEFORE triggers are fired anyway (as the trigger 
91745   ** may have modified them). So not loading those that are not going to
91746   ** be used eliminates some redundant opcodes.
91747   */
91748   newmask = sqlite3TriggerColmask(
91749       pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
91750   );
91751   for(i=0; i<pTab->nCol; i++){
91752     if( i==pTab->iPKey ){
91753       sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
91754     }else{
91755       j = aXRef[i];
91756       if( j>=0 ){
91757         sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
91758       }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<<i)) ){
91759         /* This branch loads the value of a column that will not be changed 
91760         ** into a register. This is done if there are no BEFORE triggers, or
91761         ** if there are one or more BEFORE triggers that use this value via
91762         ** a new.* reference in a trigger program.
91763         */
91764         testcase( i==31 );
91765         testcase( i==32 );
91766         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
91767         sqlite3ColumnDefault(v, pTab, i, regNew+i);
91768       }
91769     }
91770   }
91771
91772   /* Fire any BEFORE UPDATE triggers. This happens before constraints are
91773   ** verified. One could argue that this is wrong.
91774   */
91775   if( tmask&TRIGGER_BEFORE ){
91776     sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
91777     sqlite3TableAffinityStr(v, pTab);
91778     sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
91779         TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);
91780
91781     /* The row-trigger may have deleted the row being updated. In this
91782     ** case, jump to the next row. No updates or AFTER triggers are 
91783     ** required. This behaviour - what happens when the row being updated
91784     ** is deleted or renamed by a BEFORE trigger - is left undefined in the
91785     ** documentation.
91786     */
91787     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
91788
91789     /* If it did not delete it, the row-trigger may still have modified 
91790     ** some of the columns of the row being updated. Load the values for 
91791     ** all columns not modified by the update statement into their 
91792     ** registers in case this has happened.
91793     */
91794     for(i=0; i<pTab->nCol; i++){
91795       if( aXRef[i]<0 && i!=pTab->iPKey ){
91796         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
91797         sqlite3ColumnDefault(v, pTab, i, regNew+i);
91798       }
91799     }
91800   }
91801
91802   if( !isView ){
91803     int j1;                       /* Address of jump instruction */
91804
91805     /* Do constraint checks. */
91806     sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
91807         aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);
91808
91809     /* Do FK constraint checks. */
91810     if( hasFK ){
91811       sqlite3FkCheck(pParse, pTab, regOldRowid, 0);
91812     }
91813
91814     /* Delete the index entries associated with the current record.  */
91815     j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
91816     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
91817   
91818     /* If changing the record number, delete the old record.  */
91819     if( hasFK || chngRowid ){
91820       sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
91821     }
91822     sqlite3VdbeJumpHere(v, j1);
91823
91824     if( hasFK ){
91825       sqlite3FkCheck(pParse, pTab, 0, regNewRowid);
91826     }
91827   
91828     /* Insert the new index entries and the new record. */
91829     sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);
91830
91831     /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
91832     ** handle rows (possibly in other tables) that refer via a foreign key
91833     ** to the row just updated. */ 
91834     if( hasFK ){
91835       sqlite3FkActions(pParse, pTab, pChanges, regOldRowid);
91836     }
91837   }
91838
91839   /* Increment the row counter 
91840   */
91841   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
91842     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
91843   }
91844
91845   sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
91846       TRIGGER_AFTER, pTab, regOldRowid, onError, addr);
91847
91848   /* Repeat the above with the next record to be updated, until
91849   ** all record selected by the WHERE clause have been updated.
91850   */
91851   sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
91852   sqlite3VdbeJumpHere(v, addr);
91853
91854   /* Close all tables */
91855   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
91856     if( openAll || aRegIdx[i]>0 ){
91857       sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
91858     }
91859   }
91860   sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
91861
91862   /* Update the sqlite_sequence table by storing the content of the
91863   ** maximum rowid counter values recorded while inserting into
91864   ** autoincrement tables.
91865   */
91866   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
91867     sqlite3AutoincrementEnd(pParse);
91868   }
91869
91870   /*
91871   ** Return the number of rows that were changed. If this routine is 
91872   ** generating code because of a call to sqlite3NestedParse(), do not
91873   ** invoke the callback function.
91874   */
91875   if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
91876     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
91877     sqlite3VdbeSetNumCols(v, 1);
91878     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
91879   }
91880
91881 update_cleanup:
91882   sqlite3AuthContextPop(&sContext);
91883   sqlite3DbFree(db, aRegIdx);
91884   sqlite3DbFree(db, aXRef);
91885   sqlite3SrcListDelete(db, pTabList);
91886   sqlite3ExprListDelete(db, pChanges);
91887   sqlite3ExprDelete(db, pWhere);
91888   return;
91889 }
91890 /* Make sure "isView" and other macros defined above are undefined. Otherwise
91891 ** thely may interfere with compilation of other functions in this file
91892 ** (or in another file, if this file becomes part of the amalgamation).  */
91893 #ifdef isView
91894  #undef isView
91895 #endif
91896 #ifdef pTrigger
91897  #undef pTrigger
91898 #endif
91899
91900 #ifndef SQLITE_OMIT_VIRTUALTABLE
91901 /*
91902 ** Generate code for an UPDATE of a virtual table.
91903 **
91904 ** The strategy is that we create an ephemerial table that contains
91905 ** for each row to be changed:
91906 **
91907 **   (A)  The original rowid of that row.
91908 **   (B)  The revised rowid for the row. (note1)
91909 **   (C)  The content of every column in the row.
91910 **
91911 ** Then we loop over this ephemeral table and for each row in
91912 ** the ephermeral table call VUpdate.
91913 **
91914 ** When finished, drop the ephemeral table.
91915 **
91916 ** (note1) Actually, if we know in advance that (A) is always the same
91917 ** as (B) we only store (A), then duplicate (A) when pulling
91918 ** it out of the ephemeral table before calling VUpdate.
91919 */
91920 static void updateVirtualTable(
91921   Parse *pParse,       /* The parsing context */
91922   SrcList *pSrc,       /* The virtual table to be modified */
91923   Table *pTab,         /* The virtual table */
91924   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
91925   Expr *pRowid,        /* Expression used to recompute the rowid */
91926   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
91927   Expr *pWhere         /* WHERE clause of the UPDATE statement */
91928 ){
91929   Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
91930   ExprList *pEList = 0;     /* The result set of the SELECT statement */
91931   Select *pSelect = 0;      /* The SELECT statement */
91932   Expr *pExpr;              /* Temporary expression */
91933   int ephemTab;             /* Table holding the result of the SELECT */
91934   int i;                    /* Loop counter */
91935   int addr;                 /* Address of top of loop */
91936   int iReg;                 /* First register in set passed to OP_VUpdate */
91937   sqlite3 *db = pParse->db; /* Database connection */
91938   const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
91939   SelectDest dest;
91940
91941   /* Construct the SELECT statement that will find the new values for
91942   ** all updated rows. 
91943   */
91944   pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
91945   if( pRowid ){
91946     pEList = sqlite3ExprListAppend(pParse, pEList,
91947                                    sqlite3ExprDup(db, pRowid, 0));
91948   }
91949   assert( pTab->iPKey<0 );
91950   for(i=0; i<pTab->nCol; i++){
91951     if( aXRef[i]>=0 ){
91952       pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
91953     }else{
91954       pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
91955     }
91956     pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
91957   }
91958   pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
91959   
91960   /* Create the ephemeral table into which the update results will
91961   ** be stored.
91962   */
91963   assert( v );
91964   ephemTab = pParse->nTab++;
91965   sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
91966
91967   /* fill the ephemeral table 
91968   */
91969   sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
91970   sqlite3Select(pParse, pSelect, &dest);
91971
91972   /* Generate code to scan the ephemeral table and call VUpdate. */
91973   iReg = ++pParse->nMem;
91974   pParse->nMem += pTab->nCol+1;
91975   addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
91976   sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
91977   sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
91978   for(i=0; i<pTab->nCol; i++){
91979     sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
91980   }
91981   sqlite3VtabMakeWritable(pParse, pTab);
91982   sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
91983   sqlite3MayAbort(pParse);
91984   sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
91985   sqlite3VdbeJumpHere(v, addr);
91986   sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
91987
91988   /* Cleanup */
91989   sqlite3SelectDelete(db, pSelect);  
91990 }
91991 #endif /* SQLITE_OMIT_VIRTUALTABLE */
91992
91993 /************** End of update.c **********************************************/
91994 /************** Begin file vacuum.c ******************************************/
91995 /*
91996 ** 2003 April 6
91997 **
91998 ** The author disclaims copyright to this source code.  In place of
91999 ** a legal notice, here is a blessing:
92000 **
92001 **    May you do good and not evil.
92002 **    May you find forgiveness for yourself and forgive others.
92003 **    May you share freely, never taking more than you give.
92004 **
92005 *************************************************************************
92006 ** This file contains code used to implement the VACUUM command.
92007 **
92008 ** Most of the code in this file may be omitted by defining the
92009 ** SQLITE_OMIT_VACUUM macro.
92010 */
92011
92012 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
92013 /*
92014 ** Finalize a prepared statement.  If there was an error, store the
92015 ** text of the error message in *pzErrMsg.  Return the result code.
92016 */
92017 static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
92018   int rc;
92019   rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
92020   if( rc ){
92021     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
92022   }
92023   return rc;
92024 }
92025
92026 /*
92027 ** Execute zSql on database db. Return an error code.
92028 */
92029 static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
92030   sqlite3_stmt *pStmt;
92031   VVA_ONLY( int rc; )
92032   if( !zSql ){
92033     return SQLITE_NOMEM;
92034   }
92035   if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
92036     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
92037     return sqlite3_errcode(db);
92038   }
92039   VVA_ONLY( rc = ) sqlite3_step(pStmt);
92040   assert( rc!=SQLITE_ROW );
92041   return vacuumFinalize(db, pStmt, pzErrMsg);
92042 }
92043
92044 /*
92045 ** Execute zSql on database db. The statement returns exactly
92046 ** one column. Execute this as SQL on the same database.
92047 */
92048 static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
92049   sqlite3_stmt *pStmt;
92050   int rc;
92051
92052   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
92053   if( rc!=SQLITE_OK ) return rc;
92054
92055   while( SQLITE_ROW==sqlite3_step(pStmt) ){
92056     rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
92057     if( rc!=SQLITE_OK ){
92058       vacuumFinalize(db, pStmt, pzErrMsg);
92059       return rc;
92060     }
92061   }
92062
92063   return vacuumFinalize(db, pStmt, pzErrMsg);
92064 }
92065
92066 /*
92067 ** The non-standard VACUUM command is used to clean up the database,
92068 ** collapse free space, etc.  It is modelled after the VACUUM command
92069 ** in PostgreSQL.
92070 **
92071 ** In version 1.0.x of SQLite, the VACUUM command would call
92072 ** gdbm_reorganize() on all the database tables.  But beginning
92073 ** with 2.0.0, SQLite no longer uses GDBM so this command has
92074 ** become a no-op.
92075 */
92076 SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
92077   Vdbe *v = sqlite3GetVdbe(pParse);
92078   if( v ){
92079     sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
92080   }
92081   return;
92082 }
92083
92084 /*
92085 ** This routine implements the OP_Vacuum opcode of the VDBE.
92086 */
92087 SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
92088   int rc = SQLITE_OK;     /* Return code from service routines */
92089   Btree *pMain;           /* The database being vacuumed */
92090   Btree *pTemp;           /* The temporary database we vacuum into */
92091   char *zSql = 0;         /* SQL statements */
92092   int saved_flags;        /* Saved value of the db->flags */
92093   int saved_nChange;      /* Saved value of db->nChange */
92094   int saved_nTotalChange; /* Saved value of db->nTotalChange */
92095   void (*saved_xTrace)(void*,const char*);  /* Saved db->xTrace */
92096   Db *pDb = 0;            /* Database to detach at end of vacuum */
92097   int isMemDb;            /* True if vacuuming a :memory: database */
92098   int nRes;               /* Bytes of reserved space at the end of each page */
92099   int nDb;                /* Number of attached databases */
92100
92101   if( !db->autoCommit ){
92102     sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
92103     return SQLITE_ERROR;
92104   }
92105
92106   /* Save the current value of the database flags so that it can be 
92107   ** restored before returning. Then set the writable-schema flag, and
92108   ** disable CHECK and foreign key constraints.  */
92109   saved_flags = db->flags;
92110   saved_nChange = db->nChange;
92111   saved_nTotalChange = db->nTotalChange;
92112   saved_xTrace = db->xTrace;
92113   db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
92114   db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
92115   db->xTrace = 0;
92116
92117   pMain = db->aDb[0].pBt;
92118   isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
92119
92120   /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
92121   ** can be set to 'off' for this file, as it is not recovered if a crash
92122   ** occurs anyway. The integrity of the database is maintained by a
92123   ** (possibly synchronous) transaction opened on the main database before
92124   ** sqlite3BtreeCopyFile() is called.
92125   **
92126   ** An optimisation would be to use a non-journaled pager.
92127   ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
92128   ** that actually made the VACUUM run slower.  Very little journalling
92129   ** actually occurs when doing a vacuum since the vacuum_db is initially
92130   ** empty.  Only the journal header is written.  Apparently it takes more
92131   ** time to parse and run the PRAGMA to turn journalling off than it does
92132   ** to write the journal header file.
92133   */
92134   nDb = db->nDb;
92135   if( sqlite3TempInMemory(db) ){
92136     zSql = "ATTACH ':memory:' AS vacuum_db;";
92137   }else{
92138     zSql = "ATTACH '' AS vacuum_db;";
92139   }
92140   rc = execSql(db, pzErrMsg, zSql);
92141   if( db->nDb>nDb ){
92142     pDb = &db->aDb[db->nDb-1];
92143     assert( strcmp(pDb->zName,"vacuum_db")==0 );
92144   }
92145   if( rc!=SQLITE_OK ) goto end_of_vacuum;
92146   pTemp = db->aDb[db->nDb-1].pBt;
92147
92148   /* The call to execSql() to attach the temp database has left the file
92149   ** locked (as there was more than one active statement when the transaction
92150   ** to read the schema was concluded. Unlock it here so that this doesn't
92151   ** cause problems for the call to BtreeSetPageSize() below.  */
92152   sqlite3BtreeCommit(pTemp);
92153
92154   nRes = sqlite3BtreeGetReserve(pMain);
92155
92156   /* A VACUUM cannot change the pagesize of an encrypted database. */
92157 #ifdef SQLITE_HAS_CODEC
92158   if( db->nextPagesize ){
92159     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
92160     int nKey;
92161     char *zKey;
92162     sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
92163     if( nKey ) db->nextPagesize = 0;
92164   }
92165 #endif
92166
92167   /* Do not attempt to change the page size for a WAL database */
92168   if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
92169                                                ==PAGER_JOURNALMODE_WAL ){
92170     db->nextPagesize = 0;
92171   }
92172
92173   if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
92174    || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
92175    || NEVER(db->mallocFailed)
92176   ){
92177     rc = SQLITE_NOMEM;
92178     goto end_of_vacuum;
92179   }
92180   rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
92181   if( rc!=SQLITE_OK ){
92182     goto end_of_vacuum;
92183   }
92184
92185 #ifndef SQLITE_OMIT_AUTOVACUUM
92186   sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
92187                                            sqlite3BtreeGetAutoVacuum(pMain));
92188 #endif
92189
92190   /* Begin a transaction */
92191   rc = execSql(db, pzErrMsg, "BEGIN EXCLUSIVE;");
92192   if( rc!=SQLITE_OK ) goto end_of_vacuum;
92193
92194   /* Query the schema of the main database. Create a mirror schema
92195   ** in the temporary database.
92196   */
92197   rc = execExecSql(db, pzErrMsg,
92198       "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
92199       "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
92200       "   AND rootpage>0"
92201   );
92202   if( rc!=SQLITE_OK ) goto end_of_vacuum;
92203   rc = execExecSql(db, pzErrMsg,
92204       "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
92205       "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
92206   if( rc!=SQLITE_OK ) goto end_of_vacuum;
92207   rc = execExecSql(db, pzErrMsg,
92208       "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
92209       "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
92210   if( rc!=SQLITE_OK ) goto end_of_vacuum;
92211
92212   /* Loop through the tables in the main database. For each, do
92213   ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
92214   ** the contents to the temporary database.
92215   */
92216   rc = execExecSql(db, pzErrMsg,
92217       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
92218       "|| ' SELECT * FROM main.' || quote(name) || ';'"
92219       "FROM main.sqlite_master "
92220       "WHERE type = 'table' AND name!='sqlite_sequence' "
92221       "  AND rootpage>0"
92222   );
92223   if( rc!=SQLITE_OK ) goto end_of_vacuum;
92224
92225   /* Copy over the sequence table
92226   */
92227   rc = execExecSql(db, pzErrMsg,
92228       "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
92229       "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
92230   );
92231   if( rc!=SQLITE_OK ) goto end_of_vacuum;
92232   rc = execExecSql(db, pzErrMsg,
92233       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
92234       "|| ' SELECT * FROM main.' || quote(name) || ';' "
92235       "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
92236   );
92237   if( rc!=SQLITE_OK ) goto end_of_vacuum;
92238
92239
92240   /* Copy the triggers, views, and virtual tables from the main database
92241   ** over to the temporary database.  None of these objects has any
92242   ** associated storage, so all we have to do is copy their entries
92243   ** from the SQLITE_MASTER table.
92244   */
92245   rc = execSql(db, pzErrMsg,
92246       "INSERT INTO vacuum_db.sqlite_master "
92247       "  SELECT type, name, tbl_name, rootpage, sql"
92248       "    FROM main.sqlite_master"
92249       "   WHERE type='view' OR type='trigger'"
92250       "      OR (type='table' AND rootpage=0)"
92251   );
92252   if( rc ) goto end_of_vacuum;
92253
92254   /* At this point, unless the main db was completely empty, there is now a
92255   ** transaction open on the vacuum database, but not on the main database.
92256   ** Open a btree level transaction on the main database. This allows a
92257   ** call to sqlite3BtreeCopyFile(). The main database btree level
92258   ** transaction is then committed, so the SQL level never knows it was
92259   ** opened for writing. This way, the SQL transaction used to create the
92260   ** temporary database never needs to be committed.
92261   */
92262   {
92263     u32 meta;
92264     int i;
92265
92266     /* This array determines which meta meta values are preserved in the
92267     ** vacuum.  Even entries are the meta value number and odd entries
92268     ** are an increment to apply to the meta value after the vacuum.
92269     ** The increment is used to increase the schema cookie so that other
92270     ** connections to the same database will know to reread the schema.
92271     */
92272     static const unsigned char aCopy[] = {
92273        BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
92274        BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
92275        BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
92276        BTREE_USER_VERSION,       0,  /* Preserve the user version */
92277     };
92278
92279     assert( 1==sqlite3BtreeIsInTrans(pTemp) );
92280     assert( 1==sqlite3BtreeIsInTrans(pMain) );
92281
92282     /* Copy Btree meta values */
92283     for(i=0; i<ArraySize(aCopy); i+=2){
92284       /* GetMeta() and UpdateMeta() cannot fail in this context because
92285       ** we already have page 1 loaded into cache and marked dirty. */
92286       sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
92287       rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
92288       if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
92289     }
92290
92291     rc = sqlite3BtreeCopyFile(pMain, pTemp);
92292     if( rc!=SQLITE_OK ) goto end_of_vacuum;
92293     rc = sqlite3BtreeCommit(pTemp);
92294     if( rc!=SQLITE_OK ) goto end_of_vacuum;
92295 #ifndef SQLITE_OMIT_AUTOVACUUM
92296     sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
92297 #endif
92298   }
92299
92300   assert( rc==SQLITE_OK );
92301   rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
92302
92303 end_of_vacuum:
92304   /* Restore the original value of db->flags */
92305   db->flags = saved_flags;
92306   db->nChange = saved_nChange;
92307   db->nTotalChange = saved_nTotalChange;
92308   db->xTrace = saved_xTrace;
92309   sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
92310
92311   /* Currently there is an SQL level transaction open on the vacuum
92312   ** database. No locks are held on any other files (since the main file
92313   ** was committed at the btree level). So it safe to end the transaction
92314   ** by manually setting the autoCommit flag to true and detaching the
92315   ** vacuum database. The vacuum_db journal file is deleted when the pager
92316   ** is closed by the DETACH.
92317   */
92318   db->autoCommit = 1;
92319
92320   if( pDb ){
92321     sqlite3BtreeClose(pDb->pBt);
92322     pDb->pBt = 0;
92323     pDb->pSchema = 0;
92324   }
92325
92326   sqlite3ResetInternalSchema(db, 0);
92327
92328   return rc;
92329 }
92330 #endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
92331
92332 /************** End of vacuum.c **********************************************/
92333 /************** Begin file vtab.c ********************************************/
92334 /*
92335 ** 2006 June 10
92336 **
92337 ** The author disclaims copyright to this source code.  In place of
92338 ** a legal notice, here is a blessing:
92339 **
92340 **    May you do good and not evil.
92341 **    May you find forgiveness for yourself and forgive others.
92342 **    May you share freely, never taking more than you give.
92343 **
92344 *************************************************************************
92345 ** This file contains code used to help implement virtual tables.
92346 */
92347 #ifndef SQLITE_OMIT_VIRTUALTABLE
92348
92349 /*
92350 ** The actual function that does the work of creating a new module.
92351 ** This function implements the sqlite3_create_module() and
92352 ** sqlite3_create_module_v2() interfaces.
92353 */
92354 static int createModule(
92355   sqlite3 *db,                    /* Database in which module is registered */
92356   const char *zName,              /* Name assigned to this module */
92357   const sqlite3_module *pModule,  /* The definition of the module */
92358   void *pAux,                     /* Context pointer for xCreate/xConnect */
92359   void (*xDestroy)(void *)        /* Module destructor function */
92360 ){
92361   int rc, nName;
92362   Module *pMod;
92363
92364   sqlite3_mutex_enter(db->mutex);
92365   nName = sqlite3Strlen30(zName);
92366   pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
92367   if( pMod ){
92368     Module *pDel;
92369     char *zCopy = (char *)(&pMod[1]);
92370     memcpy(zCopy, zName, nName+1);
92371     pMod->zName = zCopy;
92372     pMod->pModule = pModule;
92373     pMod->pAux = pAux;
92374     pMod->xDestroy = xDestroy;
92375     pDel = (Module *)sqlite3HashInsert(&db->aModule, zCopy, nName, (void*)pMod);
92376     if( pDel && pDel->xDestroy ){
92377       pDel->xDestroy(pDel->pAux);
92378     }
92379     sqlite3DbFree(db, pDel);
92380     if( pDel==pMod ){
92381       db->mallocFailed = 1;
92382     }
92383     sqlite3ResetInternalSchema(db, 0);
92384   }else if( xDestroy ){
92385     xDestroy(pAux);
92386   }
92387   rc = sqlite3ApiExit(db, SQLITE_OK);
92388   sqlite3_mutex_leave(db->mutex);
92389   return rc;
92390 }
92391
92392
92393 /*
92394 ** External API function used to create a new virtual-table module.
92395 */
92396 SQLITE_API int sqlite3_create_module(
92397   sqlite3 *db,                    /* Database in which module is registered */
92398   const char *zName,              /* Name assigned to this module */
92399   const sqlite3_module *pModule,  /* The definition of the module */
92400   void *pAux                      /* Context pointer for xCreate/xConnect */
92401 ){
92402   return createModule(db, zName, pModule, pAux, 0);
92403 }
92404
92405 /*
92406 ** External API function used to create a new virtual-table module.
92407 */
92408 SQLITE_API int sqlite3_create_module_v2(
92409   sqlite3 *db,                    /* Database in which module is registered */
92410   const char *zName,              /* Name assigned to this module */
92411   const sqlite3_module *pModule,  /* The definition of the module */
92412   void *pAux,                     /* Context pointer for xCreate/xConnect */
92413   void (*xDestroy)(void *)        /* Module destructor function */
92414 ){
92415   return createModule(db, zName, pModule, pAux, xDestroy);
92416 }
92417
92418 /*
92419 ** Lock the virtual table so that it cannot be disconnected.
92420 ** Locks nest.  Every lock should have a corresponding unlock.
92421 ** If an unlock is omitted, resources leaks will occur.  
92422 **
92423 ** If a disconnect is attempted while a virtual table is locked,
92424 ** the disconnect is deferred until all locks have been removed.
92425 */
92426 SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
92427   pVTab->nRef++;
92428 }
92429
92430
92431 /*
92432 ** pTab is a pointer to a Table structure representing a virtual-table.
92433 ** Return a pointer to the VTable object used by connection db to access 
92434 ** this virtual-table, if one has been created, or NULL otherwise.
92435 */
92436 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
92437   VTable *pVtab;
92438   assert( IsVirtual(pTab) );
92439   for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
92440   return pVtab;
92441 }
92442
92443 /*
92444 ** Decrement the ref-count on a virtual table object. When the ref-count
92445 ** reaches zero, call the xDisconnect() method to delete the object.
92446 */
92447 SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
92448   sqlite3 *db = pVTab->db;
92449
92450   assert( db );
92451   assert( pVTab->nRef>0 );
92452   assert( sqlite3SafetyCheckOk(db) );
92453
92454   pVTab->nRef--;
92455   if( pVTab->nRef==0 ){
92456     sqlite3_vtab *p = pVTab->pVtab;
92457     if( p ){
92458       p->pModule->xDisconnect(p);
92459     }
92460     sqlite3DbFree(db, pVTab);
92461   }
92462 }
92463
92464 /*
92465 ** Table p is a virtual table. This function moves all elements in the
92466 ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
92467 ** database connections to be disconnected at the next opportunity. 
92468 ** Except, if argument db is not NULL, then the entry associated with
92469 ** connection db is left in the p->pVTable list.
92470 */
92471 static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
92472   VTable *pRet = 0;
92473   VTable *pVTable = p->pVTable;
92474   p->pVTable = 0;
92475
92476   /* Assert that the mutex (if any) associated with the BtShared database 
92477   ** that contains table p is held by the caller. See header comments 
92478   ** above function sqlite3VtabUnlockList() for an explanation of why
92479   ** this makes it safe to access the sqlite3.pDisconnect list of any
92480   ** database connection that may have an entry in the p->pVTable list.  */
92481   assert( db==0 ||
92482     sqlite3BtreeHoldsMutex(db->aDb[sqlite3SchemaToIndex(db, p->pSchema)].pBt) 
92483   );
92484
92485   while( pVTable ){
92486     sqlite3 *db2 = pVTable->db;
92487     VTable *pNext = pVTable->pNext;
92488     assert( db2 );
92489     if( db2==db ){
92490       pRet = pVTable;
92491       p->pVTable = pRet;
92492       pRet->pNext = 0;
92493     }else{
92494       pVTable->pNext = db2->pDisconnect;
92495       db2->pDisconnect = pVTable;
92496     }
92497     pVTable = pNext;
92498   }
92499
92500   assert( !db || pRet );
92501   return pRet;
92502 }
92503
92504
92505 /*
92506 ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
92507 **
92508 ** This function may only be called when the mutexes associated with all
92509 ** shared b-tree databases opened using connection db are held by the 
92510 ** caller. This is done to protect the sqlite3.pDisconnect list. The
92511 ** sqlite3.pDisconnect list is accessed only as follows:
92512 **
92513 **   1) By this function. In this case, all BtShared mutexes and the mutex
92514 **      associated with the database handle itself must be held.
92515 **
92516 **   2) By function vtabDisconnectAll(), when it adds a VTable entry to
92517 **      the sqlite3.pDisconnect list. In this case either the BtShared mutex
92518 **      associated with the database the virtual table is stored in is held
92519 **      or, if the virtual table is stored in a non-sharable database, then
92520 **      the database handle mutex is held.
92521 **
92522 ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously 
92523 ** by multiple threads. It is thread-safe.
92524 */
92525 SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
92526   VTable *p = db->pDisconnect;
92527   db->pDisconnect = 0;
92528
92529   assert( sqlite3BtreeHoldsAllMutexes(db) );
92530   assert( sqlite3_mutex_held(db->mutex) );
92531
92532   if( p ){
92533     sqlite3ExpirePreparedStatements(db);
92534     do {
92535       VTable *pNext = p->pNext;
92536       sqlite3VtabUnlock(p);
92537       p = pNext;
92538     }while( p );
92539   }
92540 }
92541
92542 /*
92543 ** Clear any and all virtual-table information from the Table record.
92544 ** This routine is called, for example, just before deleting the Table
92545 ** record.
92546 **
92547 ** Since it is a virtual-table, the Table structure contains a pointer
92548 ** to the head of a linked list of VTable structures. Each VTable 
92549 ** structure is associated with a single sqlite3* user of the schema.
92550 ** The reference count of the VTable structure associated with database 
92551 ** connection db is decremented immediately (which may lead to the 
92552 ** structure being xDisconnected and free). Any other VTable structures
92553 ** in the list are moved to the sqlite3.pDisconnect list of the associated 
92554 ** database connection.
92555 */
92556 SQLITE_PRIVATE void sqlite3VtabClear(Table *p){
92557   vtabDisconnectAll(0, p);
92558   if( p->azModuleArg ){
92559     int i;
92560     for(i=0; i<p->nModuleArg; i++){
92561       sqlite3DbFree(p->dbMem, p->azModuleArg[i]);
92562     }
92563     sqlite3DbFree(p->dbMem, p->azModuleArg);
92564   }
92565 }
92566
92567 /*
92568 ** Add a new module argument to pTable->azModuleArg[].
92569 ** The string is not copied - the pointer is stored.  The
92570 ** string will be freed automatically when the table is
92571 ** deleted.
92572 */
92573 static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
92574   int i = pTable->nModuleArg++;
92575   int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
92576   char **azModuleArg;
92577   azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
92578   if( azModuleArg==0 ){
92579     int j;
92580     for(j=0; j<i; j++){
92581       sqlite3DbFree(db, pTable->azModuleArg[j]);
92582     }
92583     sqlite3DbFree(db, zArg);
92584     sqlite3DbFree(db, pTable->azModuleArg);
92585     pTable->nModuleArg = 0;
92586   }else{
92587     azModuleArg[i] = zArg;
92588     azModuleArg[i+1] = 0;
92589   }
92590   pTable->azModuleArg = azModuleArg;
92591 }
92592
92593 /*
92594 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
92595 ** statement.  The module name has been parsed, but the optional list
92596 ** of parameters that follow the module name are still pending.
92597 */
92598 SQLITE_PRIVATE void sqlite3VtabBeginParse(
92599   Parse *pParse,        /* Parsing context */
92600   Token *pName1,        /* Name of new table, or database name */
92601   Token *pName2,        /* Name of new table or NULL */
92602   Token *pModuleName    /* Name of the module for the virtual table */
92603 ){
92604   int iDb;              /* The database the table is being created in */
92605   Table *pTable;        /* The new virtual table */
92606   sqlite3 *db;          /* Database connection */
92607
92608   sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, 0);
92609   pTable = pParse->pNewTable;
92610   if( pTable==0 ) return;
92611   assert( 0==pTable->pIndex );
92612
92613   db = pParse->db;
92614   iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
92615   assert( iDb>=0 );
92616
92617   pTable->tabFlags |= TF_Virtual;
92618   pTable->nModuleArg = 0;
92619   addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
92620   addModuleArgument(db, pTable, sqlite3DbStrDup(db, db->aDb[iDb].zName));
92621   addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
92622   pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
92623
92624 #ifndef SQLITE_OMIT_AUTHORIZATION
92625   /* Creating a virtual table invokes the authorization callback twice.
92626   ** The first invocation, to obtain permission to INSERT a row into the
92627   ** sqlite_master table, has already been made by sqlite3StartTable().
92628   ** The second call, to obtain permission to create the table, is made now.
92629   */
92630   if( pTable->azModuleArg ){
92631     sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName, 
92632             pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
92633   }
92634 #endif
92635 }
92636
92637 /*
92638 ** This routine takes the module argument that has been accumulating
92639 ** in pParse->zArg[] and appends it to the list of arguments on the
92640 ** virtual table currently under construction in pParse->pTable.
92641 */
92642 static void addArgumentToVtab(Parse *pParse){
92643   if( pParse->sArg.z && ALWAYS(pParse->pNewTable) ){
92644     const char *z = (const char*)pParse->sArg.z;
92645     int n = pParse->sArg.n;
92646     sqlite3 *db = pParse->db;
92647     addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
92648   }
92649 }
92650
92651 /*
92652 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
92653 ** has been completely parsed.
92654 */
92655 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
92656   Table *pTab = pParse->pNewTable;  /* The table being constructed */
92657   sqlite3 *db = pParse->db;         /* The database connection */
92658
92659   if( pTab==0 ) return;
92660   addArgumentToVtab(pParse);
92661   pParse->sArg.z = 0;
92662   if( pTab->nModuleArg<1 ) return;
92663   
92664   /* If the CREATE VIRTUAL TABLE statement is being entered for the
92665   ** first time (in other words if the virtual table is actually being
92666   ** created now instead of just being read out of sqlite_master) then
92667   ** do additional initialization work and store the statement text
92668   ** in the sqlite_master table.
92669   */
92670   if( !db->init.busy ){
92671     char *zStmt;
92672     char *zWhere;
92673     int iDb;
92674     Vdbe *v;
92675
92676     /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
92677     if( pEnd ){
92678       pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
92679     }
92680     zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
92681
92682     /* A slot for the record has already been allocated in the 
92683     ** SQLITE_MASTER table.  We just need to update that slot with all
92684     ** the information we've collected.  
92685     **
92686     ** The VM register number pParse->regRowid holds the rowid of an
92687     ** entry in the sqlite_master table tht was created for this vtab
92688     ** by sqlite3StartTable().
92689     */
92690     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
92691     sqlite3NestedParse(pParse,
92692       "UPDATE %Q.%s "
92693          "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
92694        "WHERE rowid=#%d",
92695       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
92696       pTab->zName,
92697       pTab->zName,
92698       zStmt,
92699       pParse->regRowid
92700     );
92701     sqlite3DbFree(db, zStmt);
92702     v = sqlite3GetVdbe(pParse);
92703     sqlite3ChangeCookie(pParse, iDb);
92704
92705     sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
92706     zWhere = sqlite3MPrintf(db, "name='%q'", pTab->zName);
92707     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 1, 0, zWhere, P4_DYNAMIC);
92708     sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0, 
92709                          pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
92710   }
92711
92712   /* If we are rereading the sqlite_master table create the in-memory
92713   ** record of the table. The xConnect() method is not called until
92714   ** the first time the virtual table is used in an SQL statement. This
92715   ** allows a schema that contains virtual tables to be loaded before
92716   ** the required virtual table implementations are registered.  */
92717   else {
92718     Table *pOld;
92719     Schema *pSchema = pTab->pSchema;
92720     const char *zName = pTab->zName;
92721     int nName = sqlite3Strlen30(zName);
92722     pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
92723     if( pOld ){
92724       db->mallocFailed = 1;
92725       assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
92726       return;
92727     }
92728     pSchema->db = pParse->db;
92729     pParse->pNewTable = 0;
92730   }
92731 }
92732
92733 /*
92734 ** The parser calls this routine when it sees the first token
92735 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
92736 */
92737 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
92738   addArgumentToVtab(pParse);
92739   pParse->sArg.z = 0;
92740   pParse->sArg.n = 0;
92741 }
92742
92743 /*
92744 ** The parser calls this routine for each token after the first token
92745 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
92746 */
92747 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
92748   Token *pArg = &pParse->sArg;
92749   if( pArg->z==0 ){
92750     pArg->z = p->z;
92751     pArg->n = p->n;
92752   }else{
92753     assert(pArg->z < p->z);
92754     pArg->n = (int)(&p->z[p->n] - pArg->z);
92755   }
92756 }
92757
92758 /*
92759 ** Invoke a virtual table constructor (either xCreate or xConnect). The
92760 ** pointer to the function to invoke is passed as the fourth parameter
92761 ** to this procedure.
92762 */
92763 static int vtabCallConstructor(
92764   sqlite3 *db, 
92765   Table *pTab,
92766   Module *pMod,
92767   int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
92768   char **pzErr
92769 ){
92770   VTable *pVTable;
92771   int rc;
92772   const char *const*azArg = (const char *const*)pTab->azModuleArg;
92773   int nArg = pTab->nModuleArg;
92774   char *zErr = 0;
92775   char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
92776
92777   if( !zModuleName ){
92778     return SQLITE_NOMEM;
92779   }
92780
92781   pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
92782   if( !pVTable ){
92783     sqlite3DbFree(db, zModuleName);
92784     return SQLITE_NOMEM;
92785   }
92786   pVTable->db = db;
92787   pVTable->pMod = pMod;
92788
92789   assert( !db->pVTab );
92790   assert( xConstruct );
92791   db->pVTab = pTab;
92792
92793   /* Invoke the virtual table constructor */
92794   rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
92795   if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
92796
92797   if( SQLITE_OK!=rc ){
92798     if( zErr==0 ){
92799       *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
92800     }else {
92801       *pzErr = sqlite3MPrintf(db, "%s", zErr);
92802       sqlite3DbFree(db, zErr);
92803     }
92804     sqlite3DbFree(db, pVTable);
92805   }else if( ALWAYS(pVTable->pVtab) ){
92806     /* Justification of ALWAYS():  A correct vtab constructor must allocate
92807     ** the sqlite3_vtab object if successful.  */
92808     pVTable->pVtab->pModule = pMod->pModule;
92809     pVTable->nRef = 1;
92810     if( db->pVTab ){
92811       const char *zFormat = "vtable constructor did not declare schema: %s";
92812       *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
92813       sqlite3VtabUnlock(pVTable);
92814       rc = SQLITE_ERROR;
92815     }else{
92816       int iCol;
92817       /* If everything went according to plan, link the new VTable structure
92818       ** into the linked list headed by pTab->pVTable. Then loop through the 
92819       ** columns of the table to see if any of them contain the token "hidden".
92820       ** If so, set the Column.isHidden flag and remove the token from
92821       ** the type string.  */
92822       pVTable->pNext = pTab->pVTable;
92823       pTab->pVTable = pVTable;
92824
92825       for(iCol=0; iCol<pTab->nCol; iCol++){
92826         char *zType = pTab->aCol[iCol].zType;
92827         int nType;
92828         int i = 0;
92829         if( !zType ) continue;
92830         nType = sqlite3Strlen30(zType);
92831         if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
92832           for(i=0; i<nType; i++){
92833             if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
92834              && (zType[i+7]=='\0' || zType[i+7]==' ')
92835             ){
92836               i++;
92837               break;
92838             }
92839           }
92840         }
92841         if( i<nType ){
92842           int j;
92843           int nDel = 6 + (zType[i+6] ? 1 : 0);
92844           for(j=i; (j+nDel)<=nType; j++){
92845             zType[j] = zType[j+nDel];
92846           }
92847           if( zType[i]=='\0' && i>0 ){
92848             assert(zType[i-1]==' ');
92849             zType[i-1] = '\0';
92850           }
92851           pTab->aCol[iCol].isHidden = 1;
92852         }
92853       }
92854     }
92855   }
92856
92857   sqlite3DbFree(db, zModuleName);
92858   db->pVTab = 0;
92859   return rc;
92860 }
92861
92862 /*
92863 ** This function is invoked by the parser to call the xConnect() method
92864 ** of the virtual table pTab. If an error occurs, an error code is returned 
92865 ** and an error left in pParse.
92866 **
92867 ** This call is a no-op if table pTab is not a virtual table.
92868 */
92869 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
92870   sqlite3 *db = pParse->db;
92871   const char *zMod;
92872   Module *pMod;
92873   int rc;
92874
92875   assert( pTab );
92876   if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
92877     return SQLITE_OK;
92878   }
92879
92880   /* Locate the required virtual table module */
92881   zMod = pTab->azModuleArg[0];
92882   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
92883
92884   if( !pMod ){
92885     const char *zModule = pTab->azModuleArg[0];
92886     sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
92887     rc = SQLITE_ERROR;
92888   }else{
92889     char *zErr = 0;
92890     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
92891     if( rc!=SQLITE_OK ){
92892       sqlite3ErrorMsg(pParse, "%s", zErr);
92893     }
92894     sqlite3DbFree(db, zErr);
92895   }
92896
92897   return rc;
92898 }
92899
92900 /*
92901 ** Add the virtual table pVTab to the array sqlite3.aVTrans[].
92902 */
92903 static int addToVTrans(sqlite3 *db, VTable *pVTab){
92904   const int ARRAY_INCR = 5;
92905
92906   /* Grow the sqlite3.aVTrans array if required */
92907   if( (db->nVTrans%ARRAY_INCR)==0 ){
92908     VTable **aVTrans;
92909     int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
92910     aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
92911     if( !aVTrans ){
92912       return SQLITE_NOMEM;
92913     }
92914     memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
92915     db->aVTrans = aVTrans;
92916   }
92917
92918   /* Add pVtab to the end of sqlite3.aVTrans */
92919   db->aVTrans[db->nVTrans++] = pVTab;
92920   sqlite3VtabLock(pVTab);
92921   return SQLITE_OK;
92922 }
92923
92924 /*
92925 ** This function is invoked by the vdbe to call the xCreate method
92926 ** of the virtual table named zTab in database iDb. 
92927 **
92928 ** If an error occurs, *pzErr is set to point an an English language
92929 ** description of the error and an SQLITE_XXX error code is returned.
92930 ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
92931 */
92932 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
92933   int rc = SQLITE_OK;
92934   Table *pTab;
92935   Module *pMod;
92936   const char *zMod;
92937
92938   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
92939   assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
92940
92941   /* Locate the required virtual table module */
92942   zMod = pTab->azModuleArg[0];
92943   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
92944
92945   /* If the module has been registered and includes a Create method, 
92946   ** invoke it now. If the module has not been registered, return an 
92947   ** error. Otherwise, do nothing.
92948   */
92949   if( !pMod ){
92950     *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
92951     rc = SQLITE_ERROR;
92952   }else{
92953     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
92954   }
92955
92956   /* Justification of ALWAYS():  The xConstructor method is required to
92957   ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
92958   if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
92959       rc = addToVTrans(db, sqlite3GetVTable(db, pTab));
92960   }
92961
92962   return rc;
92963 }
92964
92965 /*
92966 ** This function is used to set the schema of a virtual table.  It is only
92967 ** valid to call this function from within the xCreate() or xConnect() of a
92968 ** virtual table module.
92969 */
92970 SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
92971   Parse *pParse;
92972
92973   int rc = SQLITE_OK;
92974   Table *pTab;
92975   char *zErr = 0;
92976
92977   sqlite3_mutex_enter(db->mutex);
92978   pTab = db->pVTab;
92979   if( !pTab ){
92980     sqlite3Error(db, SQLITE_MISUSE, 0);
92981     sqlite3_mutex_leave(db->mutex);
92982     return SQLITE_MISUSE_BKPT;
92983   }
92984   assert( (pTab->tabFlags & TF_Virtual)!=0 );
92985
92986   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
92987   if( pParse==0 ){
92988     rc = SQLITE_NOMEM;
92989   }else{
92990     pParse->declareVtab = 1;
92991     pParse->db = db;
92992     pParse->nQueryLoop = 1;
92993   
92994     if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr) 
92995      && pParse->pNewTable
92996      && !db->mallocFailed
92997      && !pParse->pNewTable->pSelect
92998      && (pParse->pNewTable->tabFlags & TF_Virtual)==0
92999     ){
93000       if( !pTab->aCol ){
93001         pTab->aCol = pParse->pNewTable->aCol;
93002         pTab->nCol = pParse->pNewTable->nCol;
93003         pParse->pNewTable->nCol = 0;
93004         pParse->pNewTable->aCol = 0;
93005       }
93006       db->pVTab = 0;
93007     }else{
93008       sqlite3Error(db, SQLITE_ERROR, zErr);
93009       sqlite3DbFree(db, zErr);
93010       rc = SQLITE_ERROR;
93011     }
93012     pParse->declareVtab = 0;
93013   
93014     if( pParse->pVdbe ){
93015       sqlite3VdbeFinalize(pParse->pVdbe);
93016     }
93017     sqlite3DeleteTable(pParse->pNewTable);
93018     sqlite3StackFree(db, pParse);
93019   }
93020
93021   assert( (rc&0xff)==rc );
93022   rc = sqlite3ApiExit(db, rc);
93023   sqlite3_mutex_leave(db->mutex);
93024   return rc;
93025 }
93026
93027 /*
93028 ** This function is invoked by the vdbe to call the xDestroy method
93029 ** of the virtual table named zTab in database iDb. This occurs
93030 ** when a DROP TABLE is mentioned.
93031 **
93032 ** This call is a no-op if zTab is not a virtual table.
93033 */
93034 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
93035   int rc = SQLITE_OK;
93036   Table *pTab;
93037
93038   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
93039   if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
93040     VTable *p = vtabDisconnectAll(db, pTab);
93041
93042     assert( rc==SQLITE_OK );
93043     rc = p->pMod->pModule->xDestroy(p->pVtab);
93044
93045     /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
93046     if( rc==SQLITE_OK ){
93047       assert( pTab->pVTable==p && p->pNext==0 );
93048       p->pVtab = 0;
93049       pTab->pVTable = 0;
93050       sqlite3VtabUnlock(p);
93051     }
93052   }
93053
93054   return rc;
93055 }
93056
93057 /*
93058 ** This function invokes either the xRollback or xCommit method
93059 ** of each of the virtual tables in the sqlite3.aVTrans array. The method
93060 ** called is identified by the second argument, "offset", which is
93061 ** the offset of the method to call in the sqlite3_module structure.
93062 **
93063 ** The array is cleared after invoking the callbacks. 
93064 */
93065 static void callFinaliser(sqlite3 *db, int offset){
93066   int i;
93067   if( db->aVTrans ){
93068     for(i=0; i<db->nVTrans; i++){
93069       VTable *pVTab = db->aVTrans[i];
93070       sqlite3_vtab *p = pVTab->pVtab;
93071       if( p ){
93072         int (*x)(sqlite3_vtab *);
93073         x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
93074         if( x ) x(p);
93075       }
93076       sqlite3VtabUnlock(pVTab);
93077     }
93078     sqlite3DbFree(db, db->aVTrans);
93079     db->nVTrans = 0;
93080     db->aVTrans = 0;
93081   }
93082 }
93083
93084 /*
93085 ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
93086 ** array. Return the error code for the first error that occurs, or
93087 ** SQLITE_OK if all xSync operations are successful.
93088 **
93089 ** Set *pzErrmsg to point to a buffer that should be released using 
93090 ** sqlite3DbFree() containing an error message, if one is available.
93091 */
93092 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **pzErrmsg){
93093   int i;
93094   int rc = SQLITE_OK;
93095   VTable **aVTrans = db->aVTrans;
93096
93097   db->aVTrans = 0;
93098   for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
93099     int (*x)(sqlite3_vtab *);
93100     sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
93101     if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
93102       rc = x(pVtab);
93103       sqlite3DbFree(db, *pzErrmsg);
93104       *pzErrmsg = pVtab->zErrMsg;
93105       pVtab->zErrMsg = 0;
93106     }
93107   }
93108   db->aVTrans = aVTrans;
93109   return rc;
93110 }
93111
93112 /*
93113 ** Invoke the xRollback method of all virtual tables in the 
93114 ** sqlite3.aVTrans array. Then clear the array itself.
93115 */
93116 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
93117   callFinaliser(db, offsetof(sqlite3_module,xRollback));
93118   return SQLITE_OK;
93119 }
93120
93121 /*
93122 ** Invoke the xCommit method of all virtual tables in the 
93123 ** sqlite3.aVTrans array. Then clear the array itself.
93124 */
93125 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
93126   callFinaliser(db, offsetof(sqlite3_module,xCommit));
93127   return SQLITE_OK;
93128 }
93129
93130 /*
93131 ** If the virtual table pVtab supports the transaction interface
93132 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
93133 ** not currently open, invoke the xBegin method now.
93134 **
93135 ** If the xBegin call is successful, place the sqlite3_vtab pointer
93136 ** in the sqlite3.aVTrans array.
93137 */
93138 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
93139   int rc = SQLITE_OK;
93140   const sqlite3_module *pModule;
93141
93142   /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
93143   ** than zero, then this function is being called from within a
93144   ** virtual module xSync() callback. It is illegal to write to 
93145   ** virtual module tables in this case, so return SQLITE_LOCKED.
93146   */
93147   if( sqlite3VtabInSync(db) ){
93148     return SQLITE_LOCKED;
93149   }
93150   if( !pVTab ){
93151     return SQLITE_OK;
93152   } 
93153   pModule = pVTab->pVtab->pModule;
93154
93155   if( pModule->xBegin ){
93156     int i;
93157
93158
93159     /* If pVtab is already in the aVTrans array, return early */
93160     for(i=0; i<db->nVTrans; i++){
93161       if( db->aVTrans[i]==pVTab ){
93162         return SQLITE_OK;
93163       }
93164     }
93165
93166     /* Invoke the xBegin method */
93167     rc = pModule->xBegin(pVTab->pVtab);
93168     if( rc==SQLITE_OK ){
93169       rc = addToVTrans(db, pVTab);
93170     }
93171   }
93172   return rc;
93173 }
93174
93175 /*
93176 ** The first parameter (pDef) is a function implementation.  The
93177 ** second parameter (pExpr) is the first argument to this function.
93178 ** If pExpr is a column in a virtual table, then let the virtual
93179 ** table implementation have an opportunity to overload the function.
93180 **
93181 ** This routine is used to allow virtual table implementations to
93182 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
93183 **
93184 ** Return either the pDef argument (indicating no change) or a 
93185 ** new FuncDef structure that is marked as ephemeral using the
93186 ** SQLITE_FUNC_EPHEM flag.
93187 */
93188 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
93189   sqlite3 *db,    /* Database connection for reporting malloc problems */
93190   FuncDef *pDef,  /* Function to possibly overload */
93191   int nArg,       /* Number of arguments to the function */
93192   Expr *pExpr     /* First argument to the function */
93193 ){
93194   Table *pTab;
93195   sqlite3_vtab *pVtab;
93196   sqlite3_module *pMod;
93197   void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
93198   void *pArg = 0;
93199   FuncDef *pNew;
93200   int rc = 0;
93201   char *zLowerName;
93202   unsigned char *z;
93203
93204
93205   /* Check to see the left operand is a column in a virtual table */
93206   if( NEVER(pExpr==0) ) return pDef;
93207   if( pExpr->op!=TK_COLUMN ) return pDef;
93208   pTab = pExpr->pTab;
93209   if( NEVER(pTab==0) ) return pDef;
93210   if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
93211   pVtab = sqlite3GetVTable(db, pTab)->pVtab;
93212   assert( pVtab!=0 );
93213   assert( pVtab->pModule!=0 );
93214   pMod = (sqlite3_module *)pVtab->pModule;
93215   if( pMod->xFindFunction==0 ) return pDef;
93216  
93217   /* Call the xFindFunction method on the virtual table implementation
93218   ** to see if the implementation wants to overload this function 
93219   */
93220   zLowerName = sqlite3DbStrDup(db, pDef->zName);
93221   if( zLowerName ){
93222     for(z=(unsigned char*)zLowerName; *z; z++){
93223       *z = sqlite3UpperToLower[*z];
93224     }
93225     rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
93226     sqlite3DbFree(db, zLowerName);
93227   }
93228   if( rc==0 ){
93229     return pDef;
93230   }
93231
93232   /* Create a new ephemeral function definition for the overloaded
93233   ** function */
93234   pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
93235                              + sqlite3Strlen30(pDef->zName) + 1);
93236   if( pNew==0 ){
93237     return pDef;
93238   }
93239   *pNew = *pDef;
93240   pNew->zName = (char *)&pNew[1];
93241   memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
93242   pNew->xFunc = xFunc;
93243   pNew->pUserData = pArg;
93244   pNew->flags |= SQLITE_FUNC_EPHEM;
93245   return pNew;
93246 }
93247
93248 /*
93249 ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
93250 ** array so that an OP_VBegin will get generated for it.  Add pTab to the
93251 ** array if it is missing.  If pTab is already in the array, this routine
93252 ** is a no-op.
93253 */
93254 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
93255   Parse *pToplevel = sqlite3ParseToplevel(pParse);
93256   int i, n;
93257   Table **apVtabLock;
93258
93259   assert( IsVirtual(pTab) );
93260   for(i=0; i<pToplevel->nVtabLock; i++){
93261     if( pTab==pToplevel->apVtabLock[i] ) return;
93262   }
93263   n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
93264   apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
93265   if( apVtabLock ){
93266     pToplevel->apVtabLock = apVtabLock;
93267     pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
93268   }else{
93269     pToplevel->db->mallocFailed = 1;
93270   }
93271 }
93272
93273 #endif /* SQLITE_OMIT_VIRTUALTABLE */
93274
93275 /************** End of vtab.c ************************************************/
93276 /************** Begin file where.c *******************************************/
93277 /*
93278 ** 2001 September 15
93279 **
93280 ** The author disclaims copyright to this source code.  In place of
93281 ** a legal notice, here is a blessing:
93282 **
93283 **    May you do good and not evil.
93284 **    May you find forgiveness for yourself and forgive others.
93285 **    May you share freely, never taking more than you give.
93286 **
93287 *************************************************************************
93288 ** This module contains C code that generates VDBE code used to process
93289 ** the WHERE clause of SQL statements.  This module is responsible for
93290 ** generating the code that loops through a table looking for applicable
93291 ** rows.  Indices are selected and used to speed the search when doing
93292 ** so is applicable.  Because this module is responsible for selecting
93293 ** indices, you might also think of this module as the "query optimizer".
93294 */
93295
93296 /*
93297 ** Trace output macros
93298 */
93299 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
93300 SQLITE_PRIVATE int sqlite3WhereTrace = 0;
93301 #endif
93302 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
93303 # define WHERETRACE(X)  if(sqlite3WhereTrace) sqlite3DebugPrintf X
93304 #else
93305 # define WHERETRACE(X)
93306 #endif
93307
93308 /* Forward reference
93309 */
93310 typedef struct WhereClause WhereClause;
93311 typedef struct WhereMaskSet WhereMaskSet;
93312 typedef struct WhereOrInfo WhereOrInfo;
93313 typedef struct WhereAndInfo WhereAndInfo;
93314 typedef struct WhereCost WhereCost;
93315
93316 /*
93317 ** The query generator uses an array of instances of this structure to
93318 ** help it analyze the subexpressions of the WHERE clause.  Each WHERE
93319 ** clause subexpression is separated from the others by AND operators,
93320 ** usually, or sometimes subexpressions separated by OR.
93321 **
93322 ** All WhereTerms are collected into a single WhereClause structure.  
93323 ** The following identity holds:
93324 **
93325 **        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
93326 **
93327 ** When a term is of the form:
93328 **
93329 **              X <op> <expr>
93330 **
93331 ** where X is a column name and <op> is one of certain operators,
93332 ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
93333 ** cursor number and column number for X.  WhereTerm.eOperator records
93334 ** the <op> using a bitmask encoding defined by WO_xxx below.  The
93335 ** use of a bitmask encoding for the operator allows us to search
93336 ** quickly for terms that match any of several different operators.
93337 **
93338 ** A WhereTerm might also be two or more subterms connected by OR:
93339 **
93340 **         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
93341 **
93342 ** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
93343 ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
93344 ** is collected about the
93345 **
93346 ** If a term in the WHERE clause does not match either of the two previous
93347 ** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
93348 ** to the original subexpression content and wtFlags is set up appropriately
93349 ** but no other fields in the WhereTerm object are meaningful.
93350 **
93351 ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
93352 ** but they do so indirectly.  A single WhereMaskSet structure translates
93353 ** cursor number into bits and the translated bit is stored in the prereq
93354 ** fields.  The translation is used in order to maximize the number of
93355 ** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
93356 ** spread out over the non-negative integers.  For example, the cursor
93357 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
93358 ** translates these sparse cursor numbers into consecutive integers
93359 ** beginning with 0 in order to make the best possible use of the available
93360 ** bits in the Bitmask.  So, in the example above, the cursor numbers
93361 ** would be mapped into integers 0 through 7.
93362 **
93363 ** The number of terms in a join is limited by the number of bits
93364 ** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
93365 ** is only able to process joins with 64 or fewer tables.
93366 */
93367 typedef struct WhereTerm WhereTerm;
93368 struct WhereTerm {
93369   Expr *pExpr;            /* Pointer to the subexpression that is this term */
93370   int iParent;            /* Disable pWC->a[iParent] when this term disabled */
93371   int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
93372   union {
93373     int leftColumn;         /* Column number of X in "X <op> <expr>" */
93374     WhereOrInfo *pOrInfo;   /* Extra information if eOperator==WO_OR */
93375     WhereAndInfo *pAndInfo; /* Extra information if eOperator==WO_AND */
93376   } u;
93377   u16 eOperator;          /* A WO_xx value describing <op> */
93378   u8 wtFlags;             /* TERM_xxx bit flags.  See below */
93379   u8 nChild;              /* Number of children that must disable us */
93380   WhereClause *pWC;       /* The clause this term is part of */
93381   Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
93382   Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
93383 };
93384
93385 /*
93386 ** Allowed values of WhereTerm.wtFlags
93387 */
93388 #define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
93389 #define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
93390 #define TERM_CODED      0x04   /* This term is already coded */
93391 #define TERM_COPIED     0x08   /* Has a child */
93392 #define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
93393 #define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
93394 #define TERM_OR_OK      0x40   /* Used during OR-clause processing */
93395
93396 /*
93397 ** An instance of the following structure holds all information about a
93398 ** WHERE clause.  Mostly this is a container for one or more WhereTerms.
93399 */
93400 struct WhereClause {
93401   Parse *pParse;           /* The parser context */
93402   WhereMaskSet *pMaskSet;  /* Mapping of table cursor numbers to bitmasks */
93403   Bitmask vmask;           /* Bitmask identifying virtual table cursors */
93404   u8 op;                   /* Split operator.  TK_AND or TK_OR */
93405   int nTerm;               /* Number of terms */
93406   int nSlot;               /* Number of entries in a[] */
93407   WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
93408 #if defined(SQLITE_SMALL_STACK)
93409   WhereTerm aStatic[1];    /* Initial static space for a[] */
93410 #else
93411   WhereTerm aStatic[8];    /* Initial static space for a[] */
93412 #endif
93413 };
93414
93415 /*
93416 ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
93417 ** a dynamically allocated instance of the following structure.
93418 */
93419 struct WhereOrInfo {
93420   WhereClause wc;          /* Decomposition into subterms */
93421   Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
93422 };
93423
93424 /*
93425 ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
93426 ** a dynamically allocated instance of the following structure.
93427 */
93428 struct WhereAndInfo {
93429   WhereClause wc;          /* The subexpression broken out */
93430 };
93431
93432 /*
93433 ** An instance of the following structure keeps track of a mapping
93434 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
93435 **
93436 ** The VDBE cursor numbers are small integers contained in 
93437 ** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE 
93438 ** clause, the cursor numbers might not begin with 0 and they might
93439 ** contain gaps in the numbering sequence.  But we want to make maximum
93440 ** use of the bits in our bitmasks.  This structure provides a mapping
93441 ** from the sparse cursor numbers into consecutive integers beginning
93442 ** with 0.
93443 **
93444 ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
93445 ** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
93446 **
93447 ** For example, if the WHERE clause expression used these VDBE
93448 ** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
93449 ** would map those cursor numbers into bits 0 through 5.
93450 **
93451 ** Note that the mapping is not necessarily ordered.  In the example
93452 ** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
93453 ** 57->5, 73->4.  Or one of 719 other combinations might be used. It
93454 ** does not really matter.  What is important is that sparse cursor
93455 ** numbers all get mapped into bit numbers that begin with 0 and contain
93456 ** no gaps.
93457 */
93458 struct WhereMaskSet {
93459   int n;                        /* Number of assigned cursor values */
93460   int ix[BMS];                  /* Cursor assigned to each bit */
93461 };
93462
93463 /*
93464 ** A WhereCost object records a lookup strategy and the estimated
93465 ** cost of pursuing that strategy.
93466 */
93467 struct WhereCost {
93468   WherePlan plan;    /* The lookup strategy */
93469   double rCost;      /* Overall cost of pursuing this search strategy */
93470   double nRow;       /* Estimated number of output rows */
93471   Bitmask used;      /* Bitmask of cursors used by this plan */
93472 };
93473
93474 /*
93475 ** Bitmasks for the operators that indices are able to exploit.  An
93476 ** OR-ed combination of these values can be used when searching for
93477 ** terms in the where clause.
93478 */
93479 #define WO_IN     0x001
93480 #define WO_EQ     0x002
93481 #define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
93482 #define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
93483 #define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
93484 #define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
93485 #define WO_MATCH  0x040
93486 #define WO_ISNULL 0x080
93487 #define WO_OR     0x100       /* Two or more OR-connected terms */
93488 #define WO_AND    0x200       /* Two or more AND-connected terms */
93489
93490 #define WO_ALL    0xfff       /* Mask of all possible WO_* values */
93491 #define WO_SINGLE 0x0ff       /* Mask of all non-compound WO_* values */
93492
93493 /*
93494 ** Value for wsFlags returned by bestIndex() and stored in
93495 ** WhereLevel.wsFlags.  These flags determine which search
93496 ** strategies are appropriate.
93497 **
93498 ** The least significant 12 bits is reserved as a mask for WO_ values above.
93499 ** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
93500 ** But if the table is the right table of a left join, WhereLevel.wsFlags
93501 ** is set to WO_IN|WO_EQ.  The WhereLevel.wsFlags field can then be used as
93502 ** the "op" parameter to findTerm when we are resolving equality constraints.
93503 ** ISNULL constraints will then not be used on the right table of a left
93504 ** join.  Tickets #2177 and #2189.
93505 */
93506 #define WHERE_ROWID_EQ     0x00001000  /* rowid=EXPR or rowid IN (...) */
93507 #define WHERE_ROWID_RANGE  0x00002000  /* rowid<EXPR and/or rowid>EXPR */
93508 #define WHERE_COLUMN_EQ    0x00010000  /* x=EXPR or x IN (...) or x IS NULL */
93509 #define WHERE_COLUMN_RANGE 0x00020000  /* x<EXPR and/or x>EXPR */
93510 #define WHERE_COLUMN_IN    0x00040000  /* x IN (...) */
93511 #define WHERE_COLUMN_NULL  0x00080000  /* x IS NULL */
93512 #define WHERE_INDEXED      0x000f0000  /* Anything that uses an index */
93513 #define WHERE_NOT_FULLSCAN 0x000f3000  /* Does not do a full table scan */
93514 #define WHERE_IN_ABLE      0x000f1000  /* Able to support an IN operator */
93515 #define WHERE_TOP_LIMIT    0x00100000  /* x<EXPR or x<=EXPR constraint */
93516 #define WHERE_BTM_LIMIT    0x00200000  /* x>EXPR or x>=EXPR constraint */
93517 #define WHERE_IDX_ONLY     0x00800000  /* Use index only - omit table */
93518 #define WHERE_ORDERBY      0x01000000  /* Output will appear in correct order */
93519 #define WHERE_REVERSE      0x02000000  /* Scan in reverse order */
93520 #define WHERE_UNIQUE       0x04000000  /* Selects no more than one row */
93521 #define WHERE_VIRTUALTABLE 0x08000000  /* Use virtual-table processing */
93522 #define WHERE_MULTI_OR     0x10000000  /* OR using multiple indices */
93523 #define WHERE_TEMP_INDEX   0x20000000  /* Uses an ephemeral index */
93524
93525 /*
93526 ** Initialize a preallocated WhereClause structure.
93527 */
93528 static void whereClauseInit(
93529   WhereClause *pWC,        /* The WhereClause to be initialized */
93530   Parse *pParse,           /* The parsing context */
93531   WhereMaskSet *pMaskSet   /* Mapping from table cursor numbers to bitmasks */
93532 ){
93533   pWC->pParse = pParse;
93534   pWC->pMaskSet = pMaskSet;
93535   pWC->nTerm = 0;
93536   pWC->nSlot = ArraySize(pWC->aStatic);
93537   pWC->a = pWC->aStatic;
93538   pWC->vmask = 0;
93539 }
93540
93541 /* Forward reference */
93542 static void whereClauseClear(WhereClause*);
93543
93544 /*
93545 ** Deallocate all memory associated with a WhereOrInfo object.
93546 */
93547 static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
93548   whereClauseClear(&p->wc);
93549   sqlite3DbFree(db, p);
93550 }
93551
93552 /*
93553 ** Deallocate all memory associated with a WhereAndInfo object.
93554 */
93555 static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
93556   whereClauseClear(&p->wc);
93557   sqlite3DbFree(db, p);
93558 }
93559
93560 /*
93561 ** Deallocate a WhereClause structure.  The WhereClause structure
93562 ** itself is not freed.  This routine is the inverse of whereClauseInit().
93563 */
93564 static void whereClauseClear(WhereClause *pWC){
93565   int i;
93566   WhereTerm *a;
93567   sqlite3 *db = pWC->pParse->db;
93568   for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
93569     if( a->wtFlags & TERM_DYNAMIC ){
93570       sqlite3ExprDelete(db, a->pExpr);
93571     }
93572     if( a->wtFlags & TERM_ORINFO ){
93573       whereOrInfoDelete(db, a->u.pOrInfo);
93574     }else if( a->wtFlags & TERM_ANDINFO ){
93575       whereAndInfoDelete(db, a->u.pAndInfo);
93576     }
93577   }
93578   if( pWC->a!=pWC->aStatic ){
93579     sqlite3DbFree(db, pWC->a);
93580   }
93581 }
93582
93583 /*
93584 ** Add a single new WhereTerm entry to the WhereClause object pWC.
93585 ** The new WhereTerm object is constructed from Expr p and with wtFlags.
93586 ** The index in pWC->a[] of the new WhereTerm is returned on success.
93587 ** 0 is returned if the new WhereTerm could not be added due to a memory
93588 ** allocation error.  The memory allocation failure will be recorded in
93589 ** the db->mallocFailed flag so that higher-level functions can detect it.
93590 **
93591 ** This routine will increase the size of the pWC->a[] array as necessary.
93592 **
93593 ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
93594 ** for freeing the expression p is assumed by the WhereClause object pWC.
93595 ** This is true even if this routine fails to allocate a new WhereTerm.
93596 **
93597 ** WARNING:  This routine might reallocate the space used to store
93598 ** WhereTerms.  All pointers to WhereTerms should be invalidated after
93599 ** calling this routine.  Such pointers may be reinitialized by referencing
93600 ** the pWC->a[] array.
93601 */
93602 static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
93603   WhereTerm *pTerm;
93604   int idx;
93605   if( pWC->nTerm>=pWC->nSlot ){
93606     WhereTerm *pOld = pWC->a;
93607     sqlite3 *db = pWC->pParse->db;
93608     pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
93609     if( pWC->a==0 ){
93610       if( wtFlags & TERM_DYNAMIC ){
93611         sqlite3ExprDelete(db, p);
93612       }
93613       pWC->a = pOld;
93614       return 0;
93615     }
93616     memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
93617     if( pOld!=pWC->aStatic ){
93618       sqlite3DbFree(db, pOld);
93619     }
93620     pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
93621   }
93622   pTerm = &pWC->a[idx = pWC->nTerm++];
93623   pTerm->pExpr = p;
93624   pTerm->wtFlags = wtFlags;
93625   pTerm->pWC = pWC;
93626   pTerm->iParent = -1;
93627   return idx;
93628 }
93629
93630 /*
93631 ** This routine identifies subexpressions in the WHERE clause where
93632 ** each subexpression is separated by the AND operator or some other
93633 ** operator specified in the op parameter.  The WhereClause structure
93634 ** is filled with pointers to subexpressions.  For example:
93635 **
93636 **    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
93637 **           \________/     \_______________/     \________________/
93638 **            slot[0]            slot[1]               slot[2]
93639 **
93640 ** The original WHERE clause in pExpr is unaltered.  All this routine
93641 ** does is make slot[] entries point to substructure within pExpr.
93642 **
93643 ** In the previous sentence and in the diagram, "slot[]" refers to
93644 ** the WhereClause.a[] array.  The slot[] array grows as needed to contain
93645 ** all terms of the WHERE clause.
93646 */
93647 static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
93648   pWC->op = (u8)op;
93649   if( pExpr==0 ) return;
93650   if( pExpr->op!=op ){
93651     whereClauseInsert(pWC, pExpr, 0);
93652   }else{
93653     whereSplit(pWC, pExpr->pLeft, op);
93654     whereSplit(pWC, pExpr->pRight, op);
93655   }
93656 }
93657
93658 /*
93659 ** Initialize an expression mask set (a WhereMaskSet object)
93660 */
93661 #define initMaskSet(P)  memset(P, 0, sizeof(*P))
93662
93663 /*
93664 ** Return the bitmask for the given cursor number.  Return 0 if
93665 ** iCursor is not in the set.
93666 */
93667 static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
93668   int i;
93669   assert( pMaskSet->n<=sizeof(Bitmask)*8 );
93670   for(i=0; i<pMaskSet->n; i++){
93671     if( pMaskSet->ix[i]==iCursor ){
93672       return ((Bitmask)1)<<i;
93673     }
93674   }
93675   return 0;
93676 }
93677
93678 /*
93679 ** Create a new mask for cursor iCursor.
93680 **
93681 ** There is one cursor per table in the FROM clause.  The number of
93682 ** tables in the FROM clause is limited by a test early in the
93683 ** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
93684 ** array will never overflow.
93685 */
93686 static void createMask(WhereMaskSet *pMaskSet, int iCursor){
93687   assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
93688   pMaskSet->ix[pMaskSet->n++] = iCursor;
93689 }
93690
93691 /*
93692 ** This routine walks (recursively) an expression tree and generates
93693 ** a bitmask indicating which tables are used in that expression
93694 ** tree.
93695 **
93696 ** In order for this routine to work, the calling function must have
93697 ** previously invoked sqlite3ResolveExprNames() on the expression.  See
93698 ** the header comment on that routine for additional information.
93699 ** The sqlite3ResolveExprNames() routines looks for column names and
93700 ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
93701 ** the VDBE cursor number of the table.  This routine just has to
93702 ** translate the cursor numbers into bitmask values and OR all
93703 ** the bitmasks together.
93704 */
93705 static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
93706 static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
93707 static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
93708   Bitmask mask = 0;
93709   if( p==0 ) return 0;
93710   if( p->op==TK_COLUMN ){
93711     mask = getMask(pMaskSet, p->iTable);
93712     return mask;
93713   }
93714   mask = exprTableUsage(pMaskSet, p->pRight);
93715   mask |= exprTableUsage(pMaskSet, p->pLeft);
93716   if( ExprHasProperty(p, EP_xIsSelect) ){
93717     mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
93718   }else{
93719     mask |= exprListTableUsage(pMaskSet, p->x.pList);
93720   }
93721   return mask;
93722 }
93723 static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
93724   int i;
93725   Bitmask mask = 0;
93726   if( pList ){
93727     for(i=0; i<pList->nExpr; i++){
93728       mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
93729     }
93730   }
93731   return mask;
93732 }
93733 static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
93734   Bitmask mask = 0;
93735   while( pS ){
93736     mask |= exprListTableUsage(pMaskSet, pS->pEList);
93737     mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
93738     mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
93739     mask |= exprTableUsage(pMaskSet, pS->pWhere);
93740     mask |= exprTableUsage(pMaskSet, pS->pHaving);
93741     pS = pS->pPrior;
93742   }
93743   return mask;
93744 }
93745
93746 /*
93747 ** Return TRUE if the given operator is one of the operators that is
93748 ** allowed for an indexable WHERE clause term.  The allowed operators are
93749 ** "=", "<", ">", "<=", ">=", and "IN".
93750 */
93751 static int allowedOp(int op){
93752   assert( TK_GT>TK_EQ && TK_GT<TK_GE );
93753   assert( TK_LT>TK_EQ && TK_LT<TK_GE );
93754   assert( TK_LE>TK_EQ && TK_LE<TK_GE );
93755   assert( TK_GE==TK_EQ+4 );
93756   return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
93757 }
93758
93759 /*
93760 ** Swap two objects of type TYPE.
93761 */
93762 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
93763
93764 /*
93765 ** Commute a comparison operator.  Expressions of the form "X op Y"
93766 ** are converted into "Y op X".
93767 **
93768 ** If a collation sequence is associated with either the left or right
93769 ** side of the comparison, it remains associated with the same side after
93770 ** the commutation. So "Y collate NOCASE op X" becomes 
93771 ** "X collate NOCASE op Y". This is because any collation sequence on
93772 ** the left hand side of a comparison overrides any collation sequence 
93773 ** attached to the right. For the same reason the EP_ExpCollate flag
93774 ** is not commuted.
93775 */
93776 static void exprCommute(Parse *pParse, Expr *pExpr){
93777   u16 expRight = (pExpr->pRight->flags & EP_ExpCollate);
93778   u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate);
93779   assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
93780   pExpr->pRight->pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
93781   pExpr->pLeft->pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
93782   SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
93783   pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft;
93784   pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight;
93785   SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
93786   if( pExpr->op>=TK_GT ){
93787     assert( TK_LT==TK_GT+2 );
93788     assert( TK_GE==TK_LE+2 );
93789     assert( TK_GT>TK_EQ );
93790     assert( TK_GT<TK_LE );
93791     assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
93792     pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
93793   }
93794 }
93795
93796 /*
93797 ** Translate from TK_xx operator to WO_xx bitmask.
93798 */
93799 static u16 operatorMask(int op){
93800   u16 c;
93801   assert( allowedOp(op) );
93802   if( op==TK_IN ){
93803     c = WO_IN;
93804   }else if( op==TK_ISNULL ){
93805     c = WO_ISNULL;
93806   }else{
93807     assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
93808     c = (u16)(WO_EQ<<(op-TK_EQ));
93809   }
93810   assert( op!=TK_ISNULL || c==WO_ISNULL );
93811   assert( op!=TK_IN || c==WO_IN );
93812   assert( op!=TK_EQ || c==WO_EQ );
93813   assert( op!=TK_LT || c==WO_LT );
93814   assert( op!=TK_LE || c==WO_LE );
93815   assert( op!=TK_GT || c==WO_GT );
93816   assert( op!=TK_GE || c==WO_GE );
93817   return c;
93818 }
93819
93820 /*
93821 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
93822 ** where X is a reference to the iColumn of table iCur and <op> is one of
93823 ** the WO_xx operator codes specified by the op parameter.
93824 ** Return a pointer to the term.  Return 0 if not found.
93825 */
93826 static WhereTerm *findTerm(
93827   WhereClause *pWC,     /* The WHERE clause to be searched */
93828   int iCur,             /* Cursor number of LHS */
93829   int iColumn,          /* Column number of LHS */
93830   Bitmask notReady,     /* RHS must not overlap with this mask */
93831   u32 op,               /* Mask of WO_xx values describing operator */
93832   Index *pIdx           /* Must be compatible with this index, if not NULL */
93833 ){
93834   WhereTerm *pTerm;
93835   int k;
93836   assert( iCur>=0 );
93837   op &= WO_ALL;
93838   for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
93839     if( pTerm->leftCursor==iCur
93840        && (pTerm->prereqRight & notReady)==0
93841        && pTerm->u.leftColumn==iColumn
93842        && (pTerm->eOperator & op)!=0
93843     ){
93844       if( pIdx && pTerm->eOperator!=WO_ISNULL ){
93845         Expr *pX = pTerm->pExpr;
93846         CollSeq *pColl;
93847         char idxaff;
93848         int j;
93849         Parse *pParse = pWC->pParse;
93850
93851         idxaff = pIdx->pTable->aCol[iColumn].affinity;
93852         if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
93853
93854         /* Figure out the collation sequence required from an index for
93855         ** it to be useful for optimising expression pX. Store this
93856         ** value in variable pColl.
93857         */
93858         assert(pX->pLeft);
93859         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
93860         assert(pColl || pParse->nErr);
93861
93862         for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
93863           if( NEVER(j>=pIdx->nColumn) ) return 0;
93864         }
93865         if( pColl && sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
93866       }
93867       return pTerm;
93868     }
93869   }
93870   return 0;
93871 }
93872
93873 /* Forward reference */
93874 static void exprAnalyze(SrcList*, WhereClause*, int);
93875
93876 /*
93877 ** Call exprAnalyze on all terms in a WHERE clause.  
93878 **
93879 **
93880 */
93881 static void exprAnalyzeAll(
93882   SrcList *pTabList,       /* the FROM clause */
93883   WhereClause *pWC         /* the WHERE clause to be analyzed */
93884 ){
93885   int i;
93886   for(i=pWC->nTerm-1; i>=0; i--){
93887     exprAnalyze(pTabList, pWC, i);
93888   }
93889 }
93890
93891 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
93892 /*
93893 ** Check to see if the given expression is a LIKE or GLOB operator that
93894 ** can be optimized using inequality constraints.  Return TRUE if it is
93895 ** so and false if not.
93896 **
93897 ** In order for the operator to be optimizible, the RHS must be a string
93898 ** literal that does not begin with a wildcard.  
93899 */
93900 static int isLikeOrGlob(
93901   Parse *pParse,    /* Parsing and code generating context */
93902   Expr *pExpr,      /* Test this expression */
93903   Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
93904   int *pisComplete, /* True if the only wildcard is % in the last character */
93905   int *pnoCase      /* True if uppercase is equivalent to lowercase */
93906 ){
93907   const char *z = 0;         /* String on RHS of LIKE operator */
93908   Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
93909   ExprList *pList;           /* List of operands to the LIKE operator */
93910   int c;                     /* One character in z[] */
93911   int cnt;                   /* Number of non-wildcard prefix characters */
93912   char wc[3];                /* Wildcard characters */
93913   CollSeq *pColl;            /* Collating sequence for LHS */
93914   sqlite3 *db = pParse->db;  /* Database connection */
93915   sqlite3_value *pVal = 0;
93916   int op;                    /* Opcode of pRight */
93917
93918   if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
93919     return 0;
93920   }
93921 #ifdef SQLITE_EBCDIC
93922   if( *pnoCase ) return 0;
93923 #endif
93924   pList = pExpr->x.pList;
93925   pLeft = pList->a[1].pExpr;
93926   if( pLeft->op!=TK_COLUMN || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT ){
93927     /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
93928     ** be the name of an indexed column with TEXT affinity. */
93929     return 0;
93930   }
93931   assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
93932   pColl = sqlite3ExprCollSeq(pParse, pLeft);
93933   if( pColl==0 ) return 0;  /* Happens when LHS has an undefined collation */
93934   if( (pColl->type!=SQLITE_COLL_BINARY || *pnoCase) &&
93935       (pColl->type!=SQLITE_COLL_NOCASE || !*pnoCase) ){
93936     /* IMP: R-09003-32046 For the GLOB operator, the column must use the
93937     ** default BINARY collating sequence.
93938     ** IMP: R-41408-28306 For the LIKE operator, if case_sensitive_like mode
93939     ** is enabled then the column must use the default BINARY collating
93940     ** sequence, or if case_sensitive_like mode is disabled then the column
93941     ** must use the built-in NOCASE collating sequence.
93942     */
93943     return 0;
93944   }
93945
93946   pRight = pList->a[0].pExpr;
93947   op = pRight->op;
93948   if( op==TK_REGISTER ){
93949     op = pRight->op2;
93950   }
93951   if( op==TK_VARIABLE ){
93952     Vdbe *pReprepare = pParse->pReprepare;
93953     pVal = sqlite3VdbeGetValue(pReprepare, pRight->iColumn, SQLITE_AFF_NONE);
93954     if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
93955       z = (char *)sqlite3_value_text(pVal);
93956     }
93957     sqlite3VdbeSetVarmask(pParse->pVdbe, pRight->iColumn);
93958     assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
93959   }else if( op==TK_STRING ){
93960     z = pRight->u.zToken;
93961   }
93962   if( z ){
93963     cnt = 0;
93964     while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
93965       cnt++;
93966     }
93967     if( cnt!=0 && c!=0 && 255!=(u8)z[cnt-1] ){
93968       Expr *pPrefix;
93969       *pisComplete = z[cnt]==wc[0] && z[cnt+1]==0;
93970       pPrefix = sqlite3Expr(db, TK_STRING, z);
93971       if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
93972       *ppPrefix = pPrefix;
93973       if( op==TK_VARIABLE ){
93974         Vdbe *v = pParse->pVdbe;
93975         sqlite3VdbeSetVarmask(v, pRight->iColumn);
93976         if( *pisComplete && pRight->u.zToken[1] ){
93977           /* If the rhs of the LIKE expression is a variable, and the current
93978           ** value of the variable means there is no need to invoke the LIKE
93979           ** function, then no OP_Variable will be added to the program.
93980           ** This causes problems for the sqlite3_bind_parameter_name()
93981           ** API. To workaround them, add a dummy OP_Variable here.
93982           */ 
93983           int r1 = sqlite3GetTempReg(pParse);
93984           sqlite3ExprCodeTarget(pParse, pRight, r1);
93985           sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
93986           sqlite3ReleaseTempReg(pParse, r1);
93987         }
93988       }
93989     }else{
93990       z = 0;
93991     }
93992   }
93993
93994   sqlite3ValueFree(pVal);
93995   return (z!=0);
93996 }
93997 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
93998
93999
94000 #ifndef SQLITE_OMIT_VIRTUALTABLE
94001 /*
94002 ** Check to see if the given expression is of the form
94003 **
94004 **         column MATCH expr
94005 **
94006 ** If it is then return TRUE.  If not, return FALSE.
94007 */
94008 static int isMatchOfColumn(
94009   Expr *pExpr      /* Test this expression */
94010 ){
94011   ExprList *pList;
94012
94013   if( pExpr->op!=TK_FUNCTION ){
94014     return 0;
94015   }
94016   if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
94017     return 0;
94018   }
94019   pList = pExpr->x.pList;
94020   if( pList->nExpr!=2 ){
94021     return 0;
94022   }
94023   if( pList->a[1].pExpr->op != TK_COLUMN ){
94024     return 0;
94025   }
94026   return 1;
94027 }
94028 #endif /* SQLITE_OMIT_VIRTUALTABLE */
94029
94030 /*
94031 ** If the pBase expression originated in the ON or USING clause of
94032 ** a join, then transfer the appropriate markings over to derived.
94033 */
94034 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
94035   pDerived->flags |= pBase->flags & EP_FromJoin;
94036   pDerived->iRightJoinTable = pBase->iRightJoinTable;
94037 }
94038
94039 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
94040 /*
94041 ** Analyze a term that consists of two or more OR-connected
94042 ** subterms.  So in:
94043 **
94044 **     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
94045 **                          ^^^^^^^^^^^^^^^^^^^^
94046 **
94047 ** This routine analyzes terms such as the middle term in the above example.
94048 ** A WhereOrTerm object is computed and attached to the term under
94049 ** analysis, regardless of the outcome of the analysis.  Hence:
94050 **
94051 **     WhereTerm.wtFlags   |=  TERM_ORINFO
94052 **     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
94053 **
94054 ** The term being analyzed must have two or more of OR-connected subterms.
94055 ** A single subterm might be a set of AND-connected sub-subterms.
94056 ** Examples of terms under analysis:
94057 **
94058 **     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
94059 **     (B)     x=expr1 OR expr2=x OR x=expr3
94060 **     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
94061 **     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
94062 **     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
94063 **
94064 ** CASE 1:
94065 **
94066 ** If all subterms are of the form T.C=expr for some single column of C
94067 ** a single table T (as shown in example B above) then create a new virtual
94068 ** term that is an equivalent IN expression.  In other words, if the term
94069 ** being analyzed is:
94070 **
94071 **      x = expr1  OR  expr2 = x  OR  x = expr3
94072 **
94073 ** then create a new virtual term like this:
94074 **
94075 **      x IN (expr1,expr2,expr3)
94076 **
94077 ** CASE 2:
94078 **
94079 ** If all subterms are indexable by a single table T, then set
94080 **
94081 **     WhereTerm.eOperator              =  WO_OR
94082 **     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
94083 **
94084 ** A subterm is "indexable" if it is of the form
94085 ** "T.C <op> <expr>" where C is any column of table T and 
94086 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
94087 ** A subterm is also indexable if it is an AND of two or more
94088 ** subsubterms at least one of which is indexable.  Indexable AND 
94089 ** subterms have their eOperator set to WO_AND and they have
94090 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
94091 **
94092 ** From another point of view, "indexable" means that the subterm could
94093 ** potentially be used with an index if an appropriate index exists.
94094 ** This analysis does not consider whether or not the index exists; that
94095 ** is something the bestIndex() routine will determine.  This analysis
94096 ** only looks at whether subterms appropriate for indexing exist.
94097 **
94098 ** All examples A through E above all satisfy case 2.  But if a term
94099 ** also statisfies case 1 (such as B) we know that the optimizer will
94100 ** always prefer case 1, so in that case we pretend that case 2 is not
94101 ** satisfied.
94102 **
94103 ** It might be the case that multiple tables are indexable.  For example,
94104 ** (E) above is indexable on tables P, Q, and R.
94105 **
94106 ** Terms that satisfy case 2 are candidates for lookup by using
94107 ** separate indices to find rowids for each subterm and composing
94108 ** the union of all rowids using a RowSet object.  This is similar
94109 ** to "bitmap indices" in other database engines.
94110 **
94111 ** OTHERWISE:
94112 **
94113 ** If neither case 1 nor case 2 apply, then leave the eOperator set to
94114 ** zero.  This term is not useful for search.
94115 */
94116 static void exprAnalyzeOrTerm(
94117   SrcList *pSrc,            /* the FROM clause */
94118   WhereClause *pWC,         /* the complete WHERE clause */
94119   int idxTerm               /* Index of the OR-term to be analyzed */
94120 ){
94121   Parse *pParse = pWC->pParse;            /* Parser context */
94122   sqlite3 *db = pParse->db;               /* Database connection */
94123   WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
94124   Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
94125   WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
94126   int i;                                  /* Loop counters */
94127   WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
94128   WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
94129   WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
94130   Bitmask chngToIN;         /* Tables that might satisfy case 1 */
94131   Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
94132
94133   /*
94134   ** Break the OR clause into its separate subterms.  The subterms are
94135   ** stored in a WhereClause structure containing within the WhereOrInfo
94136   ** object that is attached to the original OR clause term.
94137   */
94138   assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
94139   assert( pExpr->op==TK_OR );
94140   pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
94141   if( pOrInfo==0 ) return;
94142   pTerm->wtFlags |= TERM_ORINFO;
94143   pOrWc = &pOrInfo->wc;
94144   whereClauseInit(pOrWc, pWC->pParse, pMaskSet);
94145   whereSplit(pOrWc, pExpr, TK_OR);
94146   exprAnalyzeAll(pSrc, pOrWc);
94147   if( db->mallocFailed ) return;
94148   assert( pOrWc->nTerm>=2 );
94149
94150   /*
94151   ** Compute the set of tables that might satisfy cases 1 or 2.
94152   */
94153   indexable = ~(Bitmask)0;
94154   chngToIN = ~(pWC->vmask);
94155   for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
94156     if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
94157       WhereAndInfo *pAndInfo;
94158       assert( pOrTerm->eOperator==0 );
94159       assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
94160       chngToIN = 0;
94161       pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
94162       if( pAndInfo ){
94163         WhereClause *pAndWC;
94164         WhereTerm *pAndTerm;
94165         int j;
94166         Bitmask b = 0;
94167         pOrTerm->u.pAndInfo = pAndInfo;
94168         pOrTerm->wtFlags |= TERM_ANDINFO;
94169         pOrTerm->eOperator = WO_AND;
94170         pAndWC = &pAndInfo->wc;
94171         whereClauseInit(pAndWC, pWC->pParse, pMaskSet);
94172         whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
94173         exprAnalyzeAll(pSrc, pAndWC);
94174         testcase( db->mallocFailed );
94175         if( !db->mallocFailed ){
94176           for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
94177             assert( pAndTerm->pExpr );
94178             if( allowedOp(pAndTerm->pExpr->op) ){
94179               b |= getMask(pMaskSet, pAndTerm->leftCursor);
94180             }
94181           }
94182         }
94183         indexable &= b;
94184       }
94185     }else if( pOrTerm->wtFlags & TERM_COPIED ){
94186       /* Skip this term for now.  We revisit it when we process the
94187       ** corresponding TERM_VIRTUAL term */
94188     }else{
94189       Bitmask b;
94190       b = getMask(pMaskSet, pOrTerm->leftCursor);
94191       if( pOrTerm->wtFlags & TERM_VIRTUAL ){
94192         WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
94193         b |= getMask(pMaskSet, pOther->leftCursor);
94194       }
94195       indexable &= b;
94196       if( pOrTerm->eOperator!=WO_EQ ){
94197         chngToIN = 0;
94198       }else{
94199         chngToIN &= b;
94200       }
94201     }
94202   }
94203
94204   /*
94205   ** Record the set of tables that satisfy case 2.  The set might be
94206   ** empty.
94207   */
94208   pOrInfo->indexable = indexable;
94209   pTerm->eOperator = indexable==0 ? 0 : WO_OR;
94210
94211   /*
94212   ** chngToIN holds a set of tables that *might* satisfy case 1.  But
94213   ** we have to do some additional checking to see if case 1 really
94214   ** is satisfied.
94215   **
94216   ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
94217   ** that there is no possibility of transforming the OR clause into an
94218   ** IN operator because one or more terms in the OR clause contain
94219   ** something other than == on a column in the single table.  The 1-bit
94220   ** case means that every term of the OR clause is of the form
94221   ** "table.column=expr" for some single table.  The one bit that is set
94222   ** will correspond to the common table.  We still need to check to make
94223   ** sure the same column is used on all terms.  The 2-bit case is when
94224   ** the all terms are of the form "table1.column=table2.column".  It
94225   ** might be possible to form an IN operator with either table1.column
94226   ** or table2.column as the LHS if either is common to every term of
94227   ** the OR clause.
94228   **
94229   ** Note that terms of the form "table.column1=table.column2" (the
94230   ** same table on both sizes of the ==) cannot be optimized.
94231   */
94232   if( chngToIN ){
94233     int okToChngToIN = 0;     /* True if the conversion to IN is valid */
94234     int iColumn = -1;         /* Column index on lhs of IN operator */
94235     int iCursor = -1;         /* Table cursor common to all terms */
94236     int j = 0;                /* Loop counter */
94237
94238     /* Search for a table and column that appears on one side or the
94239     ** other of the == operator in every subterm.  That table and column
94240     ** will be recorded in iCursor and iColumn.  There might not be any
94241     ** such table and column.  Set okToChngToIN if an appropriate table
94242     ** and column is found but leave okToChngToIN false if not found.
94243     */
94244     for(j=0; j<2 && !okToChngToIN; j++){
94245       pOrTerm = pOrWc->a;
94246       for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
94247         assert( pOrTerm->eOperator==WO_EQ );
94248         pOrTerm->wtFlags &= ~TERM_OR_OK;
94249         if( pOrTerm->leftCursor==iCursor ){
94250           /* This is the 2-bit case and we are on the second iteration and
94251           ** current term is from the first iteration.  So skip this term. */
94252           assert( j==1 );
94253           continue;
94254         }
94255         if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ){
94256           /* This term must be of the form t1.a==t2.b where t2 is in the
94257           ** chngToIN set but t1 is not.  This term will be either preceeded
94258           ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term 
94259           ** and use its inversion. */
94260           testcase( pOrTerm->wtFlags & TERM_COPIED );
94261           testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
94262           assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
94263           continue;
94264         }
94265         iColumn = pOrTerm->u.leftColumn;
94266         iCursor = pOrTerm->leftCursor;
94267         break;
94268       }
94269       if( i<0 ){
94270         /* No candidate table+column was found.  This can only occur
94271         ** on the second iteration */
94272         assert( j==1 );
94273         assert( (chngToIN&(chngToIN-1))==0 );
94274         assert( chngToIN==getMask(pMaskSet, iCursor) );
94275         break;
94276       }
94277       testcase( j==1 );
94278
94279       /* We have found a candidate table and column.  Check to see if that
94280       ** table and column is common to every term in the OR clause */
94281       okToChngToIN = 1;
94282       for(; i>=0 && okToChngToIN; i--, pOrTerm++){
94283         assert( pOrTerm->eOperator==WO_EQ );
94284         if( pOrTerm->leftCursor!=iCursor ){
94285           pOrTerm->wtFlags &= ~TERM_OR_OK;
94286         }else if( pOrTerm->u.leftColumn!=iColumn ){
94287           okToChngToIN = 0;
94288         }else{
94289           int affLeft, affRight;
94290           /* If the right-hand side is also a column, then the affinities
94291           ** of both right and left sides must be such that no type
94292           ** conversions are required on the right.  (Ticket #2249)
94293           */
94294           affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
94295           affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
94296           if( affRight!=0 && affRight!=affLeft ){
94297             okToChngToIN = 0;
94298           }else{
94299             pOrTerm->wtFlags |= TERM_OR_OK;
94300           }
94301         }
94302       }
94303     }
94304
94305     /* At this point, okToChngToIN is true if original pTerm satisfies
94306     ** case 1.  In that case, construct a new virtual term that is 
94307     ** pTerm converted into an IN operator.
94308     */
94309     if( okToChngToIN ){
94310       Expr *pDup;            /* A transient duplicate expression */
94311       ExprList *pList = 0;   /* The RHS of the IN operator */
94312       Expr *pLeft = 0;       /* The LHS of the IN operator */
94313       Expr *pNew;            /* The complete IN operator */
94314
94315       for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
94316         if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
94317         assert( pOrTerm->eOperator==WO_EQ );
94318         assert( pOrTerm->leftCursor==iCursor );
94319         assert( pOrTerm->u.leftColumn==iColumn );
94320         pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
94321         pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup);
94322         pLeft = pOrTerm->pExpr->pLeft;
94323       }
94324       assert( pLeft!=0 );
94325       pDup = sqlite3ExprDup(db, pLeft, 0);
94326       pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
94327       if( pNew ){
94328         int idxNew;
94329         transferJoinMarkings(pNew, pExpr);
94330         assert( !ExprHasProperty(pNew, EP_xIsSelect) );
94331         pNew->x.pList = pList;
94332         idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
94333         testcase( idxNew==0 );
94334         exprAnalyze(pSrc, pWC, idxNew);
94335         pTerm = &pWC->a[idxTerm];
94336         pWC->a[idxNew].iParent = idxTerm;
94337         pTerm->nChild = 1;
94338       }else{
94339         sqlite3ExprListDelete(db, pList);
94340       }
94341       pTerm->eOperator = 0;  /* case 1 trumps case 2 */
94342     }
94343   }
94344 }
94345 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
94346
94347
94348 /*
94349 ** The input to this routine is an WhereTerm structure with only the
94350 ** "pExpr" field filled in.  The job of this routine is to analyze the
94351 ** subexpression and populate all the other fields of the WhereTerm
94352 ** structure.
94353 **
94354 ** If the expression is of the form "<expr> <op> X" it gets commuted
94355 ** to the standard form of "X <op> <expr>".
94356 **
94357 ** If the expression is of the form "X <op> Y" where both X and Y are
94358 ** columns, then the original expression is unchanged and a new virtual
94359 ** term of the form "Y <op> X" is added to the WHERE clause and
94360 ** analyzed separately.  The original term is marked with TERM_COPIED
94361 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
94362 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
94363 ** is a commuted copy of a prior term.)  The original term has nChild=1
94364 ** and the copy has idxParent set to the index of the original term.
94365 */
94366 static void exprAnalyze(
94367   SrcList *pSrc,            /* the FROM clause */
94368   WhereClause *pWC,         /* the WHERE clause */
94369   int idxTerm               /* Index of the term to be analyzed */
94370 ){
94371   WhereTerm *pTerm;                /* The term to be analyzed */
94372   WhereMaskSet *pMaskSet;          /* Set of table index masks */
94373   Expr *pExpr;                     /* The expression to be analyzed */
94374   Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
94375   Bitmask prereqAll;               /* Prerequesites of pExpr */
94376   Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */
94377   Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
94378   int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
94379   int noCase = 0;                  /* LIKE/GLOB distinguishes case */
94380   int op;                          /* Top-level operator.  pExpr->op */
94381   Parse *pParse = pWC->pParse;     /* Parsing context */
94382   sqlite3 *db = pParse->db;        /* Database connection */
94383
94384   if( db->mallocFailed ){
94385     return;
94386   }
94387   pTerm = &pWC->a[idxTerm];
94388   pMaskSet = pWC->pMaskSet;
94389   pExpr = pTerm->pExpr;
94390   prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
94391   op = pExpr->op;
94392   if( op==TK_IN ){
94393     assert( pExpr->pRight==0 );
94394     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
94395       pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
94396     }else{
94397       pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
94398     }
94399   }else if( op==TK_ISNULL ){
94400     pTerm->prereqRight = 0;
94401   }else{
94402     pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
94403   }
94404   prereqAll = exprTableUsage(pMaskSet, pExpr);
94405   if( ExprHasProperty(pExpr, EP_FromJoin) ){
94406     Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
94407     prereqAll |= x;
94408     extraRight = x-1;  /* ON clause terms may not be used with an index
94409                        ** on left table of a LEFT JOIN.  Ticket #3015 */
94410   }
94411   pTerm->prereqAll = prereqAll;
94412   pTerm->leftCursor = -1;
94413   pTerm->iParent = -1;
94414   pTerm->eOperator = 0;
94415   if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
94416     Expr *pLeft = pExpr->pLeft;
94417     Expr *pRight = pExpr->pRight;
94418     if( pLeft->op==TK_COLUMN ){
94419       pTerm->leftCursor = pLeft->iTable;
94420       pTerm->u.leftColumn = pLeft->iColumn;
94421       pTerm->eOperator = operatorMask(op);
94422     }
94423     if( pRight && pRight->op==TK_COLUMN ){
94424       WhereTerm *pNew;
94425       Expr *pDup;
94426       if( pTerm->leftCursor>=0 ){
94427         int idxNew;
94428         pDup = sqlite3ExprDup(db, pExpr, 0);
94429         if( db->mallocFailed ){
94430           sqlite3ExprDelete(db, pDup);
94431           return;
94432         }
94433         idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
94434         if( idxNew==0 ) return;
94435         pNew = &pWC->a[idxNew];
94436         pNew->iParent = idxTerm;
94437         pTerm = &pWC->a[idxTerm];
94438         pTerm->nChild = 1;
94439         pTerm->wtFlags |= TERM_COPIED;
94440       }else{
94441         pDup = pExpr;
94442         pNew = pTerm;
94443       }
94444       exprCommute(pParse, pDup);
94445       pLeft = pDup->pLeft;
94446       pNew->leftCursor = pLeft->iTable;
94447       pNew->u.leftColumn = pLeft->iColumn;
94448       testcase( (prereqLeft | extraRight) != prereqLeft );
94449       pNew->prereqRight = prereqLeft | extraRight;
94450       pNew->prereqAll = prereqAll;
94451       pNew->eOperator = operatorMask(pDup->op);
94452     }
94453   }
94454
94455 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
94456   /* If a term is the BETWEEN operator, create two new virtual terms
94457   ** that define the range that the BETWEEN implements.  For example:
94458   **
94459   **      a BETWEEN b AND c
94460   **
94461   ** is converted into:
94462   **
94463   **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
94464   **
94465   ** The two new terms are added onto the end of the WhereClause object.
94466   ** The new terms are "dynamic" and are children of the original BETWEEN
94467   ** term.  That means that if the BETWEEN term is coded, the children are
94468   ** skipped.  Or, if the children are satisfied by an index, the original
94469   ** BETWEEN term is skipped.
94470   */
94471   else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
94472     ExprList *pList = pExpr->x.pList;
94473     int i;
94474     static const u8 ops[] = {TK_GE, TK_LE};
94475     assert( pList!=0 );
94476     assert( pList->nExpr==2 );
94477     for(i=0; i<2; i++){
94478       Expr *pNewExpr;
94479       int idxNew;
94480       pNewExpr = sqlite3PExpr(pParse, ops[i], 
94481                              sqlite3ExprDup(db, pExpr->pLeft, 0),
94482                              sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
94483       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
94484       testcase( idxNew==0 );
94485       exprAnalyze(pSrc, pWC, idxNew);
94486       pTerm = &pWC->a[idxTerm];
94487       pWC->a[idxNew].iParent = idxTerm;
94488     }
94489     pTerm->nChild = 2;
94490   }
94491 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
94492
94493 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
94494   /* Analyze a term that is composed of two or more subterms connected by
94495   ** an OR operator.
94496   */
94497   else if( pExpr->op==TK_OR ){
94498     assert( pWC->op==TK_AND );
94499     exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
94500     pTerm = &pWC->a[idxTerm];
94501   }
94502 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
94503
94504 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
94505   /* Add constraints to reduce the search space on a LIKE or GLOB
94506   ** operator.
94507   **
94508   ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
94509   **
94510   **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
94511   **
94512   ** The last character of the prefix "abc" is incremented to form the
94513   ** termination condition "abd".
94514   */
94515   if( pWC->op==TK_AND 
94516    && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
94517   ){
94518     Expr *pLeft;       /* LHS of LIKE/GLOB operator */
94519     Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
94520     Expr *pNewExpr1;
94521     Expr *pNewExpr2;
94522     int idxNew1;
94523     int idxNew2;
94524
94525     pLeft = pExpr->x.pList->a[1].pExpr;
94526     pStr2 = sqlite3ExprDup(db, pStr1, 0);
94527     if( !db->mallocFailed ){
94528       u8 c, *pC;       /* Last character before the first wildcard */
94529       pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
94530       c = *pC;
94531       if( noCase ){
94532         /* The point is to increment the last character before the first
94533         ** wildcard.  But if we increment '@', that will push it into the
94534         ** alphabetic range where case conversions will mess up the 
94535         ** inequality.  To avoid this, make sure to also run the full
94536         ** LIKE on all candidate expressions by clearing the isComplete flag
94537         */
94538         if( c=='A'-1 ) isComplete = 0;
94539
94540         c = sqlite3UpperToLower[c];
94541       }
94542       *pC = c + 1;
94543     }
94544     pNewExpr1 = sqlite3PExpr(pParse, TK_GE, sqlite3ExprDup(db,pLeft,0),pStr1,0);
94545     idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
94546     testcase( idxNew1==0 );
94547     exprAnalyze(pSrc, pWC, idxNew1);
94548     pNewExpr2 = sqlite3PExpr(pParse, TK_LT, sqlite3ExprDup(db,pLeft,0),pStr2,0);
94549     idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
94550     testcase( idxNew2==0 );
94551     exprAnalyze(pSrc, pWC, idxNew2);
94552     pTerm = &pWC->a[idxTerm];
94553     if( isComplete ){
94554       pWC->a[idxNew1].iParent = idxTerm;
94555       pWC->a[idxNew2].iParent = idxTerm;
94556       pTerm->nChild = 2;
94557     }
94558   }
94559 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
94560
94561 #ifndef SQLITE_OMIT_VIRTUALTABLE
94562   /* Add a WO_MATCH auxiliary term to the constraint set if the
94563   ** current expression is of the form:  column MATCH expr.
94564   ** This information is used by the xBestIndex methods of
94565   ** virtual tables.  The native query optimizer does not attempt
94566   ** to do anything with MATCH functions.
94567   */
94568   if( isMatchOfColumn(pExpr) ){
94569     int idxNew;
94570     Expr *pRight, *pLeft;
94571     WhereTerm *pNewTerm;
94572     Bitmask prereqColumn, prereqExpr;
94573
94574     pRight = pExpr->x.pList->a[0].pExpr;
94575     pLeft = pExpr->x.pList->a[1].pExpr;
94576     prereqExpr = exprTableUsage(pMaskSet, pRight);
94577     prereqColumn = exprTableUsage(pMaskSet, pLeft);
94578     if( (prereqExpr & prereqColumn)==0 ){
94579       Expr *pNewExpr;
94580       pNewExpr = sqlite3PExpr(pParse, TK_MATCH, 
94581                               0, sqlite3ExprDup(db, pRight, 0), 0);
94582       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
94583       testcase( idxNew==0 );
94584       pNewTerm = &pWC->a[idxNew];
94585       pNewTerm->prereqRight = prereqExpr;
94586       pNewTerm->leftCursor = pLeft->iTable;
94587       pNewTerm->u.leftColumn = pLeft->iColumn;
94588       pNewTerm->eOperator = WO_MATCH;
94589       pNewTerm->iParent = idxTerm;
94590       pTerm = &pWC->a[idxTerm];
94591       pTerm->nChild = 1;
94592       pTerm->wtFlags |= TERM_COPIED;
94593       pNewTerm->prereqAll = pTerm->prereqAll;
94594     }
94595   }
94596 #endif /* SQLITE_OMIT_VIRTUALTABLE */
94597
94598   /* Prevent ON clause terms of a LEFT JOIN from being used to drive
94599   ** an index for tables to the left of the join.
94600   */
94601   pTerm->prereqRight |= extraRight;
94602 }
94603
94604 /*
94605 ** Return TRUE if any of the expressions in pList->a[iFirst...] contain
94606 ** a reference to any table other than the iBase table.
94607 */
94608 static int referencesOtherTables(
94609   ExprList *pList,          /* Search expressions in ths list */
94610   WhereMaskSet *pMaskSet,   /* Mapping from tables to bitmaps */
94611   int iFirst,               /* Be searching with the iFirst-th expression */
94612   int iBase                 /* Ignore references to this table */
94613 ){
94614   Bitmask allowed = ~getMask(pMaskSet, iBase);
94615   while( iFirst<pList->nExpr ){
94616     if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
94617       return 1;
94618     }
94619   }
94620   return 0;
94621 }
94622
94623
94624 /*
94625 ** This routine decides if pIdx can be used to satisfy the ORDER BY
94626 ** clause.  If it can, it returns 1.  If pIdx cannot satisfy the
94627 ** ORDER BY clause, this routine returns 0.
94628 **
94629 ** pOrderBy is an ORDER BY clause from a SELECT statement.  pTab is the
94630 ** left-most table in the FROM clause of that same SELECT statement and
94631 ** the table has a cursor number of "base".  pIdx is an index on pTab.
94632 **
94633 ** nEqCol is the number of columns of pIdx that are used as equality
94634 ** constraints.  Any of these columns may be missing from the ORDER BY
94635 ** clause and the match can still be a success.
94636 **
94637 ** All terms of the ORDER BY that match against the index must be either
94638 ** ASC or DESC.  (Terms of the ORDER BY clause past the end of a UNIQUE
94639 ** index do not need to satisfy this constraint.)  The *pbRev value is
94640 ** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
94641 ** the ORDER BY clause is all ASC.
94642 */
94643 static int isSortingIndex(
94644   Parse *pParse,          /* Parsing context */
94645   WhereMaskSet *pMaskSet, /* Mapping from table cursor numbers to bitmaps */
94646   Index *pIdx,            /* The index we are testing */
94647   int base,               /* Cursor number for the table to be sorted */
94648   ExprList *pOrderBy,     /* The ORDER BY clause */
94649   int nEqCol,             /* Number of index columns with == constraints */
94650   int *pbRev              /* Set to 1 if ORDER BY is DESC */
94651 ){
94652   int i, j;                       /* Loop counters */
94653   int sortOrder = 0;              /* XOR of index and ORDER BY sort direction */
94654   int nTerm;                      /* Number of ORDER BY terms */
94655   struct ExprList_item *pTerm;    /* A term of the ORDER BY clause */
94656   sqlite3 *db = pParse->db;
94657
94658   assert( pOrderBy!=0 );
94659   nTerm = pOrderBy->nExpr;
94660   assert( nTerm>0 );
94661
94662   /* Argument pIdx must either point to a 'real' named index structure, 
94663   ** or an index structure allocated on the stack by bestBtreeIndex() to
94664   ** represent the rowid index that is part of every table.  */
94665   assert( pIdx->zName || (pIdx->nColumn==1 && pIdx->aiColumn[0]==-1) );
94666
94667   /* Match terms of the ORDER BY clause against columns of
94668   ** the index.
94669   **
94670   ** Note that indices have pIdx->nColumn regular columns plus
94671   ** one additional column containing the rowid.  The rowid column
94672   ** of the index is also allowed to match against the ORDER BY
94673   ** clause.
94674   */
94675   for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
94676     Expr *pExpr;       /* The expression of the ORDER BY pTerm */
94677     CollSeq *pColl;    /* The collating sequence of pExpr */
94678     int termSortOrder; /* Sort order for this term */
94679     int iColumn;       /* The i-th column of the index.  -1 for rowid */
94680     int iSortOrder;    /* 1 for DESC, 0 for ASC on the i-th index term */
94681     const char *zColl; /* Name of the collating sequence for i-th index term */
94682
94683     pExpr = pTerm->pExpr;
94684     if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
94685       /* Can not use an index sort on anything that is not a column in the
94686       ** left-most table of the FROM clause */
94687       break;
94688     }
94689     pColl = sqlite3ExprCollSeq(pParse, pExpr);
94690     if( !pColl ){
94691       pColl = db->pDfltColl;
94692     }
94693     if( pIdx->zName && i<pIdx->nColumn ){
94694       iColumn = pIdx->aiColumn[i];
94695       if( iColumn==pIdx->pTable->iPKey ){
94696         iColumn = -1;
94697       }
94698       iSortOrder = pIdx->aSortOrder[i];
94699       zColl = pIdx->azColl[i];
94700     }else{
94701       iColumn = -1;
94702       iSortOrder = 0;
94703       zColl = pColl->zName;
94704     }
94705     if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){
94706       /* Term j of the ORDER BY clause does not match column i of the index */
94707       if( i<nEqCol ){
94708         /* If an index column that is constrained by == fails to match an
94709         ** ORDER BY term, that is OK.  Just ignore that column of the index
94710         */
94711         continue;
94712       }else if( i==pIdx->nColumn ){
94713         /* Index column i is the rowid.  All other terms match. */
94714         break;
94715       }else{
94716         /* If an index column fails to match and is not constrained by ==
94717         ** then the index cannot satisfy the ORDER BY constraint.
94718         */
94719         return 0;
94720       }
94721     }
94722     assert( pIdx->aSortOrder!=0 || iColumn==-1 );
94723     assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
94724     assert( iSortOrder==0 || iSortOrder==1 );
94725     termSortOrder = iSortOrder ^ pTerm->sortOrder;
94726     if( i>nEqCol ){
94727       if( termSortOrder!=sortOrder ){
94728         /* Indices can only be used if all ORDER BY terms past the
94729         ** equality constraints are all either DESC or ASC. */
94730         return 0;
94731       }
94732     }else{
94733       sortOrder = termSortOrder;
94734     }
94735     j++;
94736     pTerm++;
94737     if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
94738       /* If the indexed column is the primary key and everything matches
94739       ** so far and none of the ORDER BY terms to the right reference other
94740       ** tables in the join, then we are assured that the index can be used 
94741       ** to sort because the primary key is unique and so none of the other
94742       ** columns will make any difference
94743       */
94744       j = nTerm;
94745     }
94746   }
94747
94748   *pbRev = sortOrder!=0;
94749   if( j>=nTerm ){
94750     /* All terms of the ORDER BY clause are covered by this index so
94751     ** this index can be used for sorting. */
94752     return 1;
94753   }
94754   if( pIdx->onError!=OE_None && i==pIdx->nColumn
94755       && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
94756     /* All terms of this index match some prefix of the ORDER BY clause
94757     ** and the index is UNIQUE and no terms on the tail of the ORDER BY
94758     ** clause reference other tables in a join.  If this is all true then
94759     ** the order by clause is superfluous. */
94760     return 1;
94761   }
94762   return 0;
94763 }
94764
94765 /*
94766 ** Prepare a crude estimate of the logarithm of the input value.
94767 ** The results need not be exact.  This is only used for estimating
94768 ** the total cost of performing operations with O(logN) or O(NlogN)
94769 ** complexity.  Because N is just a guess, it is no great tragedy if
94770 ** logN is a little off.
94771 */
94772 static double estLog(double N){
94773   double logN = 1;
94774   double x = 10;
94775   while( N>x ){
94776     logN += 1;
94777     x *= 10;
94778   }
94779   return logN;
94780 }
94781
94782 /*
94783 ** Two routines for printing the content of an sqlite3_index_info
94784 ** structure.  Used for testing and debugging only.  If neither
94785 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
94786 ** are no-ops.
94787 */
94788 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
94789 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
94790   int i;
94791   if( !sqlite3WhereTrace ) return;
94792   for(i=0; i<p->nConstraint; i++){
94793     sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
94794        i,
94795        p->aConstraint[i].iColumn,
94796        p->aConstraint[i].iTermOffset,
94797        p->aConstraint[i].op,
94798        p->aConstraint[i].usable);
94799   }
94800   for(i=0; i<p->nOrderBy; i++){
94801     sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
94802        i,
94803        p->aOrderBy[i].iColumn,
94804        p->aOrderBy[i].desc);
94805   }
94806 }
94807 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
94808   int i;
94809   if( !sqlite3WhereTrace ) return;
94810   for(i=0; i<p->nConstraint; i++){
94811     sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
94812        i,
94813        p->aConstraintUsage[i].argvIndex,
94814        p->aConstraintUsage[i].omit);
94815   }
94816   sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
94817   sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
94818   sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
94819   sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
94820 }
94821 #else
94822 #define TRACE_IDX_INPUTS(A)
94823 #define TRACE_IDX_OUTPUTS(A)
94824 #endif
94825
94826 /* 
94827 ** Required because bestIndex() is called by bestOrClauseIndex() 
94828 */
94829 static void bestIndex(
94830     Parse*, WhereClause*, struct SrcList_item*, Bitmask, ExprList*, WhereCost*);
94831
94832 /*
94833 ** This routine attempts to find an scanning strategy that can be used 
94834 ** to optimize an 'OR' expression that is part of a WHERE clause. 
94835 **
94836 ** The table associated with FROM clause term pSrc may be either a
94837 ** regular B-Tree table or a virtual table.
94838 */
94839 static void bestOrClauseIndex(
94840   Parse *pParse,              /* The parsing context */
94841   WhereClause *pWC,           /* The WHERE clause */
94842   struct SrcList_item *pSrc,  /* The FROM clause term to search */
94843   Bitmask notReady,           /* Mask of cursors that are not available */
94844   ExprList *pOrderBy,         /* The ORDER BY clause */
94845   WhereCost *pCost            /* Lowest cost query plan */
94846 ){
94847 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
94848   const int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
94849   const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur);  /* Bitmask for pSrc */
94850   WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm];        /* End of pWC->a[] */
94851   WhereTerm *pTerm;                 /* A single term of the WHERE clause */
94852
94853   /* No OR-clause optimization allowed if the NOT INDEXED clause is used */
94854   if( pSrc->notIndexed ){
94855     return;
94856   }
94857
94858   /* Search the WHERE clause terms for a usable WO_OR term. */
94859   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
94860     if( pTerm->eOperator==WO_OR 
94861      && ((pTerm->prereqAll & ~maskSrc) & notReady)==0
94862      && (pTerm->u.pOrInfo->indexable & maskSrc)!=0 
94863     ){
94864       WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
94865       WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
94866       WhereTerm *pOrTerm;
94867       int flags = WHERE_MULTI_OR;
94868       double rTotal = 0;
94869       double nRow = 0;
94870       Bitmask used = 0;
94871
94872       for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
94873         WhereCost sTermCost;
94874         WHERETRACE(("... Multi-index OR testing for term %d of %d....\n", 
94875           (pOrTerm - pOrWC->a), (pTerm - pWC->a)
94876         ));
94877         if( pOrTerm->eOperator==WO_AND ){
94878           WhereClause *pAndWC = &pOrTerm->u.pAndInfo->wc;
94879           bestIndex(pParse, pAndWC, pSrc, notReady, 0, &sTermCost);
94880         }else if( pOrTerm->leftCursor==iCur ){
94881           WhereClause tempWC;
94882           tempWC.pParse = pWC->pParse;
94883           tempWC.pMaskSet = pWC->pMaskSet;
94884           tempWC.op = TK_AND;
94885           tempWC.a = pOrTerm;
94886           tempWC.nTerm = 1;
94887           bestIndex(pParse, &tempWC, pSrc, notReady, 0, &sTermCost);
94888         }else{
94889           continue;
94890         }
94891         rTotal += sTermCost.rCost;
94892         nRow += sTermCost.nRow;
94893         used |= sTermCost.used;
94894         if( rTotal>=pCost->rCost ) break;
94895       }
94896
94897       /* If there is an ORDER BY clause, increase the scan cost to account 
94898       ** for the cost of the sort. */
94899       if( pOrderBy!=0 ){
94900         WHERETRACE(("... sorting increases OR cost %.9g to %.9g\n",
94901                     rTotal, rTotal+nRow*estLog(nRow)));
94902         rTotal += nRow*estLog(nRow);
94903       }
94904
94905       /* If the cost of scanning using this OR term for optimization is
94906       ** less than the current cost stored in pCost, replace the contents
94907       ** of pCost. */
94908       WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow));
94909       if( rTotal<pCost->rCost ){
94910         pCost->rCost = rTotal;
94911         pCost->nRow = nRow;
94912         pCost->used = used;
94913         pCost->plan.wsFlags = flags;
94914         pCost->plan.u.pTerm = pTerm;
94915       }
94916     }
94917   }
94918 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
94919 }
94920
94921 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
94922 /*
94923 ** Return TRUE if the WHERE clause term pTerm is of a form where it
94924 ** could be used with an index to access pSrc, assuming an appropriate
94925 ** index existed.
94926 */
94927 static int termCanDriveIndex(
94928   WhereTerm *pTerm,              /* WHERE clause term to check */
94929   struct SrcList_item *pSrc,     /* Table we are trying to access */
94930   Bitmask notReady               /* Tables in outer loops of the join */
94931 ){
94932   char aff;
94933   if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
94934   if( pTerm->eOperator!=WO_EQ ) return 0;
94935   if( (pTerm->prereqRight & notReady)!=0 ) return 0;
94936   aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
94937   if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
94938   return 1;
94939 }
94940 #endif
94941
94942 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
94943 /*
94944 ** If the query plan for pSrc specified in pCost is a full table scan
94945 ** and indexing is allows (if there is no NOT INDEXED clause) and it
94946 ** possible to construct a transient index that would perform better
94947 ** than a full table scan even when the cost of constructing the index
94948 ** is taken into account, then alter the query plan to use the
94949 ** transient index.
94950 */
94951 static void bestAutomaticIndex(
94952   Parse *pParse,              /* The parsing context */
94953   WhereClause *pWC,           /* The WHERE clause */
94954   struct SrcList_item *pSrc,  /* The FROM clause term to search */
94955   Bitmask notReady,           /* Mask of cursors that are not available */
94956   WhereCost *pCost            /* Lowest cost query plan */
94957 ){
94958   double nTableRow;           /* Rows in the input table */
94959   double logN;                /* log(nTableRow) */
94960   double costTempIdx;         /* per-query cost of the transient index */
94961   WhereTerm *pTerm;           /* A single term of the WHERE clause */
94962   WhereTerm *pWCEnd;          /* End of pWC->a[] */
94963   Table *pTable;              /* Table tht might be indexed */
94964
94965   if( (pParse->db->flags & SQLITE_AutoIndex)==0 ){
94966     /* Automatic indices are disabled at run-time */
94967     return;
94968   }
94969   if( (pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)!=0 ){
94970     /* We already have some kind of index in use for this query. */
94971     return;
94972   }
94973   if( pSrc->notIndexed ){
94974     /* The NOT INDEXED clause appears in the SQL. */
94975     return;
94976   }
94977
94978   assert( pParse->nQueryLoop >= (double)1 );
94979   pTable = pSrc->pTab;
94980   nTableRow = pTable->pIndex ? pTable->pIndex->aiRowEst[0] : 1000000;
94981   logN = estLog(nTableRow);
94982   costTempIdx = 2*logN*(nTableRow/pParse->nQueryLoop + 1);
94983   if( costTempIdx>=pCost->rCost ){
94984     /* The cost of creating the transient table would be greater than
94985     ** doing the full table scan */
94986     return;
94987   }
94988
94989   /* Search for any equality comparison term */
94990   pWCEnd = &pWC->a[pWC->nTerm];
94991   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
94992     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
94993       WHERETRACE(("auto-index reduces cost from %.2f to %.2f\n",
94994                     pCost->rCost, costTempIdx));
94995       pCost->rCost = costTempIdx;
94996       pCost->nRow = logN + 1;
94997       pCost->plan.wsFlags = WHERE_TEMP_INDEX;
94998       pCost->used = pTerm->prereqRight;
94999       break;
95000     }
95001   }
95002 }
95003 #else
95004 # define bestAutomaticIndex(A,B,C,D,E)  /* no-op */
95005 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
95006
95007
95008 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
95009 /*
95010 ** Generate code to construct the Index object for an automatic index
95011 ** and to set up the WhereLevel object pLevel so that the code generator
95012 ** makes use of the automatic index.
95013 */
95014 static void constructAutomaticIndex(
95015   Parse *pParse,              /* The parsing context */
95016   WhereClause *pWC,           /* The WHERE clause */
95017   struct SrcList_item *pSrc,  /* The FROM clause term to get the next index */
95018   Bitmask notReady,           /* Mask of cursors that are not available */
95019   WhereLevel *pLevel          /* Write new index here */
95020 ){
95021   int nColumn;                /* Number of columns in the constructed index */
95022   WhereTerm *pTerm;           /* A single term of the WHERE clause */
95023   WhereTerm *pWCEnd;          /* End of pWC->a[] */
95024   int nByte;                  /* Byte of memory needed for pIdx */
95025   Index *pIdx;                /* Object describing the transient index */
95026   Vdbe *v;                    /* Prepared statement under construction */
95027   int regIsInit;              /* Register set by initialization */
95028   int addrInit;               /* Address of the initialization bypass jump */
95029   Table *pTable;              /* The table being indexed */
95030   KeyInfo *pKeyinfo;          /* Key information for the index */   
95031   int addrTop;                /* Top of the index fill loop */
95032   int regRecord;              /* Register holding an index record */
95033   int n;                      /* Column counter */
95034   int i;                      /* Loop counter */
95035   int mxBitCol;               /* Maximum column in pSrc->colUsed */
95036   CollSeq *pColl;             /* Collating sequence to on a column */
95037   Bitmask idxCols;            /* Bitmap of columns used for indexing */
95038   Bitmask extraCols;          /* Bitmap of additional columns */
95039
95040   /* Generate code to skip over the creation and initialization of the
95041   ** transient index on 2nd and subsequent iterations of the loop. */
95042   v = pParse->pVdbe;
95043   assert( v!=0 );
95044   regIsInit = ++pParse->nMem;
95045   addrInit = sqlite3VdbeAddOp1(v, OP_If, regIsInit);
95046   sqlite3VdbeAddOp2(v, OP_Integer, 1, regIsInit);
95047
95048   /* Count the number of columns that will be added to the index
95049   ** and used to match WHERE clause constraints */
95050   nColumn = 0;
95051   pTable = pSrc->pTab;
95052   pWCEnd = &pWC->a[pWC->nTerm];
95053   idxCols = 0;
95054   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
95055     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
95056       int iCol = pTerm->u.leftColumn;
95057       Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
95058       testcase( iCol==BMS );
95059       testcase( iCol==BMS-1 );
95060       if( (idxCols & cMask)==0 ){
95061         nColumn++;
95062         idxCols |= cMask;
95063       }
95064     }
95065   }
95066   assert( nColumn>0 );
95067   pLevel->plan.nEq = nColumn;
95068
95069   /* Count the number of additional columns needed to create a
95070   ** covering index.  A "covering index" is an index that contains all
95071   ** columns that are needed by the query.  With a covering index, the
95072   ** original table never needs to be accessed.  Automatic indices must
95073   ** be a covering index because the index will not be updated if the
95074   ** original table changes and the index and table cannot both be used
95075   ** if they go out of sync.
95076   */
95077   extraCols = pSrc->colUsed & (~idxCols | (((Bitmask)1)<<(BMS-1)));
95078   mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
95079   testcase( pTable->nCol==BMS-1 );
95080   testcase( pTable->nCol==BMS-2 );
95081   for(i=0; i<mxBitCol; i++){
95082     if( extraCols & (((Bitmask)1)<<i) ) nColumn++;
95083   }
95084   if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
95085     nColumn += pTable->nCol - BMS + 1;
95086   }
95087   pLevel->plan.wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WO_EQ;
95088
95089   /* Construct the Index object to describe this index */
95090   nByte = sizeof(Index);
95091   nByte += nColumn*sizeof(int);     /* Index.aiColumn */
95092   nByte += nColumn*sizeof(char*);   /* Index.azColl */
95093   nByte += nColumn;                 /* Index.aSortOrder */
95094   pIdx = sqlite3DbMallocZero(pParse->db, nByte);
95095   if( pIdx==0 ) return;
95096   pLevel->plan.u.pIdx = pIdx;
95097   pIdx->azColl = (char**)&pIdx[1];
95098   pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
95099   pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
95100   pIdx->zName = "auto-index";
95101   pIdx->nColumn = nColumn;
95102   pIdx->pTable = pTable;
95103   n = 0;
95104   idxCols = 0;
95105   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
95106     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
95107       int iCol = pTerm->u.leftColumn;
95108       Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
95109       if( (idxCols & cMask)==0 ){
95110         Expr *pX = pTerm->pExpr;
95111         idxCols |= cMask;
95112         pIdx->aiColumn[n] = pTerm->u.leftColumn;
95113         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
95114         pIdx->azColl[n] = pColl->zName;
95115         n++;
95116       }
95117     }
95118   }
95119   assert( (u32)n==pLevel->plan.nEq );
95120
95121   /* Add additional columns needed to make the automatic index into
95122   ** a covering index */
95123   for(i=0; i<mxBitCol; i++){
95124     if( extraCols & (((Bitmask)1)<<i) ){
95125       pIdx->aiColumn[n] = i;
95126       pIdx->azColl[n] = "BINARY";
95127       n++;
95128     }
95129   }
95130   if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
95131     for(i=BMS-1; i<pTable->nCol; i++){
95132       pIdx->aiColumn[n] = i;
95133       pIdx->azColl[n] = "BINARY";
95134       n++;
95135     }
95136   }
95137   assert( n==nColumn );
95138
95139   /* Create the automatic index */
95140   pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
95141   assert( pLevel->iIdxCur>=0 );
95142   sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
95143                     (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
95144   VdbeComment((v, "for %s", pTable->zName));
95145
95146   /* Fill the automatic index with content */
95147   addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
95148   regRecord = sqlite3GetTempReg(pParse);
95149   sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1);
95150   sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
95151   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
95152   sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
95153   sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
95154   sqlite3VdbeJumpHere(v, addrTop);
95155   sqlite3ReleaseTempReg(pParse, regRecord);
95156   
95157   /* Jump here when skipping the initialization */
95158   sqlite3VdbeJumpHere(v, addrInit);
95159 }
95160 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
95161
95162 #ifndef SQLITE_OMIT_VIRTUALTABLE
95163 /*
95164 ** Allocate and populate an sqlite3_index_info structure. It is the 
95165 ** responsibility of the caller to eventually release the structure
95166 ** by passing the pointer returned by this function to sqlite3_free().
95167 */
95168 static sqlite3_index_info *allocateIndexInfo(
95169   Parse *pParse, 
95170   WhereClause *pWC,
95171   struct SrcList_item *pSrc,
95172   ExprList *pOrderBy
95173 ){
95174   int i, j;
95175   int nTerm;
95176   struct sqlite3_index_constraint *pIdxCons;
95177   struct sqlite3_index_orderby *pIdxOrderBy;
95178   struct sqlite3_index_constraint_usage *pUsage;
95179   WhereTerm *pTerm;
95180   int nOrderBy;
95181   sqlite3_index_info *pIdxInfo;
95182
95183   WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));
95184
95185   /* Count the number of possible WHERE clause constraints referring
95186   ** to this virtual table */
95187   for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
95188     if( pTerm->leftCursor != pSrc->iCursor ) continue;
95189     assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
95190     testcase( pTerm->eOperator==WO_IN );
95191     testcase( pTerm->eOperator==WO_ISNULL );
95192     if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
95193     nTerm++;
95194   }
95195
95196   /* If the ORDER BY clause contains only columns in the current 
95197   ** virtual table then allocate space for the aOrderBy part of
95198   ** the sqlite3_index_info structure.
95199   */
95200   nOrderBy = 0;
95201   if( pOrderBy ){
95202     for(i=0; i<pOrderBy->nExpr; i++){
95203       Expr *pExpr = pOrderBy->a[i].pExpr;
95204       if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
95205     }
95206     if( i==pOrderBy->nExpr ){
95207       nOrderBy = pOrderBy->nExpr;
95208     }
95209   }
95210
95211   /* Allocate the sqlite3_index_info structure
95212   */
95213   pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
95214                            + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
95215                            + sizeof(*pIdxOrderBy)*nOrderBy );
95216   if( pIdxInfo==0 ){
95217     sqlite3ErrorMsg(pParse, "out of memory");
95218     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
95219     return 0;
95220   }
95221
95222   /* Initialize the structure.  The sqlite3_index_info structure contains
95223   ** many fields that are declared "const" to prevent xBestIndex from
95224   ** changing them.  We have to do some funky casting in order to
95225   ** initialize those fields.
95226   */
95227   pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
95228   pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
95229   pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
95230   *(int*)&pIdxInfo->nConstraint = nTerm;
95231   *(int*)&pIdxInfo->nOrderBy = nOrderBy;
95232   *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
95233   *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
95234   *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
95235                                                                    pUsage;
95236
95237   for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
95238     if( pTerm->leftCursor != pSrc->iCursor ) continue;
95239     assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
95240     testcase( pTerm->eOperator==WO_IN );
95241     testcase( pTerm->eOperator==WO_ISNULL );
95242     if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
95243     pIdxCons[j].iColumn = pTerm->u.leftColumn;
95244     pIdxCons[j].iTermOffset = i;
95245     pIdxCons[j].op = (u8)pTerm->eOperator;
95246     /* The direct assignment in the previous line is possible only because
95247     ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
95248     ** following asserts verify this fact. */
95249     assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
95250     assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
95251     assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
95252     assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
95253     assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
95254     assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
95255     assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
95256     j++;
95257   }
95258   for(i=0; i<nOrderBy; i++){
95259     Expr *pExpr = pOrderBy->a[i].pExpr;
95260     pIdxOrderBy[i].iColumn = pExpr->iColumn;
95261     pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
95262   }
95263
95264   return pIdxInfo;
95265 }
95266
95267 /*
95268 ** The table object reference passed as the second argument to this function
95269 ** must represent a virtual table. This function invokes the xBestIndex()
95270 ** method of the virtual table with the sqlite3_index_info pointer passed
95271 ** as the argument.
95272 **
95273 ** If an error occurs, pParse is populated with an error message and a
95274 ** non-zero value is returned. Otherwise, 0 is returned and the output
95275 ** part of the sqlite3_index_info structure is left populated.
95276 **
95277 ** Whether or not an error is returned, it is the responsibility of the
95278 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
95279 ** that this is required.
95280 */
95281 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
95282   sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
95283   int i;
95284   int rc;
95285
95286   WHERETRACE(("xBestIndex for %s\n", pTab->zName));
95287   TRACE_IDX_INPUTS(p);
95288   rc = pVtab->pModule->xBestIndex(pVtab, p);
95289   TRACE_IDX_OUTPUTS(p);
95290
95291   if( rc!=SQLITE_OK ){
95292     if( rc==SQLITE_NOMEM ){
95293       pParse->db->mallocFailed = 1;
95294     }else if( !pVtab->zErrMsg ){
95295       sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
95296     }else{
95297       sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
95298     }
95299   }
95300   sqlite3DbFree(pParse->db, pVtab->zErrMsg);
95301   pVtab->zErrMsg = 0;
95302
95303   for(i=0; i<p->nConstraint; i++){
95304     if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
95305       sqlite3ErrorMsg(pParse, 
95306           "table %s: xBestIndex returned an invalid plan", pTab->zName);
95307     }
95308   }
95309
95310   return pParse->nErr;
95311 }
95312
95313
95314 /*
95315 ** Compute the best index for a virtual table.
95316 **
95317 ** The best index is computed by the xBestIndex method of the virtual
95318 ** table module.  This routine is really just a wrapper that sets up
95319 ** the sqlite3_index_info structure that is used to communicate with
95320 ** xBestIndex.
95321 **
95322 ** In a join, this routine might be called multiple times for the
95323 ** same virtual table.  The sqlite3_index_info structure is created
95324 ** and initialized on the first invocation and reused on all subsequent
95325 ** invocations.  The sqlite3_index_info structure is also used when
95326 ** code is generated to access the virtual table.  The whereInfoDelete() 
95327 ** routine takes care of freeing the sqlite3_index_info structure after
95328 ** everybody has finished with it.
95329 */
95330 static void bestVirtualIndex(
95331   Parse *pParse,                  /* The parsing context */
95332   WhereClause *pWC,               /* The WHERE clause */
95333   struct SrcList_item *pSrc,      /* The FROM clause term to search */
95334   Bitmask notReady,               /* Mask of cursors that are not available */
95335   ExprList *pOrderBy,             /* The order by clause */
95336   WhereCost *pCost,               /* Lowest cost query plan */
95337   sqlite3_index_info **ppIdxInfo  /* Index information passed to xBestIndex */
95338 ){
95339   Table *pTab = pSrc->pTab;
95340   sqlite3_index_info *pIdxInfo;
95341   struct sqlite3_index_constraint *pIdxCons;
95342   struct sqlite3_index_constraint_usage *pUsage;
95343   WhereTerm *pTerm;
95344   int i, j;
95345   int nOrderBy;
95346   double rCost;
95347
95348   /* Make sure wsFlags is initialized to some sane value. Otherwise, if the 
95349   ** malloc in allocateIndexInfo() fails and this function returns leaving
95350   ** wsFlags in an uninitialized state, the caller may behave unpredictably.
95351   */
95352   memset(pCost, 0, sizeof(*pCost));
95353   pCost->plan.wsFlags = WHERE_VIRTUALTABLE;
95354
95355   /* If the sqlite3_index_info structure has not been previously
95356   ** allocated and initialized, then allocate and initialize it now.
95357   */
95358   pIdxInfo = *ppIdxInfo;
95359   if( pIdxInfo==0 ){
95360     *ppIdxInfo = pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pOrderBy);
95361   }
95362   if( pIdxInfo==0 ){
95363     return;
95364   }
95365
95366   /* At this point, the sqlite3_index_info structure that pIdxInfo points
95367   ** to will have been initialized, either during the current invocation or
95368   ** during some prior invocation.  Now we just have to customize the
95369   ** details of pIdxInfo for the current invocation and pass it to
95370   ** xBestIndex.
95371   */
95372
95373   /* The module name must be defined. Also, by this point there must
95374   ** be a pointer to an sqlite3_vtab structure. Otherwise
95375   ** sqlite3ViewGetColumnNames() would have picked up the error. 
95376   */
95377   assert( pTab->azModuleArg && pTab->azModuleArg[0] );
95378   assert( sqlite3GetVTable(pParse->db, pTab) );
95379
95380   /* Set the aConstraint[].usable fields and initialize all 
95381   ** output variables to zero.
95382   **
95383   ** aConstraint[].usable is true for constraints where the right-hand
95384   ** side contains only references to tables to the left of the current
95385   ** table.  In other words, if the constraint is of the form:
95386   **
95387   **           column = expr
95388   **
95389   ** and we are evaluating a join, then the constraint on column is 
95390   ** only valid if all tables referenced in expr occur to the left
95391   ** of the table containing column.
95392   **
95393   ** The aConstraints[] array contains entries for all constraints
95394   ** on the current table.  That way we only have to compute it once
95395   ** even though we might try to pick the best index multiple times.
95396   ** For each attempt at picking an index, the order of tables in the
95397   ** join might be different so we have to recompute the usable flag
95398   ** each time.
95399   */
95400   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
95401   pUsage = pIdxInfo->aConstraintUsage;
95402   for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
95403     j = pIdxCons->iTermOffset;
95404     pTerm = &pWC->a[j];
95405     pIdxCons->usable = (pTerm->prereqRight&notReady) ? 0 : 1;
95406   }
95407   memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
95408   if( pIdxInfo->needToFreeIdxStr ){
95409     sqlite3_free(pIdxInfo->idxStr);
95410   }
95411   pIdxInfo->idxStr = 0;
95412   pIdxInfo->idxNum = 0;
95413   pIdxInfo->needToFreeIdxStr = 0;
95414   pIdxInfo->orderByConsumed = 0;
95415   /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
95416   pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);
95417   nOrderBy = pIdxInfo->nOrderBy;
95418   if( !pOrderBy ){
95419     pIdxInfo->nOrderBy = 0;
95420   }
95421
95422   if( vtabBestIndex(pParse, pTab, pIdxInfo) ){
95423     return;
95424   }
95425
95426   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
95427   for(i=0; i<pIdxInfo->nConstraint; i++){
95428     if( pUsage[i].argvIndex>0 ){
95429       pCost->used |= pWC->a[pIdxCons[i].iTermOffset].prereqRight;
95430     }
95431   }
95432
95433   /* If there is an ORDER BY clause, and the selected virtual table index
95434   ** does not satisfy it, increase the cost of the scan accordingly. This
95435   ** matches the processing for non-virtual tables in bestBtreeIndex().
95436   */
95437   rCost = pIdxInfo->estimatedCost;
95438   if( pOrderBy && pIdxInfo->orderByConsumed==0 ){
95439     rCost += estLog(rCost)*rCost;
95440   }
95441
95442   /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
95443   ** inital value of lowestCost in this loop. If it is, then the
95444   ** (cost<lowestCost) test below will never be true.
95445   ** 
95446   ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT 
95447   ** is defined.
95448   */
95449   if( (SQLITE_BIG_DBL/((double)2))<rCost ){
95450     pCost->rCost = (SQLITE_BIG_DBL/((double)2));
95451   }else{
95452     pCost->rCost = rCost;
95453   }
95454   pCost->plan.u.pVtabIdx = pIdxInfo;
95455   if( pIdxInfo->orderByConsumed ){
95456     pCost->plan.wsFlags |= WHERE_ORDERBY;
95457   }
95458   pCost->plan.nEq = 0;
95459   pIdxInfo->nOrderBy = nOrderBy;
95460
95461   /* Try to find a more efficient access pattern by using multiple indexes
95462   ** to optimize an OR expression within the WHERE clause. 
95463   */
95464   bestOrClauseIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
95465 }
95466 #endif /* SQLITE_OMIT_VIRTUALTABLE */
95467
95468 /*
95469 ** Argument pIdx is a pointer to an index structure that has an array of
95470 ** SQLITE_INDEX_SAMPLES evenly spaced samples of the first indexed column
95471 ** stored in Index.aSample. The domain of values stored in said column
95472 ** may be thought of as divided into (SQLITE_INDEX_SAMPLES+1) regions.
95473 ** Region 0 contains all values smaller than the first sample value. Region
95474 ** 1 contains values larger than or equal to the value of the first sample,
95475 ** but smaller than the value of the second. And so on.
95476 **
95477 ** If successful, this function determines which of the regions value 
95478 ** pVal lies in, sets *piRegion to the region index (a value between 0
95479 ** and SQLITE_INDEX_SAMPLES+1, inclusive) and returns SQLITE_OK.
95480 ** Or, if an OOM occurs while converting text values between encodings,
95481 ** SQLITE_NOMEM is returned and *piRegion is undefined.
95482 */
95483 #ifdef SQLITE_ENABLE_STAT2
95484 static int whereRangeRegion(
95485   Parse *pParse,              /* Database connection */
95486   Index *pIdx,                /* Index to consider domain of */
95487   sqlite3_value *pVal,        /* Value to consider */
95488   int *piRegion               /* OUT: Region of domain in which value lies */
95489 ){
95490   if( ALWAYS(pVal) ){
95491     IndexSample *aSample = pIdx->aSample;
95492     int i = 0;
95493     int eType = sqlite3_value_type(pVal);
95494
95495     if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
95496       double r = sqlite3_value_double(pVal);
95497       for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
95498         if( aSample[i].eType==SQLITE_NULL ) continue;
95499         if( aSample[i].eType>=SQLITE_TEXT || aSample[i].u.r>r ) break;
95500       }
95501     }else{ 
95502       sqlite3 *db = pParse->db;
95503       CollSeq *pColl;
95504       const u8 *z;
95505       int n;
95506
95507       /* pVal comes from sqlite3ValueFromExpr() so the type cannot be NULL */
95508       assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
95509
95510       if( eType==SQLITE_BLOB ){
95511         z = (const u8 *)sqlite3_value_blob(pVal);
95512         pColl = db->pDfltColl;
95513         assert( pColl->enc==SQLITE_UTF8 );
95514       }else{
95515         pColl = sqlite3GetCollSeq(db, SQLITE_UTF8, 0, *pIdx->azColl);
95516         if( pColl==0 ){
95517           sqlite3ErrorMsg(pParse, "no such collation sequence: %s",
95518                           *pIdx->azColl);
95519           return SQLITE_ERROR;
95520         }
95521         z = (const u8 *)sqlite3ValueText(pVal, pColl->enc);
95522         if( !z ){
95523           return SQLITE_NOMEM;
95524         }
95525         assert( z && pColl && pColl->xCmp );
95526       }
95527       n = sqlite3ValueBytes(pVal, pColl->enc);
95528
95529       for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
95530         int r;
95531         int eSampletype = aSample[i].eType;
95532         if( eSampletype==SQLITE_NULL || eSampletype<eType ) continue;
95533         if( (eSampletype!=eType) ) break;
95534 #ifndef SQLITE_OMIT_UTF16
95535         if( pColl->enc!=SQLITE_UTF8 ){
95536           int nSample;
95537           char *zSample = sqlite3Utf8to16(
95538               db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample
95539           );
95540           if( !zSample ){
95541             assert( db->mallocFailed );
95542             return SQLITE_NOMEM;
95543           }
95544           r = pColl->xCmp(pColl->pUser, nSample, zSample, n, z);
95545           sqlite3DbFree(db, zSample);
95546         }else
95547 #endif
95548         {
95549           r = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z);
95550         }
95551         if( r>0 ) break;
95552       }
95553     }
95554
95555     assert( i>=0 && i<=SQLITE_INDEX_SAMPLES );
95556     *piRegion = i;
95557   }
95558   return SQLITE_OK;
95559 }
95560 #endif   /* #ifdef SQLITE_ENABLE_STAT2 */
95561
95562 /*
95563 ** If expression pExpr represents a literal value, set *pp to point to
95564 ** an sqlite3_value structure containing the same value, with affinity
95565 ** aff applied to it, before returning. It is the responsibility of the 
95566 ** caller to eventually release this structure by passing it to 
95567 ** sqlite3ValueFree().
95568 **
95569 ** If the current parse is a recompile (sqlite3Reprepare()) and pExpr
95570 ** is an SQL variable that currently has a non-NULL value bound to it,
95571 ** create an sqlite3_value structure containing this value, again with
95572 ** affinity aff applied to it, instead.
95573 **
95574 ** If neither of the above apply, set *pp to NULL.
95575 **
95576 ** If an error occurs, return an error code. Otherwise, SQLITE_OK.
95577 */
95578 #ifdef SQLITE_ENABLE_STAT2
95579 static int valueFromExpr(
95580   Parse *pParse, 
95581   Expr *pExpr, 
95582   u8 aff, 
95583   sqlite3_value **pp
95584 ){
95585   /* The evalConstExpr() function will have already converted any TK_VARIABLE
95586   ** expression involved in an comparison into a TK_REGISTER. */
95587   assert( pExpr->op!=TK_VARIABLE );
95588   if( pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE ){
95589     int iVar = pExpr->iColumn;
95590     sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
95591     *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);
95592     return SQLITE_OK;
95593   }
95594   return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
95595 }
95596 #endif
95597
95598 /*
95599 ** This function is used to estimate the number of rows that will be visited
95600 ** by scanning an index for a range of values. The range may have an upper
95601 ** bound, a lower bound, or both. The WHERE clause terms that set the upper
95602 ** and lower bounds are represented by pLower and pUpper respectively. For
95603 ** example, assuming that index p is on t1(a):
95604 **
95605 **   ... FROM t1 WHERE a > ? AND a < ? ...
95606 **                    |_____|   |_____|
95607 **                       |         |
95608 **                     pLower    pUpper
95609 **
95610 ** If either of the upper or lower bound is not present, then NULL is passed in
95611 ** place of the corresponding WhereTerm.
95612 **
95613 ** The nEq parameter is passed the index of the index column subject to the
95614 ** range constraint. Or, equivalently, the number of equality constraints
95615 ** optimized by the proposed index scan. For example, assuming index p is
95616 ** on t1(a, b), and the SQL query is:
95617 **
95618 **   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
95619 **
95620 ** then nEq should be passed the value 1 (as the range restricted column,
95621 ** b, is the second left-most column of the index). Or, if the query is:
95622 **
95623 **   ... FROM t1 WHERE a > ? AND a < ? ...
95624 **
95625 ** then nEq should be passed 0.
95626 **
95627 ** The returned value is an integer between 1 and 100, inclusive. A return
95628 ** value of 1 indicates that the proposed range scan is expected to visit
95629 ** approximately 1/100th (1%) of the rows selected by the nEq equality
95630 ** constraints (if any). A return value of 100 indicates that it is expected
95631 ** that the range scan will visit every row (100%) selected by the equality
95632 ** constraints.
95633 **
95634 ** In the absence of sqlite_stat2 ANALYZE data, each range inequality
95635 ** reduces the search space by 2/3rds.  Hence a single constraint (x>?)
95636 ** results in a return of 33 and a range constraint (x>? AND x<?) results
95637 ** in a return of 11.
95638 */
95639 static int whereRangeScanEst(
95640   Parse *pParse,       /* Parsing & code generating context */
95641   Index *p,            /* The index containing the range-compared column; "x" */
95642   int nEq,             /* index into p->aCol[] of the range-compared column */
95643   WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
95644   WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
95645   int *piEst           /* OUT: Return value */
95646 ){
95647   int rc = SQLITE_OK;
95648
95649 #ifdef SQLITE_ENABLE_STAT2
95650
95651   if( nEq==0 && p->aSample ){
95652     sqlite3_value *pLowerVal = 0;
95653     sqlite3_value *pUpperVal = 0;
95654     int iEst;
95655     int iLower = 0;
95656     int iUpper = SQLITE_INDEX_SAMPLES;
95657     u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
95658
95659     if( pLower ){
95660       Expr *pExpr = pLower->pExpr->pRight;
95661       rc = valueFromExpr(pParse, pExpr, aff, &pLowerVal);
95662     }
95663     if( rc==SQLITE_OK && pUpper ){
95664       Expr *pExpr = pUpper->pExpr->pRight;
95665       rc = valueFromExpr(pParse, pExpr, aff, &pUpperVal);
95666     }
95667
95668     if( rc!=SQLITE_OK || (pLowerVal==0 && pUpperVal==0) ){
95669       sqlite3ValueFree(pLowerVal);
95670       sqlite3ValueFree(pUpperVal);
95671       goto range_est_fallback;
95672     }else if( pLowerVal==0 ){
95673       rc = whereRangeRegion(pParse, p, pUpperVal, &iUpper);
95674       if( pLower ) iLower = iUpper/2;
95675     }else if( pUpperVal==0 ){
95676       rc = whereRangeRegion(pParse, p, pLowerVal, &iLower);
95677       if( pUpper ) iUpper = (iLower + SQLITE_INDEX_SAMPLES + 1)/2;
95678     }else{
95679       rc = whereRangeRegion(pParse, p, pUpperVal, &iUpper);
95680       if( rc==SQLITE_OK ){
95681         rc = whereRangeRegion(pParse, p, pLowerVal, &iLower);
95682       }
95683     }
95684
95685     iEst = iUpper - iLower;
95686     testcase( iEst==SQLITE_INDEX_SAMPLES );
95687     assert( iEst<=SQLITE_INDEX_SAMPLES );
95688     if( iEst<1 ){
95689       iEst = 1;
95690     }
95691
95692     sqlite3ValueFree(pLowerVal);
95693     sqlite3ValueFree(pUpperVal);
95694     *piEst = (iEst * 100)/SQLITE_INDEX_SAMPLES;
95695     return rc;
95696   }
95697 range_est_fallback:
95698 #else
95699   UNUSED_PARAMETER(pParse);
95700   UNUSED_PARAMETER(p);
95701   UNUSED_PARAMETER(nEq);
95702 #endif
95703   assert( pLower || pUpper );
95704   if( pLower && pUpper ){
95705     *piEst = 11;
95706   }else{
95707     *piEst = 33;
95708   }
95709   return rc;
95710 }
95711
95712
95713 /*
95714 ** Find the query plan for accessing a particular table.  Write the
95715 ** best query plan and its cost into the WhereCost object supplied as the
95716 ** last parameter.
95717 **
95718 ** The lowest cost plan wins.  The cost is an estimate of the amount of
95719 ** CPU and disk I/O need to process the request using the selected plan.
95720 ** Factors that influence cost include:
95721 **
95722 **    *  The estimated number of rows that will be retrieved.  (The
95723 **       fewer the better.)
95724 **
95725 **    *  Whether or not sorting must occur.
95726 **
95727 **    *  Whether or not there must be separate lookups in the
95728 **       index and in the main table.
95729 **
95730 ** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in
95731 ** the SQL statement, then this function only considers plans using the 
95732 ** named index. If no such plan is found, then the returned cost is
95733 ** SQLITE_BIG_DBL. If a plan is found that uses the named index, 
95734 ** then the cost is calculated in the usual way.
95735 **
95736 ** If a NOT INDEXED clause (pSrc->notIndexed!=0) was attached to the table 
95737 ** in the SELECT statement, then no indexes are considered. However, the 
95738 ** selected plan may still take advantage of the tables built-in rowid
95739 ** index.
95740 */
95741 static void bestBtreeIndex(
95742   Parse *pParse,              /* The parsing context */
95743   WhereClause *pWC,           /* The WHERE clause */
95744   struct SrcList_item *pSrc,  /* The FROM clause term to search */
95745   Bitmask notReady,           /* Mask of cursors that are not available */
95746   ExprList *pOrderBy,         /* The ORDER BY clause */
95747   WhereCost *pCost            /* Lowest cost query plan */
95748 ){
95749   int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
95750   Index *pProbe;              /* An index we are evaluating */
95751   Index *pIdx;                /* Copy of pProbe, or zero for IPK index */
95752   int eqTermMask;             /* Current mask of valid equality operators */
95753   int idxEqTermMask;          /* Index mask of valid equality operators */
95754   Index sPk;                  /* A fake index object for the primary key */
95755   unsigned int aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
95756   int aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
95757   int wsFlagMask;             /* Allowed flags in pCost->plan.wsFlag */
95758
95759   /* Initialize the cost to a worst-case value */
95760   memset(pCost, 0, sizeof(*pCost));
95761   pCost->rCost = SQLITE_BIG_DBL;
95762
95763   /* If the pSrc table is the right table of a LEFT JOIN then we may not
95764   ** use an index to satisfy IS NULL constraints on that table.  This is
95765   ** because columns might end up being NULL if the table does not match -
95766   ** a circumstance which the index cannot help us discover.  Ticket #2177.
95767   */
95768   if( pSrc->jointype & JT_LEFT ){
95769     idxEqTermMask = WO_EQ|WO_IN;
95770   }else{
95771     idxEqTermMask = WO_EQ|WO_IN|WO_ISNULL;
95772   }
95773
95774   if( pSrc->pIndex ){
95775     /* An INDEXED BY clause specifies a particular index to use */
95776     pIdx = pProbe = pSrc->pIndex;
95777     wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
95778     eqTermMask = idxEqTermMask;
95779   }else{
95780     /* There is no INDEXED BY clause.  Create a fake Index object to
95781     ** represent the primary key */
95782     Index *pFirst;                /* Any other index on the table */
95783     memset(&sPk, 0, sizeof(Index));
95784     sPk.nColumn = 1;
95785     sPk.aiColumn = &aiColumnPk;
95786     sPk.aiRowEst = aiRowEstPk;
95787     aiRowEstPk[1] = 1;
95788     sPk.onError = OE_Replace;
95789     sPk.pTable = pSrc->pTab;
95790     pFirst = pSrc->pTab->pIndex;
95791     if( pSrc->notIndexed==0 ){
95792       sPk.pNext = pFirst;
95793     }
95794     /* The aiRowEstPk[0] is an estimate of the total number of rows in the
95795     ** table.  Get this information from the ANALYZE information if it is
95796     ** available.  If not available, assume the table 1 million rows in size.
95797     */
95798     if( pFirst ){
95799       assert( pFirst->aiRowEst!=0 ); /* Allocated together with pFirst */
95800       aiRowEstPk[0] = pFirst->aiRowEst[0];
95801     }else{
95802       aiRowEstPk[0] = 1000000;
95803     }
95804     pProbe = &sPk;
95805     wsFlagMask = ~(
95806         WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE
95807     );
95808     eqTermMask = WO_EQ|WO_IN;
95809     pIdx = 0;
95810   }
95811
95812   /* Loop over all indices looking for the best one to use
95813   */
95814   for(; pProbe; pIdx=pProbe=pProbe->pNext){
95815     const unsigned int * const aiRowEst = pProbe->aiRowEst;
95816     double cost;                /* Cost of using pProbe */
95817     double nRow;                /* Estimated number of rows in result set */
95818     int rev;                    /* True to scan in reverse order */
95819     int wsFlags = 0;
95820     Bitmask used = 0;
95821
95822     /* The following variables are populated based on the properties of
95823     ** scan being evaluated. They are then used to determine the expected
95824     ** cost and number of rows returned.
95825     **
95826     **  nEq: 
95827     **    Number of equality terms that can be implemented using the index.
95828     **
95829     **  nInMul:  
95830     **    The "in-multiplier". This is an estimate of how many seek operations 
95831     **    SQLite must perform on the index in question. For example, if the 
95832     **    WHERE clause is:
95833     **
95834     **      WHERE a IN (1, 2, 3) AND b IN (4, 5, 6)
95835     **
95836     **    SQLite must perform 9 lookups on an index on (a, b), so nInMul is 
95837     **    set to 9. Given the same schema and either of the following WHERE 
95838     **    clauses:
95839     **
95840     **      WHERE a =  1
95841     **      WHERE a >= 2
95842     **
95843     **    nInMul is set to 1.
95844     **
95845     **    If there exists a WHERE term of the form "x IN (SELECT ...)", then 
95846     **    the sub-select is assumed to return 25 rows for the purposes of 
95847     **    determining nInMul.
95848     **
95849     **  bInEst:  
95850     **    Set to true if there was at least one "x IN (SELECT ...)" term used 
95851     **    in determining the value of nInMul.
95852     **
95853     **  estBound:
95854     **    An estimate on the amount of the table that must be searched.  A
95855     **    value of 100 means the entire table is searched.  Range constraints
95856     **    might reduce this to a value less than 100 to indicate that only
95857     **    a fraction of the table needs searching.  In the absence of
95858     **    sqlite_stat2 ANALYZE data, a single inequality reduces the search
95859     **    space to 1/3rd its original size.  So an x>? constraint reduces
95860     **    estBound to 33.  Two constraints (x>? AND x<?) reduce estBound to 11.
95861     **
95862     **  bSort:   
95863     **    Boolean. True if there is an ORDER BY clause that will require an 
95864     **    external sort (i.e. scanning the index being evaluated will not 
95865     **    correctly order records).
95866     **
95867     **  bLookup: 
95868     **    Boolean. True if for each index entry visited a lookup on the 
95869     **    corresponding table b-tree is required. This is always false 
95870     **    for the rowid index. For other indexes, it is true unless all the 
95871     **    columns of the table used by the SELECT statement are present in 
95872     **    the index (such an index is sometimes described as a covering index).
95873     **    For example, given the index on (a, b), the second of the following 
95874     **    two queries requires table b-tree lookups, but the first does not.
95875     **
95876     **             SELECT a, b    FROM tbl WHERE a = 1;
95877     **             SELECT a, b, c FROM tbl WHERE a = 1;
95878     */
95879     int nEq;
95880     int bInEst = 0;
95881     int nInMul = 1;
95882     int estBound = 100;
95883     int nBound = 0;             /* Number of range constraints seen */
95884     int bSort = 0;
95885     int bLookup = 0;
95886     WhereTerm *pTerm;           /* A single term of the WHERE clause */
95887
95888     /* Determine the values of nEq and nInMul */
95889     for(nEq=0; nEq<pProbe->nColumn; nEq++){
95890       int j = pProbe->aiColumn[nEq];
95891       pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pIdx);
95892       if( pTerm==0 ) break;
95893       wsFlags |= (WHERE_COLUMN_EQ|WHERE_ROWID_EQ);
95894       if( pTerm->eOperator & WO_IN ){
95895         Expr *pExpr = pTerm->pExpr;
95896         wsFlags |= WHERE_COLUMN_IN;
95897         if( ExprHasProperty(pExpr, EP_xIsSelect) ){
95898           nInMul *= 25;
95899           bInEst = 1;
95900         }else if( ALWAYS(pExpr->x.pList) ){
95901           nInMul *= pExpr->x.pList->nExpr + 1;
95902         }
95903       }else if( pTerm->eOperator & WO_ISNULL ){
95904         wsFlags |= WHERE_COLUMN_NULL;
95905       }
95906       used |= pTerm->prereqRight;
95907     }
95908
95909     /* Determine the value of estBound. */
95910     if( nEq<pProbe->nColumn ){
95911       int j = pProbe->aiColumn[nEq];
95912       if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){
95913         WhereTerm *pTop = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pIdx);
95914         WhereTerm *pBtm = findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pIdx);
95915         whereRangeScanEst(pParse, pProbe, nEq, pBtm, pTop, &estBound);
95916         if( pTop ){
95917           nBound = 1;
95918           wsFlags |= WHERE_TOP_LIMIT;
95919           used |= pTop->prereqRight;
95920         }
95921         if( pBtm ){
95922           nBound++;
95923           wsFlags |= WHERE_BTM_LIMIT;
95924           used |= pBtm->prereqRight;
95925         }
95926         wsFlags |= (WHERE_COLUMN_RANGE|WHERE_ROWID_RANGE);
95927       }
95928     }else if( pProbe->onError!=OE_None ){
95929       testcase( wsFlags & WHERE_COLUMN_IN );
95930       testcase( wsFlags & WHERE_COLUMN_NULL );
95931       if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){
95932         wsFlags |= WHERE_UNIQUE;
95933       }
95934     }
95935
95936     /* If there is an ORDER BY clause and the index being considered will
95937     ** naturally scan rows in the required order, set the appropriate flags
95938     ** in wsFlags. Otherwise, if there is an ORDER BY clause but the index
95939     ** will scan rows in a different order, set the bSort variable.  */
95940     if( pOrderBy ){
95941       if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0
95942         && isSortingIndex(pParse,pWC->pMaskSet,pProbe,iCur,pOrderBy,nEq,&rev)
95943       ){
95944         wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_ORDERBY;
95945         wsFlags |= (rev ? WHERE_REVERSE : 0);
95946       }else{
95947         bSort = 1;
95948       }
95949     }
95950
95951     /* If currently calculating the cost of using an index (not the IPK
95952     ** index), determine if all required column data may be obtained without 
95953     ** using the main table (i.e. if the index is a covering
95954     ** index for this query). If it is, set the WHERE_IDX_ONLY flag in
95955     ** wsFlags. Otherwise, set the bLookup variable to true.  */
95956     if( pIdx && wsFlags ){
95957       Bitmask m = pSrc->colUsed;
95958       int j;
95959       for(j=0; j<pIdx->nColumn; j++){
95960         int x = pIdx->aiColumn[j];
95961         if( x<BMS-1 ){
95962           m &= ~(((Bitmask)1)<<x);
95963         }
95964       }
95965       if( m==0 ){
95966         wsFlags |= WHERE_IDX_ONLY;
95967       }else{
95968         bLookup = 1;
95969       }
95970     }
95971
95972     /*
95973     ** Estimate the number of rows of output.  For an IN operator,
95974     ** do not let the estimate exceed half the rows in the table.
95975     */
95976     nRow = (double)(aiRowEst[nEq] * nInMul);
95977     if( bInEst && nRow*2>aiRowEst[0] ){
95978       nRow = aiRowEst[0]/2;
95979       nInMul = (int)(nRow / aiRowEst[nEq]);
95980     }
95981
95982     /* Assume constant cost to access a row and logarithmic cost to
95983     ** do a binary search.  Hence, the initial cost is the number of output
95984     ** rows plus log2(table-size) times the number of binary searches.
95985     */
95986     cost = nRow + nInMul*estLog(aiRowEst[0]);
95987
95988     /* Adjust the number of rows and the cost downward to reflect rows
95989     ** that are excluded by range constraints.
95990     */
95991     nRow = (nRow * (double)estBound) / (double)100;
95992     cost = (cost * (double)estBound) / (double)100;
95993
95994     /* Add in the estimated cost of sorting the result
95995     */
95996     if( bSort ){
95997       cost += cost*estLog(cost);
95998     }
95999
96000     /* If all information can be taken directly from the index, we avoid
96001     ** doing table lookups.  This reduces the cost by half.  (Not really -
96002     ** this needs to be fixed.)
96003     */
96004     if( pIdx && bLookup==0 ){
96005       cost /= (double)2;
96006     }
96007     /**** Cost of using this index has now been computed ****/
96008
96009     /* If there are additional constraints on this table that cannot
96010     ** be used with the current index, but which might lower the number
96011     ** of output rows, adjust the nRow value accordingly.  This only 
96012     ** matters if the current index is the least costly, so do not bother
96013     ** with this step if we already know this index will not be chosen.
96014     ** Also, never reduce the output row count below 2 using this step.
96015     **
96016     ** Do not reduce the output row count if pSrc is the only table that
96017     ** is notReady; if notReady is a power of two.  This will be the case
96018     ** when the main sqlite3WhereBegin() loop is scanning for a table with
96019     ** and "optimal" index, and on such a scan the output row count
96020     ** reduction is not valid because it does not update the "pCost->used"
96021     ** bitmap.  The notReady bitmap will also be a power of two when we
96022     ** are scanning for the last table in a 64-way join.  We are willing
96023     ** to bypass this optimization in that corner case.
96024     */
96025     if( nRow>2 && cost<=pCost->rCost && (notReady & (notReady-1))!=0 ){
96026       int k;                       /* Loop counter */
96027       int nSkipEq = nEq;           /* Number of == constraints to skip */
96028       int nSkipRange = nBound;     /* Number of < constraints to skip */
96029       Bitmask thisTab;             /* Bitmap for pSrc */
96030
96031       thisTab = getMask(pWC->pMaskSet, iCur);
96032       for(pTerm=pWC->a, k=pWC->nTerm; nRow>2 && k; k--, pTerm++){
96033         if( pTerm->wtFlags & TERM_VIRTUAL ) continue;
96034         if( (pTerm->prereqAll & notReady)!=thisTab ) continue;
96035         if( pTerm->eOperator & (WO_EQ|WO_IN|WO_ISNULL) ){
96036           if( nSkipEq ){
96037             /* Ignore the first nEq equality matches since the index
96038             ** has already accounted for these */
96039             nSkipEq--;
96040           }else{
96041             /* Assume each additional equality match reduces the result
96042             ** set size by a factor of 10 */
96043             nRow /= 10;
96044           }
96045         }else if( pTerm->eOperator & (WO_LT|WO_LE|WO_GT|WO_GE) ){
96046           if( nSkipRange ){
96047             /* Ignore the first nBound range constraints since the index
96048             ** has already accounted for these */
96049             nSkipRange--;
96050           }else{
96051             /* Assume each additional range constraint reduces the result
96052             ** set size by a factor of 3 */
96053             nRow /= 3;
96054           }
96055         }else{
96056           /* Any other expression lowers the output row count by half */
96057           nRow /= 2;
96058         }
96059       }
96060       if( nRow<2 ) nRow = 2;
96061     }
96062
96063
96064     WHERETRACE((
96065       "%s(%s): nEq=%d nInMul=%d estBound=%d bSort=%d bLookup=%d wsFlags=0x%x\n"
96066       "         notReady=0x%llx nRow=%.2f cost=%.2f used=0x%llx\n",
96067       pSrc->pTab->zName, (pIdx ? pIdx->zName : "ipk"), 
96068       nEq, nInMul, estBound, bSort, bLookup, wsFlags,
96069       notReady, nRow, cost, used
96070     ));
96071
96072     /* If this index is the best we have seen so far, then record this
96073     ** index and its cost in the pCost structure.
96074     */
96075     if( (!pIdx || wsFlags)
96076      && (cost<pCost->rCost || (cost<=pCost->rCost && nRow<pCost->nRow))
96077     ){
96078       pCost->rCost = cost;
96079       pCost->nRow = nRow;
96080       pCost->used = used;
96081       pCost->plan.wsFlags = (wsFlags&wsFlagMask);
96082       pCost->plan.nEq = nEq;
96083       pCost->plan.u.pIdx = pIdx;
96084     }
96085
96086     /* If there was an INDEXED BY clause, then only that one index is
96087     ** considered. */
96088     if( pSrc->pIndex ) break;
96089
96090     /* Reset masks for the next index in the loop */
96091     wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
96092     eqTermMask = idxEqTermMask;
96093   }
96094
96095   /* If there is no ORDER BY clause and the SQLITE_ReverseOrder flag
96096   ** is set, then reverse the order that the index will be scanned
96097   ** in. This is used for application testing, to help find cases
96098   ** where application behaviour depends on the (undefined) order that
96099   ** SQLite outputs rows in in the absence of an ORDER BY clause.  */
96100   if( !pOrderBy && pParse->db->flags & SQLITE_ReverseOrder ){
96101     pCost->plan.wsFlags |= WHERE_REVERSE;
96102   }
96103
96104   assert( pOrderBy || (pCost->plan.wsFlags&WHERE_ORDERBY)==0 );
96105   assert( pCost->plan.u.pIdx==0 || (pCost->plan.wsFlags&WHERE_ROWID_EQ)==0 );
96106   assert( pSrc->pIndex==0 
96107        || pCost->plan.u.pIdx==0 
96108        || pCost->plan.u.pIdx==pSrc->pIndex 
96109   );
96110
96111   WHERETRACE(("best index is: %s\n", 
96112     ((pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ? "none" : 
96113          pCost->plan.u.pIdx ? pCost->plan.u.pIdx->zName : "ipk")
96114   ));
96115   
96116   bestOrClauseIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
96117   bestAutomaticIndex(pParse, pWC, pSrc, notReady, pCost);
96118   pCost->plan.wsFlags |= eqTermMask;
96119 }
96120
96121 /*
96122 ** Find the query plan for accessing table pSrc->pTab. Write the
96123 ** best query plan and its cost into the WhereCost object supplied 
96124 ** as the last parameter. This function may calculate the cost of
96125 ** both real and virtual table scans.
96126 */
96127 static void bestIndex(
96128   Parse *pParse,              /* The parsing context */
96129   WhereClause *pWC,           /* The WHERE clause */
96130   struct SrcList_item *pSrc,  /* The FROM clause term to search */
96131   Bitmask notReady,           /* Mask of cursors that are not available */
96132   ExprList *pOrderBy,         /* The ORDER BY clause */
96133   WhereCost *pCost            /* Lowest cost query plan */
96134 ){
96135 #ifndef SQLITE_OMIT_VIRTUALTABLE
96136   if( IsVirtual(pSrc->pTab) ){
96137     sqlite3_index_info *p = 0;
96138     bestVirtualIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost, &p);
96139     if( p->needToFreeIdxStr ){
96140       sqlite3_free(p->idxStr);
96141     }
96142     sqlite3DbFree(pParse->db, p);
96143   }else
96144 #endif
96145   {
96146     bestBtreeIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
96147   }
96148 }
96149
96150 /*
96151 ** Disable a term in the WHERE clause.  Except, do not disable the term
96152 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
96153 ** or USING clause of that join.
96154 **
96155 ** Consider the term t2.z='ok' in the following queries:
96156 **
96157 **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
96158 **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
96159 **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
96160 **
96161 ** The t2.z='ok' is disabled in the in (2) because it originates
96162 ** in the ON clause.  The term is disabled in (3) because it is not part
96163 ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
96164 **
96165 ** Disabling a term causes that term to not be tested in the inner loop
96166 ** of the join.  Disabling is an optimization.  When terms are satisfied
96167 ** by indices, we disable them to prevent redundant tests in the inner
96168 ** loop.  We would get the correct results if nothing were ever disabled,
96169 ** but joins might run a little slower.  The trick is to disable as much
96170 ** as we can without disabling too much.  If we disabled in (1), we'd get
96171 ** the wrong answer.  See ticket #813.
96172 */
96173 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
96174   if( pTerm
96175       && (pTerm->wtFlags & TERM_CODED)==0
96176       && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
96177   ){
96178     pTerm->wtFlags |= TERM_CODED;
96179     if( pTerm->iParent>=0 ){
96180       WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
96181       if( (--pOther->nChild)==0 ){
96182         disableTerm(pLevel, pOther);
96183       }
96184     }
96185   }
96186 }
96187
96188 /*
96189 ** Code an OP_Affinity opcode to apply the column affinity string zAff
96190 ** to the n registers starting at base. 
96191 **
96192 ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
96193 ** beginning and end of zAff are ignored.  If all entries in zAff are
96194 ** SQLITE_AFF_NONE, then no code gets generated.
96195 **
96196 ** This routine makes its own copy of zAff so that the caller is free
96197 ** to modify zAff after this routine returns.
96198 */
96199 static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
96200   Vdbe *v = pParse->pVdbe;
96201   if( zAff==0 ){
96202     assert( pParse->db->mallocFailed );
96203     return;
96204   }
96205   assert( v!=0 );
96206
96207   /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
96208   ** and end of the affinity string.
96209   */
96210   while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
96211     n--;
96212     base++;
96213     zAff++;
96214   }
96215   while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
96216     n--;
96217   }
96218
96219   /* Code the OP_Affinity opcode if there is anything left to do. */
96220   if( n>0 ){
96221     sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
96222     sqlite3VdbeChangeP4(v, -1, zAff, n);
96223     sqlite3ExprCacheAffinityChange(pParse, base, n);
96224   }
96225 }
96226
96227
96228 /*
96229 ** Generate code for a single equality term of the WHERE clause.  An equality
96230 ** term can be either X=expr or X IN (...).   pTerm is the term to be 
96231 ** coded.
96232 **
96233 ** The current value for the constraint is left in register iReg.
96234 **
96235 ** For a constraint of the form X=expr, the expression is evaluated and its
96236 ** result is left on the stack.  For constraints of the form X IN (...)
96237 ** this routine sets up a loop that will iterate over all values of X.
96238 */
96239 static int codeEqualityTerm(
96240   Parse *pParse,      /* The parsing context */
96241   WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
96242   WhereLevel *pLevel, /* When level of the FROM clause we are working on */
96243   int iTarget         /* Attempt to leave results in this register */
96244 ){
96245   Expr *pX = pTerm->pExpr;
96246   Vdbe *v = pParse->pVdbe;
96247   int iReg;                  /* Register holding results */
96248
96249   assert( iTarget>0 );
96250   if( pX->op==TK_EQ ){
96251     iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
96252   }else if( pX->op==TK_ISNULL ){
96253     iReg = iTarget;
96254     sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
96255 #ifndef SQLITE_OMIT_SUBQUERY
96256   }else{
96257     int eType;
96258     int iTab;
96259     struct InLoop *pIn;
96260
96261     assert( pX->op==TK_IN );
96262     iReg = iTarget;
96263     eType = sqlite3FindInIndex(pParse, pX, 0);
96264     iTab = pX->iTable;
96265     sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
96266     assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
96267     if( pLevel->u.in.nIn==0 ){
96268       pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
96269     }
96270     pLevel->u.in.nIn++;
96271     pLevel->u.in.aInLoop =
96272        sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
96273                               sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
96274     pIn = pLevel->u.in.aInLoop;
96275     if( pIn ){
96276       pIn += pLevel->u.in.nIn - 1;
96277       pIn->iCur = iTab;
96278       if( eType==IN_INDEX_ROWID ){
96279         pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
96280       }else{
96281         pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
96282       }
96283       sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
96284     }else{
96285       pLevel->u.in.nIn = 0;
96286     }
96287 #endif
96288   }
96289   disableTerm(pLevel, pTerm);
96290   return iReg;
96291 }
96292
96293 /*
96294 ** Generate code that will evaluate all == and IN constraints for an
96295 ** index.
96296 **
96297 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
96298 ** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
96299 ** The index has as many as three equality constraints, but in this
96300 ** example, the third "c" value is an inequality.  So only two 
96301 ** constraints are coded.  This routine will generate code to evaluate
96302 ** a==5 and b IN (1,2,3).  The current values for a and b will be stored
96303 ** in consecutive registers and the index of the first register is returned.
96304 **
96305 ** In the example above nEq==2.  But this subroutine works for any value
96306 ** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
96307 ** The only thing it does is allocate the pLevel->iMem memory cell and
96308 ** compute the affinity string.
96309 **
96310 ** This routine always allocates at least one memory cell and returns
96311 ** the index of that memory cell. The code that
96312 ** calls this routine will use that memory cell to store the termination
96313 ** key value of the loop.  If one or more IN operators appear, then
96314 ** this routine allocates an additional nEq memory cells for internal
96315 ** use.
96316 **
96317 ** Before returning, *pzAff is set to point to a buffer containing a
96318 ** copy of the column affinity string of the index allocated using
96319 ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
96320 ** with equality constraints that use NONE affinity are set to
96321 ** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
96322 **
96323 **   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
96324 **   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
96325 **
96326 ** In the example above, the index on t1(a) has TEXT affinity. But since
96327 ** the right hand side of the equality constraint (t2.b) has NONE affinity,
96328 ** no conversion should be attempted before using a t2.b value as part of
96329 ** a key to search the index. Hence the first byte in the returned affinity
96330 ** string in this example would be set to SQLITE_AFF_NONE.
96331 */
96332 static int codeAllEqualityTerms(
96333   Parse *pParse,        /* Parsing context */
96334   WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
96335   WhereClause *pWC,     /* The WHERE clause */
96336   Bitmask notReady,     /* Which parts of FROM have not yet been coded */
96337   int nExtraReg,        /* Number of extra registers to allocate */
96338   char **pzAff          /* OUT: Set to point to affinity string */
96339 ){
96340   int nEq = pLevel->plan.nEq;   /* The number of == or IN constraints to code */
96341   Vdbe *v = pParse->pVdbe;      /* The vm under construction */
96342   Index *pIdx;                  /* The index being used for this loop */
96343   int iCur = pLevel->iTabCur;   /* The cursor of the table */
96344   WhereTerm *pTerm;             /* A single constraint term */
96345   int j;                        /* Loop counter */
96346   int regBase;                  /* Base register */
96347   int nReg;                     /* Number of registers to allocate */
96348   char *zAff;                   /* Affinity string to return */
96349
96350   /* This module is only called on query plans that use an index. */
96351   assert( pLevel->plan.wsFlags & WHERE_INDEXED );
96352   pIdx = pLevel->plan.u.pIdx;
96353
96354   /* Figure out how many memory cells we will need then allocate them.
96355   */
96356   regBase = pParse->nMem + 1;
96357   nReg = pLevel->plan.nEq + nExtraReg;
96358   pParse->nMem += nReg;
96359
96360   zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
96361   if( !zAff ){
96362     pParse->db->mallocFailed = 1;
96363   }
96364
96365   /* Evaluate the equality constraints
96366   */
96367   assert( pIdx->nColumn>=nEq );
96368   for(j=0; j<nEq; j++){
96369     int r1;
96370     int k = pIdx->aiColumn[j];
96371     pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
96372     if( NEVER(pTerm==0) ) break;
96373     /* The following true for indices with redundant columns. 
96374     ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
96375     testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
96376     r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
96377     if( r1!=regBase+j ){
96378       if( nReg==1 ){
96379         sqlite3ReleaseTempReg(pParse, regBase);
96380         regBase = r1;
96381       }else{
96382         sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
96383       }
96384     }
96385     testcase( pTerm->eOperator & WO_ISNULL );
96386     testcase( pTerm->eOperator & WO_IN );
96387     if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
96388       Expr *pRight = pTerm->pExpr->pRight;
96389       sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
96390       if( zAff ){
96391         if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
96392           zAff[j] = SQLITE_AFF_NONE;
96393         }
96394         if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
96395           zAff[j] = SQLITE_AFF_NONE;
96396         }
96397       }
96398     }
96399   }
96400   *pzAff = zAff;
96401   return regBase;
96402 }
96403
96404 /*
96405 ** Generate code for the start of the iLevel-th loop in the WHERE clause
96406 ** implementation described by pWInfo.
96407 */
96408 static Bitmask codeOneLoopStart(
96409   WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
96410   int iLevel,          /* Which level of pWInfo->a[] should be coded */
96411   u16 wctrlFlags,      /* One of the WHERE_* flags defined in sqliteInt.h */
96412   Bitmask notReady     /* Which tables are currently available */
96413 ){
96414   int j, k;            /* Loop counters */
96415   int iCur;            /* The VDBE cursor for the table */
96416   int addrNxt;         /* Where to jump to continue with the next IN case */
96417   int omitTable;       /* True if we use the index only */
96418   int bRev;            /* True if we need to scan in reverse order */
96419   WhereLevel *pLevel;  /* The where level to be coded */
96420   WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
96421   WhereTerm *pTerm;               /* A WHERE clause term */
96422   Parse *pParse;                  /* Parsing context */
96423   Vdbe *v;                        /* The prepared stmt under constructions */
96424   struct SrcList_item *pTabItem;  /* FROM clause term being coded */
96425   int addrBrk;                    /* Jump here to break out of the loop */
96426   int addrCont;                   /* Jump here to continue with next cycle */
96427   int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
96428   int iReleaseReg = 0;      /* Temp register to free before returning */
96429
96430   pParse = pWInfo->pParse;
96431   v = pParse->pVdbe;
96432   pWC = pWInfo->pWC;
96433   pLevel = &pWInfo->a[iLevel];
96434   pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
96435   iCur = pTabItem->iCursor;
96436   bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
96437   omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0 
96438            && (wctrlFlags & WHERE_FORCE_TABLE)==0;
96439
96440   /* Create labels for the "break" and "continue" instructions
96441   ** for the current loop.  Jump to addrBrk to break out of a loop.
96442   ** Jump to cont to go immediately to the next iteration of the
96443   ** loop.
96444   **
96445   ** When there is an IN operator, we also have a "addrNxt" label that
96446   ** means to continue with the next IN value combination.  When
96447   ** there are no IN operators in the constraints, the "addrNxt" label
96448   ** is the same as "addrBrk".
96449   */
96450   addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
96451   addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
96452
96453   /* If this is the right table of a LEFT OUTER JOIN, allocate and
96454   ** initialize a memory cell that records if this table matches any
96455   ** row of the left table of the join.
96456   */
96457   if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
96458     pLevel->iLeftJoin = ++pParse->nMem;
96459     sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
96460     VdbeComment((v, "init LEFT JOIN no-match flag"));
96461   }
96462
96463 #ifndef SQLITE_OMIT_VIRTUALTABLE
96464   if(  (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
96465     /* Case 0:  The table is a virtual-table.  Use the VFilter and VNext
96466     **          to access the data.
96467     */
96468     int iReg;   /* P3 Value for OP_VFilter */
96469     sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
96470     int nConstraint = pVtabIdx->nConstraint;
96471     struct sqlite3_index_constraint_usage *aUsage =
96472                                                 pVtabIdx->aConstraintUsage;
96473     const struct sqlite3_index_constraint *aConstraint =
96474                                                 pVtabIdx->aConstraint;
96475
96476     sqlite3ExprCachePush(pParse);
96477     iReg = sqlite3GetTempRange(pParse, nConstraint+2);
96478     for(j=1; j<=nConstraint; j++){
96479       for(k=0; k<nConstraint; k++){
96480         if( aUsage[k].argvIndex==j ){
96481           int iTerm = aConstraint[k].iTermOffset;
96482           sqlite3ExprCode(pParse, pWC->a[iTerm].pExpr->pRight, iReg+j+1);
96483           break;
96484         }
96485       }
96486       if( k==nConstraint ) break;
96487     }
96488     sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
96489     sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
96490     sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrBrk, iReg, pVtabIdx->idxStr,
96491                       pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
96492     pVtabIdx->needToFreeIdxStr = 0;
96493     for(j=0; j<nConstraint; j++){
96494       if( aUsage[j].omit ){
96495         int iTerm = aConstraint[j].iTermOffset;
96496         disableTerm(pLevel, &pWC->a[iTerm]);
96497       }
96498     }
96499     pLevel->op = OP_VNext;
96500     pLevel->p1 = iCur;
96501     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
96502     sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
96503     sqlite3ExprCachePop(pParse, 1);
96504   }else
96505 #endif /* SQLITE_OMIT_VIRTUALTABLE */
96506
96507   if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
96508     /* Case 1:  We can directly reference a single row using an
96509     **          equality comparison against the ROWID field.  Or
96510     **          we reference multiple rows using a "rowid IN (...)"
96511     **          construct.
96512     */
96513     iReleaseReg = sqlite3GetTempReg(pParse);
96514     pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
96515     assert( pTerm!=0 );
96516     assert( pTerm->pExpr!=0 );
96517     assert( pTerm->leftCursor==iCur );
96518     assert( omitTable==0 );
96519     iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, iReleaseReg);
96520     addrNxt = pLevel->addrNxt;
96521     sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
96522     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
96523     sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
96524     VdbeComment((v, "pk"));
96525     pLevel->op = OP_Noop;
96526   }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
96527     /* Case 2:  We have an inequality comparison against the ROWID field.
96528     */
96529     int testOp = OP_Noop;
96530     int start;
96531     int memEndValue = 0;
96532     WhereTerm *pStart, *pEnd;
96533
96534     assert( omitTable==0 );
96535     pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);
96536     pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);
96537     if( bRev ){
96538       pTerm = pStart;
96539       pStart = pEnd;
96540       pEnd = pTerm;
96541     }
96542     if( pStart ){
96543       Expr *pX;             /* The expression that defines the start bound */
96544       int r1, rTemp;        /* Registers for holding the start boundary */
96545
96546       /* The following constant maps TK_xx codes into corresponding 
96547       ** seek opcodes.  It depends on a particular ordering of TK_xx
96548       */
96549       const u8 aMoveOp[] = {
96550            /* TK_GT */  OP_SeekGt,
96551            /* TK_LE */  OP_SeekLe,
96552            /* TK_LT */  OP_SeekLt,
96553            /* TK_GE */  OP_SeekGe
96554       };
96555       assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
96556       assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
96557       assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
96558
96559       pX = pStart->pExpr;
96560       assert( pX!=0 );
96561       assert( pStart->leftCursor==iCur );
96562       r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
96563       sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
96564       VdbeComment((v, "pk"));
96565       sqlite3ExprCacheAffinityChange(pParse, r1, 1);
96566       sqlite3ReleaseTempReg(pParse, rTemp);
96567       disableTerm(pLevel, pStart);
96568     }else{
96569       sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
96570     }
96571     if( pEnd ){
96572       Expr *pX;
96573       pX = pEnd->pExpr;
96574       assert( pX!=0 );
96575       assert( pEnd->leftCursor==iCur );
96576       memEndValue = ++pParse->nMem;
96577       sqlite3ExprCode(pParse, pX->pRight, memEndValue);
96578       if( pX->op==TK_LT || pX->op==TK_GT ){
96579         testOp = bRev ? OP_Le : OP_Ge;
96580       }else{
96581         testOp = bRev ? OP_Lt : OP_Gt;
96582       }
96583       disableTerm(pLevel, pEnd);
96584     }
96585     start = sqlite3VdbeCurrentAddr(v);
96586     pLevel->op = bRev ? OP_Prev : OP_Next;
96587     pLevel->p1 = iCur;
96588     pLevel->p2 = start;
96589     if( pStart==0 && pEnd==0 ){
96590       pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
96591     }else{
96592       assert( pLevel->p5==0 );
96593     }
96594     if( testOp!=OP_Noop ){
96595       iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
96596       sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
96597       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
96598       sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
96599       sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
96600     }
96601   }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
96602     /* Case 3: A scan using an index.
96603     **
96604     **         The WHERE clause may contain zero or more equality 
96605     **         terms ("==" or "IN" operators) that refer to the N
96606     **         left-most columns of the index. It may also contain
96607     **         inequality constraints (>, <, >= or <=) on the indexed
96608     **         column that immediately follows the N equalities. Only 
96609     **         the right-most column can be an inequality - the rest must
96610     **         use the "==" and "IN" operators. For example, if the 
96611     **         index is on (x,y,z), then the following clauses are all 
96612     **         optimized:
96613     **
96614     **            x=5
96615     **            x=5 AND y=10
96616     **            x=5 AND y<10
96617     **            x=5 AND y>5 AND y<10
96618     **            x=5 AND y=5 AND z<=10
96619     **
96620     **         The z<10 term of the following cannot be used, only
96621     **         the x=5 term:
96622     **
96623     **            x=5 AND z<10
96624     **
96625     **         N may be zero if there are inequality constraints.
96626     **         If there are no inequality constraints, then N is at
96627     **         least one.
96628     **
96629     **         This case is also used when there are no WHERE clause
96630     **         constraints but an index is selected anyway, in order
96631     **         to force the output order to conform to an ORDER BY.
96632     */  
96633     int aStartOp[] = {
96634       0,
96635       0,
96636       OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
96637       OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
96638       OP_SeekGt,           /* 4: (start_constraints  && !startEq && !bRev) */
96639       OP_SeekLt,           /* 5: (start_constraints  && !startEq &&  bRev) */
96640       OP_SeekGe,           /* 6: (start_constraints  &&  startEq && !bRev) */
96641       OP_SeekLe            /* 7: (start_constraints  &&  startEq &&  bRev) */
96642     };
96643     int aEndOp[] = {
96644       OP_Noop,             /* 0: (!end_constraints) */
96645       OP_IdxGE,            /* 1: (end_constraints && !bRev) */
96646       OP_IdxLT             /* 2: (end_constraints && bRev) */
96647     };
96648     int nEq = pLevel->plan.nEq;
96649     int isMinQuery = 0;          /* If this is an optimized SELECT min(x).. */
96650     int regBase;                 /* Base register holding constraint values */
96651     int r1;                      /* Temp register */
96652     WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
96653     WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
96654     int startEq;                 /* True if range start uses ==, >= or <= */
96655     int endEq;                   /* True if range end uses ==, >= or <= */
96656     int start_constraints;       /* Start of range is constrained */
96657     int nConstraint;             /* Number of constraint terms */
96658     Index *pIdx;         /* The index we will be using */
96659     int iIdxCur;         /* The VDBE cursor for the index */
96660     int nExtraReg = 0;   /* Number of extra registers needed */
96661     int op;              /* Instruction opcode */
96662     char *zStartAff;             /* Affinity for start of range constraint */
96663     char *zEndAff;               /* Affinity for end of range constraint */
96664
96665     pIdx = pLevel->plan.u.pIdx;
96666     iIdxCur = pLevel->iIdxCur;
96667     k = pIdx->aiColumn[nEq];     /* Column for inequality constraints */
96668
96669     /* If this loop satisfies a sort order (pOrderBy) request that 
96670     ** was passed to this function to implement a "SELECT min(x) ..." 
96671     ** query, then the caller will only allow the loop to run for
96672     ** a single iteration. This means that the first row returned
96673     ** should not have a NULL value stored in 'x'. If column 'x' is
96674     ** the first one after the nEq equality constraints in the index,
96675     ** this requires some special handling.
96676     */
96677     if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
96678      && (pLevel->plan.wsFlags&WHERE_ORDERBY)
96679      && (pIdx->nColumn>nEq)
96680     ){
96681       /* assert( pOrderBy->nExpr==1 ); */
96682       /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
96683       isMinQuery = 1;
96684       nExtraReg = 1;
96685     }
96686
96687     /* Find any inequality constraint terms for the start and end 
96688     ** of the range. 
96689     */
96690     if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
96691       pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
96692       nExtraReg = 1;
96693     }
96694     if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
96695       pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
96696       nExtraReg = 1;
96697     }
96698
96699     /* Generate code to evaluate all constraint terms using == or IN
96700     ** and store the values of those terms in an array of registers
96701     ** starting at regBase.
96702     */
96703     regBase = codeAllEqualityTerms(
96704         pParse, pLevel, pWC, notReady, nExtraReg, &zStartAff
96705     );
96706     zEndAff = sqlite3DbStrDup(pParse->db, zStartAff);
96707     addrNxt = pLevel->addrNxt;
96708
96709     /* If we are doing a reverse order scan on an ascending index, or
96710     ** a forward order scan on a descending index, interchange the 
96711     ** start and end terms (pRangeStart and pRangeEnd).
96712     */
96713     if( nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC) ){
96714       SWAP(WhereTerm *, pRangeEnd, pRangeStart);
96715     }
96716
96717     testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
96718     testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
96719     testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
96720     testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
96721     startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
96722     endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
96723     start_constraints = pRangeStart || nEq>0;
96724
96725     /* Seek the index cursor to the start of the range. */
96726     nConstraint = nEq;
96727     if( pRangeStart ){
96728       Expr *pRight = pRangeStart->pExpr->pRight;
96729       sqlite3ExprCode(pParse, pRight, regBase+nEq);
96730       sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
96731       if( zStartAff ){
96732         if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
96733           /* Since the comparison is to be performed with no conversions
96734           ** applied to the operands, set the affinity to apply to pRight to 
96735           ** SQLITE_AFF_NONE.  */
96736           zStartAff[nEq] = SQLITE_AFF_NONE;
96737         }
96738         if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
96739           zStartAff[nEq] = SQLITE_AFF_NONE;
96740         }
96741       }  
96742       nConstraint++;
96743     }else if( isMinQuery ){
96744       sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
96745       nConstraint++;
96746       startEq = 0;
96747       start_constraints = 1;
96748     }
96749     codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
96750     op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
96751     assert( op!=0 );
96752     testcase( op==OP_Rewind );
96753     testcase( op==OP_Last );
96754     testcase( op==OP_SeekGt );
96755     testcase( op==OP_SeekGe );
96756     testcase( op==OP_SeekLe );
96757     testcase( op==OP_SeekLt );
96758     sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
96759
96760     /* Load the value for the inequality constraint at the end of the
96761     ** range (if any).
96762     */
96763     nConstraint = nEq;
96764     if( pRangeEnd ){
96765       Expr *pRight = pRangeEnd->pExpr->pRight;
96766       sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
96767       sqlite3ExprCode(pParse, pRight, regBase+nEq);
96768       sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
96769       if( zEndAff ){
96770         if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){
96771           /* Since the comparison is to be performed with no conversions
96772           ** applied to the operands, set the affinity to apply to pRight to 
96773           ** SQLITE_AFF_NONE.  */
96774           zEndAff[nEq] = SQLITE_AFF_NONE;
96775         }
96776         if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
96777           zEndAff[nEq] = SQLITE_AFF_NONE;
96778         }
96779       }  
96780       codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
96781       nConstraint++;
96782     }
96783     sqlite3DbFree(pParse->db, zStartAff);
96784     sqlite3DbFree(pParse->db, zEndAff);
96785
96786     /* Top of the loop body */
96787     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
96788
96789     /* Check if the index cursor is past the end of the range. */
96790     op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
96791     testcase( op==OP_Noop );
96792     testcase( op==OP_IdxGE );
96793     testcase( op==OP_IdxLT );
96794     if( op!=OP_Noop ){
96795       sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
96796       sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
96797     }
96798
96799     /* If there are inequality constraints, check that the value
96800     ** of the table column that the inequality contrains is not NULL.
96801     ** If it is, jump to the next iteration of the loop.
96802     */
96803     r1 = sqlite3GetTempReg(pParse);
96804     testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
96805     testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
96806     if( pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT) ){
96807       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
96808       sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
96809     }
96810     sqlite3ReleaseTempReg(pParse, r1);
96811
96812     /* Seek the table cursor, if required */
96813     disableTerm(pLevel, pRangeStart);
96814     disableTerm(pLevel, pRangeEnd);
96815     if( !omitTable ){
96816       iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
96817       sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
96818       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
96819       sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */
96820     }
96821
96822     /* Record the instruction used to terminate the loop. Disable 
96823     ** WHERE clause terms made redundant by the index range scan.
96824     */
96825     pLevel->op = bRev ? OP_Prev : OP_Next;
96826     pLevel->p1 = iIdxCur;
96827   }else
96828
96829 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
96830   if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
96831     /* Case 4:  Two or more separately indexed terms connected by OR
96832     **
96833     ** Example:
96834     **
96835     **   CREATE TABLE t1(a,b,c,d);
96836     **   CREATE INDEX i1 ON t1(a);
96837     **   CREATE INDEX i2 ON t1(b);
96838     **   CREATE INDEX i3 ON t1(c);
96839     **
96840     **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
96841     **
96842     ** In the example, there are three indexed terms connected by OR.
96843     ** The top of the loop looks like this:
96844     **
96845     **          Null       1                # Zero the rowset in reg 1
96846     **
96847     ** Then, for each indexed term, the following. The arguments to
96848     ** RowSetTest are such that the rowid of the current row is inserted
96849     ** into the RowSet. If it is already present, control skips the
96850     ** Gosub opcode and jumps straight to the code generated by WhereEnd().
96851     **
96852     **        sqlite3WhereBegin(<term>)
96853     **          RowSetTest                  # Insert rowid into rowset
96854     **          Gosub      2 A
96855     **        sqlite3WhereEnd()
96856     **
96857     ** Following the above, code to terminate the loop. Label A, the target
96858     ** of the Gosub above, jumps to the instruction right after the Goto.
96859     **
96860     **          Null       1                # Zero the rowset in reg 1
96861     **          Goto       B                # The loop is finished.
96862     **
96863     **       A: <loop body>                 # Return data, whatever.
96864     **
96865     **          Return     2                # Jump back to the Gosub
96866     **
96867     **       B: <after the loop>
96868     **
96869     */
96870     WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
96871     WhereTerm *pFinal;     /* Final subterm within the OR-clause. */
96872     SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
96873
96874     int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
96875     int regRowset = 0;                        /* Register for RowSet object */
96876     int regRowid = 0;                         /* Register holding rowid */
96877     int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
96878     int iRetInit;                             /* Address of regReturn init */
96879     int untestedTerms = 0;             /* Some terms not completely tested */
96880     int ii;
96881    
96882     pTerm = pLevel->plan.u.pTerm;
96883     assert( pTerm!=0 );
96884     assert( pTerm->eOperator==WO_OR );
96885     assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
96886     pOrWc = &pTerm->u.pOrInfo->wc;
96887     pFinal = &pOrWc->a[pOrWc->nTerm-1];
96888     pLevel->op = OP_Return;
96889     pLevel->p1 = regReturn;
96890
96891     /* Set up a new SrcList ni pOrTab containing the table being scanned
96892     ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
96893     ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
96894     */
96895     if( pWInfo->nLevel>1 ){
96896       int nNotReady;                 /* The number of notReady tables */
96897       struct SrcList_item *origSrc;     /* Original list of tables */
96898       nNotReady = pWInfo->nLevel - iLevel - 1;
96899       pOrTab = sqlite3StackAllocRaw(pParse->db,
96900                             sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
96901       if( pOrTab==0 ) return notReady;
96902       pOrTab->nAlloc = (i16)(nNotReady + 1);
96903       pOrTab->nSrc = pOrTab->nAlloc;
96904       memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
96905       origSrc = pWInfo->pTabList->a;
96906       for(k=1; k<=nNotReady; k++){
96907         memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
96908       }
96909     }else{
96910       pOrTab = pWInfo->pTabList;
96911     }
96912
96913     /* Initialize the rowset register to contain NULL. An SQL NULL is 
96914     ** equivalent to an empty rowset.
96915     **
96916     ** Also initialize regReturn to contain the address of the instruction 
96917     ** immediately following the OP_Return at the bottom of the loop. This
96918     ** is required in a few obscure LEFT JOIN cases where control jumps
96919     ** over the top of the loop into the body of it. In this case the 
96920     ** correct response for the end-of-loop code (the OP_Return) is to 
96921     ** fall through to the next instruction, just as an OP_Next does if
96922     ** called on an uninitialized cursor.
96923     */
96924     if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
96925       regRowset = ++pParse->nMem;
96926       regRowid = ++pParse->nMem;
96927       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
96928     }
96929     iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
96930
96931     for(ii=0; ii<pOrWc->nTerm; ii++){
96932       WhereTerm *pOrTerm = &pOrWc->a[ii];
96933       if( pOrTerm->leftCursor==iCur || pOrTerm->eOperator==WO_AND ){
96934         WhereInfo *pSubWInfo;          /* Info for single OR-term scan */
96935         /* Loop through table entries that match term pOrTerm. */
96936         pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrTerm->pExpr, 0,
96937                         WHERE_OMIT_OPEN | WHERE_OMIT_CLOSE |
96938                         WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY);
96939         if( pSubWInfo ){
96940           if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
96941             int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
96942             int r;
96943             r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur, 
96944                                          regRowid);
96945             sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
96946                                  sqlite3VdbeCurrentAddr(v)+2, r, iSet);
96947           }
96948           sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
96949
96950           /* The pSubWInfo->untestedTerms flag means that this OR term
96951           ** contained one or more AND term from a notReady table.  The
96952           ** terms from the notReady table could not be tested and will
96953           ** need to be tested later.
96954           */
96955           if( pSubWInfo->untestedTerms ) untestedTerms = 1;
96956
96957           /* Finish the loop through table entries that match term pOrTerm. */
96958           sqlite3WhereEnd(pSubWInfo);
96959         }
96960       }
96961     }
96962     sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
96963     sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
96964     sqlite3VdbeResolveLabel(v, iLoopBody);
96965
96966     if( pWInfo->nLevel>1 ) sqlite3StackFree(pParse->db, pOrTab);
96967     if( !untestedTerms ) disableTerm(pLevel, pTerm);
96968   }else
96969 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
96970
96971   {
96972     /* Case 5:  There is no usable index.  We must do a complete
96973     **          scan of the entire table.
96974     */
96975     static const u8 aStep[] = { OP_Next, OP_Prev };
96976     static const u8 aStart[] = { OP_Rewind, OP_Last };
96977     assert( bRev==0 || bRev==1 );
96978     assert( omitTable==0 );
96979     pLevel->op = aStep[bRev];
96980     pLevel->p1 = iCur;
96981     pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
96982     pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
96983   }
96984   notReady &= ~getMask(pWC->pMaskSet, iCur);
96985
96986   /* Insert code to test every subexpression that can be completely
96987   ** computed using the current set of tables.
96988   */
96989   k = 0;
96990   for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
96991     Expr *pE;
96992     testcase( pTerm->wtFlags & TERM_VIRTUAL );
96993     testcase( pTerm->wtFlags & TERM_CODED );
96994     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
96995     if( (pTerm->prereqAll & notReady)!=0 ){
96996       testcase( pWInfo->untestedTerms==0
96997                && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
96998       pWInfo->untestedTerms = 1;
96999       continue;
97000     }
97001     pE = pTerm->pExpr;
97002     assert( pE!=0 );
97003     if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
97004       continue;
97005     }
97006     sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
97007     k = 1;
97008     pTerm->wtFlags |= TERM_CODED;
97009   }
97010
97011   /* For a LEFT OUTER JOIN, generate code that will record the fact that
97012   ** at least one row of the right table has matched the left table.  
97013   */
97014   if( pLevel->iLeftJoin ){
97015     pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
97016     sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
97017     VdbeComment((v, "record LEFT JOIN hit"));
97018     sqlite3ExprCacheClear(pParse);
97019     for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
97020       testcase( pTerm->wtFlags & TERM_VIRTUAL );
97021       testcase( pTerm->wtFlags & TERM_CODED );
97022       if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
97023       if( (pTerm->prereqAll & notReady)!=0 ){
97024         assert( pWInfo->untestedTerms );
97025         continue;
97026       }
97027       assert( pTerm->pExpr );
97028       sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
97029       pTerm->wtFlags |= TERM_CODED;
97030     }
97031   }
97032   sqlite3ReleaseTempReg(pParse, iReleaseReg);
97033
97034   return notReady;
97035 }
97036
97037 #if defined(SQLITE_TEST)
97038 /*
97039 ** The following variable holds a text description of query plan generated
97040 ** by the most recent call to sqlite3WhereBegin().  Each call to WhereBegin
97041 ** overwrites the previous.  This information is used for testing and
97042 ** analysis only.
97043 */
97044 SQLITE_API char sqlite3_query_plan[BMS*2*40];  /* Text of the join */
97045 static int nQPlan = 0;              /* Next free slow in _query_plan[] */
97046
97047 #endif /* SQLITE_TEST */
97048
97049
97050 /*
97051 ** Free a WhereInfo structure
97052 */
97053 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
97054   if( ALWAYS(pWInfo) ){
97055     int i;
97056     for(i=0; i<pWInfo->nLevel; i++){
97057       sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
97058       if( pInfo ){
97059         /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
97060         if( pInfo->needToFreeIdxStr ){
97061           sqlite3_free(pInfo->idxStr);
97062         }
97063         sqlite3DbFree(db, pInfo);
97064       }
97065       if( pWInfo->a[i].plan.wsFlags & WHERE_TEMP_INDEX ){
97066         Index *pIdx = pWInfo->a[i].plan.u.pIdx;
97067         if( pIdx ){
97068           sqlite3DbFree(db, pIdx->zColAff);
97069           sqlite3DbFree(db, pIdx);
97070         }
97071       }
97072     }
97073     whereClauseClear(pWInfo->pWC);
97074     sqlite3DbFree(db, pWInfo);
97075   }
97076 }
97077
97078
97079 /*
97080 ** Generate the beginning of the loop used for WHERE clause processing.
97081 ** The return value is a pointer to an opaque structure that contains
97082 ** information needed to terminate the loop.  Later, the calling routine
97083 ** should invoke sqlite3WhereEnd() with the return value of this function
97084 ** in order to complete the WHERE clause processing.
97085 **
97086 ** If an error occurs, this routine returns NULL.
97087 **
97088 ** The basic idea is to do a nested loop, one loop for each table in
97089 ** the FROM clause of a select.  (INSERT and UPDATE statements are the
97090 ** same as a SELECT with only a single table in the FROM clause.)  For
97091 ** example, if the SQL is this:
97092 **
97093 **       SELECT * FROM t1, t2, t3 WHERE ...;
97094 **
97095 ** Then the code generated is conceptually like the following:
97096 **
97097 **      foreach row1 in t1 do       \    Code generated
97098 **        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
97099 **          foreach row3 in t3 do   /
97100 **            ...
97101 **          end                     \    Code generated
97102 **        end                        |-- by sqlite3WhereEnd()
97103 **      end                         /
97104 **
97105 ** Note that the loops might not be nested in the order in which they
97106 ** appear in the FROM clause if a different order is better able to make
97107 ** use of indices.  Note also that when the IN operator appears in
97108 ** the WHERE clause, it might result in additional nested loops for
97109 ** scanning through all values on the right-hand side of the IN.
97110 **
97111 ** There are Btree cursors associated with each table.  t1 uses cursor
97112 ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
97113 ** And so forth.  This routine generates code to open those VDBE cursors
97114 ** and sqlite3WhereEnd() generates the code to close them.
97115 **
97116 ** The code that sqlite3WhereBegin() generates leaves the cursors named
97117 ** in pTabList pointing at their appropriate entries.  The [...] code
97118 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
97119 ** data from the various tables of the loop.
97120 **
97121 ** If the WHERE clause is empty, the foreach loops must each scan their
97122 ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
97123 ** the tables have indices and there are terms in the WHERE clause that
97124 ** refer to those indices, a complete table scan can be avoided and the
97125 ** code will run much faster.  Most of the work of this routine is checking
97126 ** to see if there are indices that can be used to speed up the loop.
97127 **
97128 ** Terms of the WHERE clause are also used to limit which rows actually
97129 ** make it to the "..." in the middle of the loop.  After each "foreach",
97130 ** terms of the WHERE clause that use only terms in that loop and outer
97131 ** loops are evaluated and if false a jump is made around all subsequent
97132 ** inner loops (or around the "..." if the test occurs within the inner-
97133 ** most loop)
97134 **
97135 ** OUTER JOINS
97136 **
97137 ** An outer join of tables t1 and t2 is conceptally coded as follows:
97138 **
97139 **    foreach row1 in t1 do
97140 **      flag = 0
97141 **      foreach row2 in t2 do
97142 **        start:
97143 **          ...
97144 **          flag = 1
97145 **      end
97146 **      if flag==0 then
97147 **        move the row2 cursor to a null row
97148 **        goto start
97149 **      fi
97150 **    end
97151 **
97152 ** ORDER BY CLAUSE PROCESSING
97153 **
97154 ** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
97155 ** if there is one.  If there is no ORDER BY clause or if this routine
97156 ** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
97157 **
97158 ** If an index can be used so that the natural output order of the table
97159 ** scan is correct for the ORDER BY clause, then that index is used and
97160 ** *ppOrderBy is set to NULL.  This is an optimization that prevents an
97161 ** unnecessary sort of the result set if an index appropriate for the
97162 ** ORDER BY clause already exists.
97163 **
97164 ** If the where clause loops cannot be arranged to provide the correct
97165 ** output order, then the *ppOrderBy is unchanged.
97166 */
97167 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
97168   Parse *pParse,        /* The parser context */
97169   SrcList *pTabList,    /* A list of all tables to be scanned */
97170   Expr *pWhere,         /* The WHERE clause */
97171   ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
97172   u16 wctrlFlags        /* One of the WHERE_* flags defined in sqliteInt.h */
97173 ){
97174   int i;                     /* Loop counter */
97175   int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
97176   int nTabList;              /* Number of elements in pTabList */
97177   WhereInfo *pWInfo;         /* Will become the return value of this function */
97178   Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
97179   Bitmask notReady;          /* Cursors that are not yet positioned */
97180   WhereMaskSet *pMaskSet;    /* The expression mask set */
97181   WhereClause *pWC;               /* Decomposition of the WHERE clause */
97182   struct SrcList_item *pTabItem;  /* A single entry from pTabList */
97183   WhereLevel *pLevel;             /* A single level in the pWInfo list */
97184   int iFrom;                      /* First unused FROM clause element */
97185   int andFlags;              /* AND-ed combination of all pWC->a[].wtFlags */
97186   sqlite3 *db;               /* Database connection */
97187
97188   /* The number of tables in the FROM clause is limited by the number of
97189   ** bits in a Bitmask 
97190   */
97191   testcase( pTabList->nSrc==BMS );
97192   if( pTabList->nSrc>BMS ){
97193     sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
97194     return 0;
97195   }
97196
97197   /* This function normally generates a nested loop for all tables in 
97198   ** pTabList.  But if the WHERE_ONETABLE_ONLY flag is set, then we should
97199   ** only generate code for the first table in pTabList and assume that
97200   ** any cursors associated with subsequent tables are uninitialized.
97201   */
97202   nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
97203
97204   /* Allocate and initialize the WhereInfo structure that will become the
97205   ** return value. A single allocation is used to store the WhereInfo
97206   ** struct, the contents of WhereInfo.a[], the WhereClause structure
97207   ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
97208   ** field (type Bitmask) it must be aligned on an 8-byte boundary on
97209   ** some architectures. Hence the ROUND8() below.
97210   */
97211   db = pParse->db;
97212   nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
97213   pWInfo = sqlite3DbMallocZero(db, 
97214       nByteWInfo + 
97215       sizeof(WhereClause) +
97216       sizeof(WhereMaskSet)
97217   );
97218   if( db->mallocFailed ){
97219     sqlite3DbFree(db, pWInfo);
97220     pWInfo = 0;
97221     goto whereBeginError;
97222   }
97223   pWInfo->nLevel = nTabList;
97224   pWInfo->pParse = pParse;
97225   pWInfo->pTabList = pTabList;
97226   pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
97227   pWInfo->pWC = pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
97228   pWInfo->wctrlFlags = wctrlFlags;
97229   pWInfo->savedNQueryLoop = pParse->nQueryLoop;
97230   pMaskSet = (WhereMaskSet*)&pWC[1];
97231
97232   /* Split the WHERE clause into separate subexpressions where each
97233   ** subexpression is separated by an AND operator.
97234   */
97235   initMaskSet(pMaskSet);
97236   whereClauseInit(pWC, pParse, pMaskSet);
97237   sqlite3ExprCodeConstants(pParse, pWhere);
97238   whereSplit(pWC, pWhere, TK_AND);
97239     
97240   /* Special case: a WHERE clause that is constant.  Evaluate the
97241   ** expression and either jump over all of the code or fall thru.
97242   */
97243   if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
97244     sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
97245     pWhere = 0;
97246   }
97247
97248   /* Assign a bit from the bitmask to every term in the FROM clause.
97249   **
97250   ** When assigning bitmask values to FROM clause cursors, it must be
97251   ** the case that if X is the bitmask for the N-th FROM clause term then
97252   ** the bitmask for all FROM clause terms to the left of the N-th term
97253   ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
97254   ** its Expr.iRightJoinTable value to find the bitmask of the right table
97255   ** of the join.  Subtracting one from the right table bitmask gives a
97256   ** bitmask for all tables to the left of the join.  Knowing the bitmask
97257   ** for all tables to the left of a left join is important.  Ticket #3015.
97258   **
97259   ** Configure the WhereClause.vmask variable so that bits that correspond
97260   ** to virtual table cursors are set. This is used to selectively disable 
97261   ** the OR-to-IN transformation in exprAnalyzeOrTerm(). It is not helpful 
97262   ** with virtual tables.
97263   **
97264   ** Note that bitmasks are created for all pTabList->nSrc tables in
97265   ** pTabList, not just the first nTabList tables.  nTabList is normally
97266   ** equal to pTabList->nSrc but might be shortened to 1 if the
97267   ** WHERE_ONETABLE_ONLY flag is set.
97268   */
97269   assert( pWC->vmask==0 && pMaskSet->n==0 );
97270   for(i=0; i<pTabList->nSrc; i++){
97271     createMask(pMaskSet, pTabList->a[i].iCursor);
97272 #ifndef SQLITE_OMIT_VIRTUALTABLE
97273     if( ALWAYS(pTabList->a[i].pTab) && IsVirtual(pTabList->a[i].pTab) ){
97274       pWC->vmask |= ((Bitmask)1 << i);
97275     }
97276 #endif
97277   }
97278 #ifndef NDEBUG
97279   {
97280     Bitmask toTheLeft = 0;
97281     for(i=0; i<pTabList->nSrc; i++){
97282       Bitmask m = getMask(pMaskSet, pTabList->a[i].iCursor);
97283       assert( (m-1)==toTheLeft );
97284       toTheLeft |= m;
97285     }
97286   }
97287 #endif
97288
97289   /* Analyze all of the subexpressions.  Note that exprAnalyze() might
97290   ** add new virtual terms onto the end of the WHERE clause.  We do not
97291   ** want to analyze these virtual terms, so start analyzing at the end
97292   ** and work forward so that the added virtual terms are never processed.
97293   */
97294   exprAnalyzeAll(pTabList, pWC);
97295   if( db->mallocFailed ){
97296     goto whereBeginError;
97297   }
97298
97299   /* Chose the best index to use for each table in the FROM clause.
97300   **
97301   ** This loop fills in the following fields:
97302   **
97303   **   pWInfo->a[].pIdx      The index to use for this level of the loop.
97304   **   pWInfo->a[].wsFlags   WHERE_xxx flags associated with pIdx
97305   **   pWInfo->a[].nEq       The number of == and IN constraints
97306   **   pWInfo->a[].iFrom     Which term of the FROM clause is being coded
97307   **   pWInfo->a[].iTabCur   The VDBE cursor for the database table
97308   **   pWInfo->a[].iIdxCur   The VDBE cursor for the index
97309   **   pWInfo->a[].pTerm     When wsFlags==WO_OR, the OR-clause term
97310   **
97311   ** This loop also figures out the nesting order of tables in the FROM
97312   ** clause.
97313   */
97314   notReady = ~(Bitmask)0;
97315   pTabItem = pTabList->a;
97316   pLevel = pWInfo->a;
97317   andFlags = ~0;
97318   WHERETRACE(("*** Optimizer Start ***\n"));
97319   for(i=iFrom=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
97320     WhereCost bestPlan;         /* Most efficient plan seen so far */
97321     Index *pIdx;                /* Index for FROM table at pTabItem */
97322     int j;                      /* For looping over FROM tables */
97323     int bestJ = -1;             /* The value of j */
97324     Bitmask m;                  /* Bitmask value for j or bestJ */
97325     int isOptimal;              /* Iterator for optimal/non-optimal search */
97326
97327     memset(&bestPlan, 0, sizeof(bestPlan));
97328     bestPlan.rCost = SQLITE_BIG_DBL;
97329
97330     /* Loop through the remaining entries in the FROM clause to find the
97331     ** next nested loop. The loop tests all FROM clause entries
97332     ** either once or twice. 
97333     **
97334     ** The first test is always performed if there are two or more entries
97335     ** remaining and never performed if there is only one FROM clause entry
97336     ** to choose from.  The first test looks for an "optimal" scan.  In
97337     ** this context an optimal scan is one that uses the same strategy
97338     ** for the given FROM clause entry as would be selected if the entry
97339     ** were used as the innermost nested loop.  In other words, a table
97340     ** is chosen such that the cost of running that table cannot be reduced
97341     ** by waiting for other tables to run first.  This "optimal" test works
97342     ** by first assuming that the FROM clause is on the inner loop and finding
97343     ** its query plan, then checking to see if that query plan uses any
97344     ** other FROM clause terms that are notReady.  If no notReady terms are
97345     ** used then the "optimal" query plan works.
97346     **
97347     ** The second loop iteration is only performed if no optimal scan
97348     ** strategies were found by the first loop. This 2nd iteration is used to
97349     ** search for the lowest cost scan overall.
97350     **
97351     ** Previous versions of SQLite performed only the second iteration -
97352     ** the next outermost loop was always that with the lowest overall
97353     ** cost. However, this meant that SQLite could select the wrong plan
97354     ** for scripts such as the following:
97355     **   
97356     **   CREATE TABLE t1(a, b); 
97357     **   CREATE TABLE t2(c, d);
97358     **   SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
97359     **
97360     ** The best strategy is to iterate through table t1 first. However it
97361     ** is not possible to determine this with a simple greedy algorithm.
97362     ** However, since the cost of a linear scan through table t2 is the same 
97363     ** as the cost of a linear scan through table t1, a simple greedy 
97364     ** algorithm may choose to use t2 for the outer loop, which is a much
97365     ** costlier approach.
97366     */
97367     for(isOptimal=(iFrom<nTabList-1); isOptimal>=0; isOptimal--){
97368       Bitmask mask;  /* Mask of tables not yet ready */
97369       for(j=iFrom, pTabItem=&pTabList->a[j]; j<nTabList; j++, pTabItem++){
97370         int doNotReorder;    /* True if this table should not be reordered */
97371         WhereCost sCost;     /* Cost information from best[Virtual]Index() */
97372         ExprList *pOrderBy;  /* ORDER BY clause for index to optimize */
97373   
97374         doNotReorder =  (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
97375         if( j!=iFrom && doNotReorder ) break;
97376         m = getMask(pMaskSet, pTabItem->iCursor);
97377         if( (m & notReady)==0 ){
97378           if( j==iFrom ) iFrom++;
97379           continue;
97380         }
97381         mask = (isOptimal ? m : notReady);
97382         pOrderBy = ((i==0 && ppOrderBy )?*ppOrderBy:0);
97383   
97384         assert( pTabItem->pTab );
97385 #ifndef SQLITE_OMIT_VIRTUALTABLE
97386         if( IsVirtual(pTabItem->pTab) ){
97387           sqlite3_index_info **pp = &pWInfo->a[j].pIdxInfo;
97388           bestVirtualIndex(pParse, pWC, pTabItem, mask, pOrderBy, &sCost, pp);
97389         }else 
97390 #endif
97391         {
97392           bestBtreeIndex(pParse, pWC, pTabItem, mask, pOrderBy, &sCost);
97393         }
97394         assert( isOptimal || (sCost.used&notReady)==0 );
97395
97396         if( (sCost.used&notReady)==0
97397          && (bestJ<0 || sCost.rCost<bestPlan.rCost
97398              || (sCost.rCost<=bestPlan.rCost && sCost.nRow<bestPlan.nRow))
97399         ){
97400           WHERETRACE(("... best so far with cost=%g and nRow=%g\n",
97401                       sCost.rCost, sCost.nRow));
97402           bestPlan = sCost;
97403           bestJ = j;
97404         }
97405         if( doNotReorder ) break;
97406       }
97407     }
97408     assert( bestJ>=0 );
97409     assert( notReady & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
97410     WHERETRACE(("*** Optimizer selects table %d for loop %d\n", bestJ,
97411            pLevel-pWInfo->a));
97412     if( (bestPlan.plan.wsFlags & WHERE_ORDERBY)!=0 ){
97413       *ppOrderBy = 0;
97414     }
97415     andFlags &= bestPlan.plan.wsFlags;
97416     pLevel->plan = bestPlan.plan;
97417     testcase( bestPlan.plan.wsFlags & WHERE_INDEXED );
97418     testcase( bestPlan.plan.wsFlags & WHERE_TEMP_INDEX );
97419     if( bestPlan.plan.wsFlags & (WHERE_INDEXED|WHERE_TEMP_INDEX) ){
97420       pLevel->iIdxCur = pParse->nTab++;
97421     }else{
97422       pLevel->iIdxCur = -1;
97423     }
97424     notReady &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
97425     pLevel->iFrom = (u8)bestJ;
97426     if( bestPlan.nRow>=(double)1 ) pParse->nQueryLoop *= bestPlan.nRow;
97427
97428     /* Check that if the table scanned by this loop iteration had an
97429     ** INDEXED BY clause attached to it, that the named index is being
97430     ** used for the scan. If not, then query compilation has failed.
97431     ** Return an error.
97432     */
97433     pIdx = pTabList->a[bestJ].pIndex;
97434     if( pIdx ){
97435       if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){
97436         sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
97437         goto whereBeginError;
97438       }else{
97439         /* If an INDEXED BY clause is used, the bestIndex() function is
97440         ** guaranteed to find the index specified in the INDEXED BY clause
97441         ** if it find an index at all. */
97442         assert( bestPlan.plan.u.pIdx==pIdx );
97443       }
97444     }
97445   }
97446   WHERETRACE(("*** Optimizer Finished ***\n"));
97447   if( pParse->nErr || db->mallocFailed ){
97448     goto whereBeginError;
97449   }
97450
97451   /* If the total query only selects a single row, then the ORDER BY
97452   ** clause is irrelevant.
97453   */
97454   if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
97455     *ppOrderBy = 0;
97456   }
97457
97458   /* If the caller is an UPDATE or DELETE statement that is requesting
97459   ** to use a one-pass algorithm, determine if this is appropriate.
97460   ** The one-pass algorithm only works if the WHERE clause constraints
97461   ** the statement to update a single row.
97462   */
97463   assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
97464   if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
97465     pWInfo->okOnePass = 1;
97466     pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
97467   }
97468
97469   /* Open all tables in the pTabList and any indices selected for
97470   ** searching those tables.
97471   */
97472   sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
97473   notReady = ~(Bitmask)0;
97474   for(i=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
97475     Table *pTab;     /* Table to open */
97476     int iDb;         /* Index of database containing table/index */
97477
97478 #ifndef SQLITE_OMIT_EXPLAIN
97479     if( pParse->explain==2 ){
97480       char *zMsg;
97481       struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
97482       zMsg = sqlite3MPrintf(db, "TABLE %s", pItem->zName);
97483       if( pItem->zAlias ){
97484         zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
97485       }
97486       if( (pLevel->plan.wsFlags & WHERE_TEMP_INDEX)!=0 ){
97487         zMsg = sqlite3MAppendf(db, zMsg, "%s WITH AUTOMATIC INDEX", zMsg);
97488       }else if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
97489         zMsg = sqlite3MAppendf(db, zMsg, "%s WITH INDEX %s",
97490            zMsg, pLevel->plan.u.pIdx->zName);
97491       }else if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
97492         zMsg = sqlite3MAppendf(db, zMsg, "%s VIA MULTI-INDEX UNION", zMsg);
97493       }else if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
97494         zMsg = sqlite3MAppendf(db, zMsg, "%s USING PRIMARY KEY", zMsg);
97495       }
97496 #ifndef SQLITE_OMIT_VIRTUALTABLE
97497       else if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
97498         sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
97499         zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
97500                     pVtabIdx->idxNum, pVtabIdx->idxStr);
97501       }
97502 #endif
97503       if( pLevel->plan.wsFlags & WHERE_ORDERBY ){
97504         zMsg = sqlite3MAppendf(db, zMsg, "%s ORDER BY", zMsg);
97505       }
97506       sqlite3VdbeAddOp4(v, OP_Explain, i, pLevel->iFrom, 0, zMsg, P4_DYNAMIC);
97507     }
97508 #endif /* SQLITE_OMIT_EXPLAIN */
97509     pTabItem = &pTabList->a[pLevel->iFrom];
97510     pTab = pTabItem->pTab;
97511     pLevel->iTabCur = pTabItem->iCursor;
97512     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
97513     if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
97514       /* Do nothing */
97515     }else
97516 #ifndef SQLITE_OMIT_VIRTUALTABLE
97517     if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
97518       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
97519       int iCur = pTabItem->iCursor;
97520       sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
97521     }else
97522 #endif
97523     if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
97524          && (wctrlFlags & WHERE_OMIT_OPEN)==0 ){
97525       int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
97526       sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
97527       testcase( pTab->nCol==BMS-1 );
97528       testcase( pTab->nCol==BMS );
97529       if( !pWInfo->okOnePass && pTab->nCol<BMS ){
97530         Bitmask b = pTabItem->colUsed;
97531         int n = 0;
97532         for(; b; b=b>>1, n++){}
97533         sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1, 
97534                             SQLITE_INT_TO_PTR(n), P4_INT32);
97535         assert( n<=pTab->nCol );
97536       }
97537     }else{
97538       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
97539     }
97540 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
97541     if( (pLevel->plan.wsFlags & WHERE_TEMP_INDEX)!=0 ){
97542       constructAutomaticIndex(pParse, pWC, pTabItem, notReady, pLevel);
97543     }else
97544 #endif
97545     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
97546       Index *pIx = pLevel->plan.u.pIdx;
97547       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
97548       int iIdxCur = pLevel->iIdxCur;
97549       assert( pIx->pSchema==pTab->pSchema );
97550       assert( iIdxCur>=0 );
97551       sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIx->tnum, iDb,
97552                         (char*)pKey, P4_KEYINFO_HANDOFF);
97553       VdbeComment((v, "%s", pIx->zName));
97554     }
97555     sqlite3CodeVerifySchema(pParse, iDb);
97556     notReady &= ~getMask(pWC->pMaskSet, pTabItem->iCursor);
97557   }
97558   pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
97559   if( db->mallocFailed ) goto whereBeginError;
97560
97561   /* Generate the code to do the search.  Each iteration of the for
97562   ** loop below generates code for a single nested loop of the VM
97563   ** program.
97564   */
97565   notReady = ~(Bitmask)0;
97566   for(i=0; i<nTabList; i++){
97567     notReady = codeOneLoopStart(pWInfo, i, wctrlFlags, notReady);
97568     pWInfo->iContinue = pWInfo->a[i].addrCont;
97569   }
97570
97571 #ifdef SQLITE_TEST  /* For testing and debugging use only */
97572   /* Record in the query plan information about the current table
97573   ** and the index used to access it (if any).  If the table itself
97574   ** is not used, its name is just '{}'.  If no index is used
97575   ** the index is listed as "{}".  If the primary key is used the
97576   ** index name is '*'.
97577   */
97578   for(i=0; i<nTabList; i++){
97579     char *z;
97580     int n;
97581     pLevel = &pWInfo->a[i];
97582     pTabItem = &pTabList->a[pLevel->iFrom];
97583     z = pTabItem->zAlias;
97584     if( z==0 ) z = pTabItem->pTab->zName;
97585     n = sqlite3Strlen30(z);
97586     if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
97587       if( pLevel->plan.wsFlags & WHERE_IDX_ONLY ){
97588         memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
97589         nQPlan += 2;
97590       }else{
97591         memcpy(&sqlite3_query_plan[nQPlan], z, n);
97592         nQPlan += n;
97593       }
97594       sqlite3_query_plan[nQPlan++] = ' ';
97595     }
97596     testcase( pLevel->plan.wsFlags & WHERE_ROWID_EQ );
97597     testcase( pLevel->plan.wsFlags & WHERE_ROWID_RANGE );
97598     if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
97599       memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
97600       nQPlan += 2;
97601     }else if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
97602       n = sqlite3Strlen30(pLevel->plan.u.pIdx->zName);
97603       if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
97604         memcpy(&sqlite3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);
97605         nQPlan += n;
97606         sqlite3_query_plan[nQPlan++] = ' ';
97607       }
97608     }else{
97609       memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
97610       nQPlan += 3;
97611     }
97612   }
97613   while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
97614     sqlite3_query_plan[--nQPlan] = 0;
97615   }
97616   sqlite3_query_plan[nQPlan] = 0;
97617   nQPlan = 0;
97618 #endif /* SQLITE_TEST // Testing and debugging use only */
97619
97620   /* Record the continuation address in the WhereInfo structure.  Then
97621   ** clean up and return.
97622   */
97623   return pWInfo;
97624
97625   /* Jump here if malloc fails */
97626 whereBeginError:
97627   if( pWInfo ){
97628     pParse->nQueryLoop = pWInfo->savedNQueryLoop;
97629     whereInfoFree(db, pWInfo);
97630   }
97631   return 0;
97632 }
97633
97634 /*
97635 ** Generate the end of the WHERE loop.  See comments on 
97636 ** sqlite3WhereBegin() for additional information.
97637 */
97638 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
97639   Parse *pParse = pWInfo->pParse;
97640   Vdbe *v = pParse->pVdbe;
97641   int i;
97642   WhereLevel *pLevel;
97643   SrcList *pTabList = pWInfo->pTabList;
97644   sqlite3 *db = pParse->db;
97645
97646   /* Generate loop termination code.
97647   */
97648   sqlite3ExprCacheClear(pParse);
97649   for(i=pWInfo->nLevel-1; i>=0; i--){
97650     pLevel = &pWInfo->a[i];
97651     sqlite3VdbeResolveLabel(v, pLevel->addrCont);
97652     if( pLevel->op!=OP_Noop ){
97653       sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
97654       sqlite3VdbeChangeP5(v, pLevel->p5);
97655     }
97656     if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
97657       struct InLoop *pIn;
97658       int j;
97659       sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
97660       for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
97661         sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
97662         sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->addrInTop);
97663         sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
97664       }
97665       sqlite3DbFree(db, pLevel->u.in.aInLoop);
97666     }
97667     sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
97668     if( pLevel->iLeftJoin ){
97669       int addr;
97670       addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
97671       assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
97672            || (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 );
97673       if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
97674         sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
97675       }
97676       if( pLevel->iIdxCur>=0 ){
97677         sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
97678       }
97679       if( pLevel->op==OP_Return ){
97680         sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
97681       }else{
97682         sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
97683       }
97684       sqlite3VdbeJumpHere(v, addr);
97685     }
97686   }
97687
97688   /* The "break" point is here, just past the end of the outer loop.
97689   ** Set it.
97690   */
97691   sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
97692
97693   /* Close all of the cursors that were opened by sqlite3WhereBegin.
97694   */
97695   assert( pWInfo->nLevel==1 || pWInfo->nLevel==pTabList->nSrc );
97696   for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
97697     struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
97698     Table *pTab = pTabItem->pTab;
97699     assert( pTab!=0 );
97700     if( (pTab->tabFlags & TF_Ephemeral)==0
97701      && pTab->pSelect==0
97702      && (pWInfo->wctrlFlags & WHERE_OMIT_CLOSE)==0
97703     ){
97704       int ws = pLevel->plan.wsFlags;
97705       if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
97706         sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
97707       }
97708       if( (ws & WHERE_INDEXED)!=0 && (ws & WHERE_TEMP_INDEX)==0 ){
97709         sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
97710       }
97711     }
97712
97713     /* If this scan uses an index, make code substitutions to read data
97714     ** from the index in preference to the table. Sometimes, this means
97715     ** the table need never be read from. This is a performance boost,
97716     ** as the vdbe level waits until the table is read before actually
97717     ** seeking the table cursor to the record corresponding to the current
97718     ** position in the index.
97719     ** 
97720     ** Calls to the code generator in between sqlite3WhereBegin and
97721     ** sqlite3WhereEnd will have created code that references the table
97722     ** directly.  This loop scans all that code looking for opcodes
97723     ** that reference the table and converts them into opcodes that
97724     ** reference the index.
97725     */
97726     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 && !db->mallocFailed){
97727       int k, j, last;
97728       VdbeOp *pOp;
97729       Index *pIdx = pLevel->plan.u.pIdx;
97730
97731       assert( pIdx!=0 );
97732       pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
97733       last = sqlite3VdbeCurrentAddr(v);
97734       for(k=pWInfo->iTop; k<last; k++, pOp++){
97735         if( pOp->p1!=pLevel->iTabCur ) continue;
97736         if( pOp->opcode==OP_Column ){
97737           for(j=0; j<pIdx->nColumn; j++){
97738             if( pOp->p2==pIdx->aiColumn[j] ){
97739               pOp->p2 = j;
97740               pOp->p1 = pLevel->iIdxCur;
97741               break;
97742             }
97743           }
97744           assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
97745                || j<pIdx->nColumn );
97746         }else if( pOp->opcode==OP_Rowid ){
97747           pOp->p1 = pLevel->iIdxCur;
97748           pOp->opcode = OP_IdxRowid;
97749         }
97750       }
97751     }
97752   }
97753
97754   /* Final cleanup
97755   */
97756   pParse->nQueryLoop = pWInfo->savedNQueryLoop;
97757   whereInfoFree(db, pWInfo);
97758   return;
97759 }
97760
97761 /************** End of where.c ***********************************************/
97762 /************** Begin file parse.c *******************************************/
97763 /* Driver template for the LEMON parser generator.
97764 ** The author disclaims copyright to this source code.
97765 **
97766 ** This version of "lempar.c" is modified, slightly, for use by SQLite.
97767 ** The only modifications are the addition of a couple of NEVER()
97768 ** macros to disable tests that are needed in the case of a general
97769 ** LALR(1) grammar but which are always false in the
97770 ** specific grammar used by SQLite.
97771 */
97772 /* First off, code is included that follows the "include" declaration
97773 ** in the input grammar file. */
97774
97775
97776 /*
97777 ** Disable all error recovery processing in the parser push-down
97778 ** automaton.
97779 */
97780 #define YYNOERRORRECOVERY 1
97781
97782 /*
97783 ** Make yytestcase() the same as testcase()
97784 */
97785 #define yytestcase(X) testcase(X)
97786
97787 /*
97788 ** An instance of this structure holds information about the
97789 ** LIMIT clause of a SELECT statement.
97790 */
97791 struct LimitVal {
97792   Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
97793   Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
97794 };
97795
97796 /*
97797 ** An instance of this structure is used to store the LIKE,
97798 ** GLOB, NOT LIKE, and NOT GLOB operators.
97799 */
97800 struct LikeOp {
97801   Token eOperator;  /* "like" or "glob" or "regexp" */
97802   int not;         /* True if the NOT keyword is present */
97803 };
97804
97805 /*
97806 ** An instance of the following structure describes the event of a
97807 ** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
97808 ** TK_DELETE, or TK_INSTEAD.  If the event is of the form
97809 **
97810 **      UPDATE ON (a,b,c)
97811 **
97812 ** Then the "b" IdList records the list "a,b,c".
97813 */
97814 struct TrigEvent { int a; IdList * b; };
97815
97816 /*
97817 ** An instance of this structure holds the ATTACH key and the key type.
97818 */
97819 struct AttachKey { int type;  Token key; };
97820
97821
97822   /* This is a utility routine used to set the ExprSpan.zStart and
97823   ** ExprSpan.zEnd values of pOut so that the span covers the complete
97824   ** range of text beginning with pStart and going to the end of pEnd.
97825   */
97826   static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
97827     pOut->zStart = pStart->z;
97828     pOut->zEnd = &pEnd->z[pEnd->n];
97829   }
97830
97831   /* Construct a new Expr object from a single identifier.  Use the
97832   ** new Expr to populate pOut.  Set the span of pOut to be the identifier
97833   ** that created the expression.
97834   */
97835   static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
97836     pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
97837     pOut->zStart = pValue->z;
97838     pOut->zEnd = &pValue->z[pValue->n];
97839   }
97840
97841   /* This routine constructs a binary expression node out of two ExprSpan
97842   ** objects and uses the result to populate a new ExprSpan object.
97843   */
97844   static void spanBinaryExpr(
97845     ExprSpan *pOut,     /* Write the result here */
97846     Parse *pParse,      /* The parsing context.  Errors accumulate here */
97847     int op,             /* The binary operation */
97848     ExprSpan *pLeft,    /* The left operand */
97849     ExprSpan *pRight    /* The right operand */
97850   ){
97851     pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
97852     pOut->zStart = pLeft->zStart;
97853     pOut->zEnd = pRight->zEnd;
97854   }
97855
97856   /* Construct an expression node for a unary postfix operator
97857   */
97858   static void spanUnaryPostfix(
97859     ExprSpan *pOut,        /* Write the new expression node here */
97860     Parse *pParse,         /* Parsing context to record errors */
97861     int op,                /* The operator */
97862     ExprSpan *pOperand,    /* The operand */
97863     Token *pPostOp         /* The operand token for setting the span */
97864   ){
97865     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
97866     pOut->zStart = pOperand->zStart;
97867     pOut->zEnd = &pPostOp->z[pPostOp->n];
97868   }                           
97869
97870   /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
97871   ** unary TK_ISNULL or TK_NOTNULL expression. */
97872   static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
97873     sqlite3 *db = pParse->db;
97874     if( db->mallocFailed==0 && pY->op==TK_NULL ){
97875       pA->op = (u8)op;
97876       sqlite3ExprDelete(db, pA->pRight);
97877       pA->pRight = 0;
97878     }
97879   }
97880
97881   /* Construct an expression node for a unary prefix operator
97882   */
97883   static void spanUnaryPrefix(
97884     ExprSpan *pOut,        /* Write the new expression node here */
97885     Parse *pParse,         /* Parsing context to record errors */
97886     int op,                /* The operator */
97887     ExprSpan *pOperand,    /* The operand */
97888     Token *pPreOp         /* The operand token for setting the span */
97889   ){
97890     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
97891     pOut->zStart = pPreOp->z;
97892     pOut->zEnd = pOperand->zEnd;
97893   }
97894 /* Next is all token values, in a form suitable for use by makeheaders.
97895 ** This section will be null unless lemon is run with the -m switch.
97896 */
97897 /* 
97898 ** These constants (all generated automatically by the parser generator)
97899 ** specify the various kinds of tokens (terminals) that the parser
97900 ** understands. 
97901 **
97902 ** Each symbol here is a terminal symbol in the grammar.
97903 */
97904 /* Make sure the INTERFACE macro is defined.
97905 */
97906 #ifndef INTERFACE
97907 # define INTERFACE 1
97908 #endif
97909 /* The next thing included is series of defines which control
97910 ** various aspects of the generated parser.
97911 **    YYCODETYPE         is the data type used for storing terminal
97912 **                       and nonterminal numbers.  "unsigned char" is
97913 **                       used if there are fewer than 250 terminals
97914 **                       and nonterminals.  "int" is used otherwise.
97915 **    YYNOCODE           is a number of type YYCODETYPE which corresponds
97916 **                       to no legal terminal or nonterminal number.  This
97917 **                       number is used to fill in empty slots of the hash 
97918 **                       table.
97919 **    YYFALLBACK         If defined, this indicates that one or more tokens
97920 **                       have fall-back values which should be used if the
97921 **                       original value of the token will not parse.
97922 **    YYACTIONTYPE       is the data type used for storing terminal
97923 **                       and nonterminal numbers.  "unsigned char" is
97924 **                       used if there are fewer than 250 rules and
97925 **                       states combined.  "int" is used otherwise.
97926 **    sqlite3ParserTOKENTYPE     is the data type used for minor tokens given 
97927 **                       directly to the parser from the tokenizer.
97928 **    YYMINORTYPE        is the data type used for all minor tokens.
97929 **                       This is typically a union of many types, one of
97930 **                       which is sqlite3ParserTOKENTYPE.  The entry in the union
97931 **                       for base tokens is called "yy0".
97932 **    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
97933 **                       zero the stack is dynamically sized using realloc()
97934 **    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
97935 **    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
97936 **    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
97937 **    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
97938 **    YYNSTATE           the combined number of states.
97939 **    YYNRULE            the number of rules in the grammar
97940 **    YYERRORSYMBOL      is the code number of the error symbol.  If not
97941 **                       defined, then do no error processing.
97942 */
97943 #define YYCODETYPE unsigned char
97944 #define YYNOCODE 253
97945 #define YYACTIONTYPE unsigned short int
97946 #define YYWILDCARD 67
97947 #define sqlite3ParserTOKENTYPE Token
97948 typedef union {
97949   int yyinit;
97950   sqlite3ParserTOKENTYPE yy0;
97951   int yy4;
97952   struct TrigEvent yy90;
97953   ExprSpan yy118;
97954   TriggerStep* yy203;
97955   u8 yy210;
97956   struct {int value; int mask;} yy215;
97957   SrcList* yy259;
97958   struct LimitVal yy292;
97959   Expr* yy314;
97960   ExprList* yy322;
97961   struct LikeOp yy342;
97962   IdList* yy384;
97963   Select* yy387;
97964 } YYMINORTYPE;
97965 #ifndef YYSTACKDEPTH
97966 #define YYSTACKDEPTH 100
97967 #endif
97968 #define sqlite3ParserARG_SDECL Parse *pParse;
97969 #define sqlite3ParserARG_PDECL ,Parse *pParse
97970 #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
97971 #define sqlite3ParserARG_STORE yypParser->pParse = pParse
97972 #define YYNSTATE 630
97973 #define YYNRULE 329
97974 #define YYFALLBACK 1
97975 #define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
97976 #define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
97977 #define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)
97978
97979 /* The yyzerominor constant is used to initialize instances of
97980 ** YYMINORTYPE objects to zero. */
97981 static const YYMINORTYPE yyzerominor = { 0 };
97982
97983 /* Define the yytestcase() macro to be a no-op if is not already defined
97984 ** otherwise.
97985 **
97986 ** Applications can choose to define yytestcase() in the %include section
97987 ** to a macro that can assist in verifying code coverage.  For production
97988 ** code the yytestcase() macro should be turned off.  But it is useful
97989 ** for testing.
97990 */
97991 #ifndef yytestcase
97992 # define yytestcase(X)
97993 #endif
97994
97995
97996 /* Next are the tables used to determine what action to take based on the
97997 ** current state and lookahead token.  These tables are used to implement
97998 ** functions that take a state number and lookahead value and return an
97999 ** action integer.  
98000 **
98001 ** Suppose the action integer is N.  Then the action is determined as
98002 ** follows
98003 **
98004 **   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
98005 **                                      token onto the stack and goto state N.
98006 **
98007 **   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
98008 **
98009 **   N == YYNSTATE+YYNRULE              A syntax error has occurred.
98010 **
98011 **   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
98012 **
98013 **   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
98014 **                                      slots in the yy_action[] table.
98015 **
98016 ** The action table is constructed as a single large table named yy_action[].
98017 ** Given state S and lookahead X, the action is computed as
98018 **
98019 **      yy_action[ yy_shift_ofst[S] + X ]
98020 **
98021 ** If the index value yy_shift_ofst[S]+X is out of range or if the value
98022 ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
98023 ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
98024 ** and that yy_default[S] should be used instead.  
98025 **
98026 ** The formula above is for computing the action when the lookahead is
98027 ** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
98028 ** a reduce action) then the yy_reduce_ofst[] array is used in place of
98029 ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
98030 ** YY_SHIFT_USE_DFLT.
98031 **
98032 ** The following are the tables generated in this section:
98033 **
98034 **  yy_action[]        A single table containing all actions.
98035 **  yy_lookahead[]     A table containing the lookahead for each entry in
98036 **                     yy_action.  Used to detect hash collisions.
98037 **  yy_shift_ofst[]    For each state, the offset into yy_action for
98038 **                     shifting terminals.
98039 **  yy_reduce_ofst[]   For each state, the offset into yy_action for
98040 **                     shifting non-terminals after a reduce.
98041 **  yy_default[]       Default action for each state.
98042 */
98043 #define YY_ACTTAB_COUNT (1557)
98044 static const YYACTIONTYPE yy_action[] = {
98045  /*     0 */   313,  960,  186,  419,    2,  172,  627,  597,   55,   55,
98046  /*    10 */    55,   55,   48,   53,   53,   53,   53,   52,   52,   51,
98047  /*    20 */    51,   51,   50,  238,  302,  283,  623,  622,  516,  515,
98048  /*    30 */   590,  584,   55,   55,   55,   55,  282,   53,   53,   53,
98049  /*    40 */    53,   52,   52,   51,   51,   51,   50,  238,    6,   56,
98050  /*    50 */    57,   47,  582,  581,  583,  583,   54,   54,   55,   55,
98051  /*    60 */    55,   55,  608,   53,   53,   53,   53,   52,   52,   51,
98052  /*    70 */    51,   51,   50,  238,  313,  597,  409,  330,  579,  579,
98053  /*    80 */    32,   53,   53,   53,   53,   52,   52,   51,   51,   51,
98054  /*    90 */    50,  238,  330,  217,  620,  619,  166,  411,  624,  382,
98055  /*   100 */   379,  378,    7,  491,  590,  584,  200,  199,  198,   58,
98056  /*   110 */   377,  300,  414,  621,  481,   66,  623,  622,  621,  580,
98057  /*   120 */   254,  601,   94,   56,   57,   47,  582,  581,  583,  583,
98058  /*   130 */    54,   54,   55,   55,   55,   55,  671,   53,   53,   53,
98059  /*   140 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  532,
98060  /*   150 */   226,  506,  507,  133,  177,  139,  284,  385,  279,  384,
98061  /*   160 */   169,  197,  342,  398,  251,  226,  253,  275,  388,  167,
98062  /*   170 */   139,  284,  385,  279,  384,  169,  570,  236,  590,  584,
98063  /*   180 */   672,  240,  275,  157,  620,  619,  554,  437,   51,   51,
98064  /*   190 */    51,   50,  238,  343,  439,  553,  438,   56,   57,   47,
98065  /*   200 */   582,  581,  583,  583,   54,   54,   55,   55,   55,   55,
98066  /*   210 */   465,   53,   53,   53,   53,   52,   52,   51,   51,   51,
98067  /*   220 */    50,  238,  313,  390,   52,   52,   51,   51,   51,   50,
98068  /*   230 */   238,  391,  166,  491,  566,  382,  379,  378,  409,  440,
98069  /*   240 */   579,  579,  252,  440,  607,   66,  377,  513,  621,   49,
98070  /*   250 */    46,  147,  590,  584,  621,   16,  466,  189,  621,  441,
98071  /*   260 */   442,  673,  526,  441,  340,  577,  595,   64,  194,  482,
98072  /*   270 */   434,   56,   57,   47,  582,  581,  583,  583,   54,   54,
98073  /*   280 */    55,   55,   55,   55,   30,   53,   53,   53,   53,   52,
98074  /*   290 */    52,   51,   51,   51,   50,  238,  313,  593,  593,  593,
98075  /*   300 */   387,  578,  606,  493,  259,  351,  258,  411,    1,  623,
98076  /*   310 */   622,  496,  623,  622,   65,  240,  623,  622,  597,  443,
98077  /*   320 */   237,  239,  414,  341,  237,  602,  590,  584,   18,  603,
98078  /*   330 */   166,  601,   87,  382,  379,  378,   67,  623,  622,   38,
98079  /*   340 */   623,  622,  176,  270,  377,   56,   57,   47,  582,  581,
98080  /*   350 */   583,  583,   54,   54,   55,   55,   55,   55,  175,   53,
98081  /*   360 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
98082  /*   370 */   313,  396,  233,  411,  531,  565,  317,  620,  619,   44,
98083  /*   380 */   620,  619,  240,  206,  620,  619,  597,  266,  414,  268,
98084  /*   390 */   409,  597,  579,  579,  352,  184,  505,  601,   73,  533,
98085  /*   400 */   590,  584,  466,  548,  190,  620,  619,  576,  620,  619,
98086  /*   410 */   547,  383,  551,   35,  332,  575,  574,  600,  504,   56,
98087  /*   420 */    57,   47,  582,  581,  583,  583,   54,   54,   55,   55,
98088  /*   430 */    55,   55,  567,   53,   53,   53,   53,   52,   52,   51,
98089  /*   440 */    51,   51,   50,  238,  313,  411,  561,  561,  528,  364,
98090  /*   450 */   259,  351,  258,  183,  361,  549,  524,  374,  411,  597,
98091  /*   460 */   414,  240,  560,  560,  409,  604,  579,  579,  328,  601,
98092  /*   470 */    93,  623,  622,  414,  590,  584,  237,  564,  559,  559,
98093  /*   480 */   520,  402,  601,   87,  409,  210,  579,  579,  168,  421,
98094  /*   490 */   950,  519,  950,   56,   57,   47,  582,  581,  583,  583,
98095  /*   500 */    54,   54,   55,   55,   55,   55,  192,   53,   53,   53,
98096  /*   510 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  600,
98097  /*   520 */   293,  563,  511,  234,  357,  146,  475,  475,  367,  411,
98098  /*   530 */   562,  411,  358,  542,  425,  171,  411,  215,  144,  620,
98099  /*   540 */   619,  544,  318,  353,  414,  203,  414,  275,  590,  584,
98100  /*   550 */   549,  414,  174,  601,   94,  601,   79,  558,  471,   61,
98101  /*   560 */   601,   79,  421,  949,  350,  949,   34,   56,   57,   47,
98102  /*   570 */   582,  581,  583,  583,   54,   54,   55,   55,   55,   55,
98103  /*   580 */   535,   53,   53,   53,   53,   52,   52,   51,   51,   51,
98104  /*   590 */    50,  238,  313,  307,  424,  394,  272,   49,   46,  147,
98105  /*   600 */   349,  322,    4,  411,  491,  312,  321,  425,  568,  492,
98106  /*   610 */   216,  264,  407,  575,  574,  429,   66,  549,  414,  621,
98107  /*   620 */   540,  602,  590,  584,   13,  603,  621,  601,   72,   12,
98108  /*   630 */   618,  617,  616,  202,  210,  621,  546,  469,  422,  319,
98109  /*   640 */   148,   56,   57,   47,  582,  581,  583,  583,   54,   54,
98110  /*   650 */    55,   55,   55,   55,  338,   53,   53,   53,   53,   52,
98111  /*   660 */    52,   51,   51,   51,   50,  238,  313,  600,  600,  411,
98112  /*   670 */    39,   21,   37,  170,  237,  875,  411,  572,  572,  201,
98113  /*   680 */   144,  473,  538,  331,  414,  474,  143,  146,  630,  628,
98114  /*   690 */   334,  414,  353,  601,   68,  168,  590,  584,  132,  365,
98115  /*   700 */   601,   96,  307,  423,  530,  336,   49,   46,  147,  568,
98116  /*   710 */   406,  216,  549,  360,  529,   56,   57,   47,  582,  581,
98117  /*   720 */   583,  583,   54,   54,   55,   55,   55,   55,  411,   53,
98118  /*   730 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
98119  /*   740 */   313,  411,  605,  414,  484,  510,  172,  422,  597,  318,
98120  /*   750 */   496,  485,  601,   99,  411,  142,  414,  411,  231,  411,
98121  /*   760 */   540,  411,  359,  629,    2,  601,   97,  426,  308,  414,
98122  /*   770 */   590,  584,  414,   20,  414,  621,  414,  621,  601,  106,
98123  /*   780 */   503,  601,  105,  601,  108,  601,  109,  204,   28,   56,
98124  /*   790 */    57,   47,  582,  581,  583,  583,   54,   54,   55,   55,
98125  /*   800 */    55,   55,  411,   53,   53,   53,   53,   52,   52,   51,
98126  /*   810 */    51,   51,   50,  238,  313,  411,  597,  414,  411,  276,
98127  /*   820 */   214,  600,  411,  366,  213,  381,  601,  134,  274,  500,
98128  /*   830 */   414,  167,  130,  414,  621,  411,  354,  414,  376,  601,
98129  /*   840 */   135,  129,  601,  100,  590,  584,  601,  104,  522,  521,
98130  /*   850 */   414,  621,  224,  273,  600,  167,  327,  282,  600,  601,
98131  /*   860 */   103,  468,  521,   56,   57,   47,  582,  581,  583,  583,
98132  /*   870 */    54,   54,   55,   55,   55,   55,  411,   53,   53,   53,
98133  /*   880 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  411,
98134  /*   890 */    27,  414,  411,  375,  276,  167,  359,  544,   50,  238,
98135  /*   900 */   601,   95,  128,  223,  414,  411,  165,  414,  411,  621,
98136  /*   910 */   411,  621,  612,  601,  102,  372,  601,   76,  590,  584,
98137  /*   920 */   414,  570,  236,  414,  470,  414,  167,  621,  188,  601,
98138  /*   930 */    98,  225,  601,  138,  601,  137,  232,   56,   45,   47,
98139  /*   940 */   582,  581,  583,  583,   54,   54,   55,   55,   55,   55,
98140  /*   950 */   411,   53,   53,   53,   53,   52,   52,   51,   51,   51,
98141  /*   960 */    50,  238,  313,  276,  276,  414,  411,  276,  544,  459,
98142  /*   970 */   359,  171,  209,  479,  601,  136,  628,  334,  621,  621,
98143  /*   980 */   125,  414,  621,  368,  411,  621,  257,  540,  589,  588,
98144  /*   990 */   601,   75,  590,  584,  458,  446,   23,   23,  124,  414,
98145  /*  1000 */   326,  325,  621,  427,  324,  309,  600,  288,  601,   92,
98146  /*  1010 */   586,  585,   57,   47,  582,  581,  583,  583,   54,   54,
98147  /*  1020 */    55,   55,   55,   55,  411,   53,   53,   53,   53,   52,
98148  /*  1030 */    52,   51,   51,   51,   50,  238,  313,  587,  411,  414,
98149  /*  1040 */   411,  207,  611,  476,  171,  472,  160,  123,  601,   91,
98150  /*  1050 */   323,  261,   15,  414,  464,  414,  411,  621,  411,  354,
98151  /*  1060 */   222,  411,  601,   74,  601,   90,  590,  584,  159,  264,
98152  /*  1070 */   158,  414,  461,  414,  621,  600,  414,  121,  120,   25,
98153  /*  1080 */   601,   89,  601,  101,  621,  601,   88,   47,  582,  581,
98154  /*  1090 */   583,  583,   54,   54,   55,   55,   55,   55,  544,   53,
98155  /*  1100 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
98156  /*  1110 */    43,  405,  263,    3,  610,  264,  140,  415,  622,   24,
98157  /*  1120 */   410,   11,  456,  594,  118,  155,  219,  452,  408,  621,
98158  /*  1130 */   621,  621,  156,   43,  405,  621,    3,  286,  621,  113,
98159  /*  1140 */   415,  622,  111,  445,  411,  400,  557,  403,  545,   10,
98160  /*  1150 */   411,  408,  264,  110,  205,  436,  541,  566,  453,  414,
98161  /*  1160 */   621,  621,   63,  621,  435,  414,  411,  621,  601,   94,
98162  /*  1170 */   403,  621,  411,  337,  601,   86,  150,   40,   41,  534,
98163  /*  1180 */   566,  414,  242,  264,   42,  413,  412,  414,  600,  595,
98164  /*  1190 */   601,   85,  191,  333,  107,  451,  601,   84,  621,  539,
98165  /*  1200 */    40,   41,  420,  230,  411,  149,  316,   42,  413,  412,
98166  /*  1210 */   398,  127,  595,  315,  621,  399,  278,  625,  181,  414,
98167  /*  1220 */   593,  593,  593,  592,  591,   14,  450,  411,  601,   71,
98168  /*  1230 */   240,  621,   43,  405,  264,    3,  615,  180,  264,  415,
98169  /*  1240 */   622,  614,  414,  593,  593,  593,  592,  591,   14,  621,
98170  /*  1250 */   408,  601,   70,  621,  417,   33,  405,  613,    3,  411,
98171  /*  1260 */   264,  411,  415,  622,  418,  626,  178,  509,    8,  403,
98172  /*  1270 */   241,  416,  126,  408,  414,  621,  414,  449,  208,  566,
98173  /*  1280 */   240,  221,  621,  601,   83,  601,   82,  599,  297,  277,
98174  /*  1290 */   296,   30,  403,   31,  395,  264,  295,  397,  489,   40,
98175  /*  1300 */    41,  411,  566,  220,  621,  294,   42,  413,  412,  271,
98176  /*  1310 */   621,  595,  600,  621,   59,   60,  414,  269,  267,  623,
98177  /*  1320 */   622,   36,   40,   41,  621,  601,   81,  598,  235,   42,
98178  /*  1330 */   413,  412,  621,  621,  595,  265,  344,  411,  248,  556,
98179  /*  1340 */   173,  185,  593,  593,  593,  592,  591,   14,  218,   29,
98180  /*  1350 */   621,  543,  414,  305,  304,  303,  179,  301,  411,  566,
98181  /*  1360 */   454,  601,   80,  289,  335,  593,  593,  593,  592,  591,
98182  /*  1370 */    14,  411,  287,  414,  151,  392,  246,  260,  411,  196,
98183  /*  1380 */   195,  523,  601,   69,  411,  245,  414,  526,  537,  285,
98184  /*  1390 */   389,  595,  621,  414,  536,  601,   17,  362,  153,  414,
98185  /*  1400 */   466,  463,  601,   78,  154,  414,  462,  152,  601,   77,
98186  /*  1410 */   355,  255,  621,  455,  601,    9,  621,  386,  444,  517,
98187  /*  1420 */   247,  621,  593,  593,  593,  621,  621,  244,  621,  243,
98188  /*  1430 */   430,  518,  292,  621,  329,  621,  145,  393,  280,  513,
98189  /*  1440 */   291,  131,  621,  514,  621,  621,  311,  621,  259,  346,
98190  /*  1450 */   249,  621,  621,  229,  314,  621,  228,  512,  227,  240,
98191  /*  1460 */   494,  488,  310,  164,  487,  486,  373,  480,  163,  262,
98192  /*  1470 */   369,  371,  162,   26,  212,  478,  477,  161,  141,  363,
98193  /*  1480 */   467,  122,  339,  187,  119,  348,  347,  117,  116,  115,
98194  /*  1490 */   114,  112,  182,  457,  320,   22,  433,  432,  448,   19,
98195  /*  1500 */   609,  431,  428,   62,  193,  596,  573,  298,  555,  552,
98196  /*  1510 */   571,  404,  290,  380,  498,  510,  495,  306,  281,  499,
98197  /*  1520 */   250,    5,  497,  460,  345,  447,  569,  550,  238,  299,
98198  /*  1530 */   527,  525,  508,  961,  502,  501,  961,  401,  961,  211,
98199  /*  1540 */   490,  356,  256,  961,  483,  961,  961,  961,  961,  961,
98200  /*  1550 */   961,  961,  961,  961,  961,  961,  370,
98201 };
98202 static const YYCODETYPE yy_lookahead[] = {
98203  /*     0 */    19,  142,  143,  144,  145,   24,    1,   26,   77,   78,
98204  /*    10 */    79,   80,   81,   82,   83,   84,   85,   86,   87,   88,
98205  /*    20 */    89,   90,   91,   92,   15,   98,   26,   27,    7,    8,
98206  /*    30 */    49,   50,   77,   78,   79,   80,  109,   82,   83,   84,
98207  /*    40 */    85,   86,   87,   88,   89,   90,   91,   92,   22,   68,
98208  /*    50 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
98209  /*    60 */    79,   80,   23,   82,   83,   84,   85,   86,   87,   88,
98210  /*    70 */    89,   90,   91,   92,   19,   94,  112,   19,  114,  115,
98211  /*    80 */    25,   82,   83,   84,   85,   86,   87,   88,   89,   90,
98212  /*    90 */    91,   92,   19,   22,   94,   95,   96,  150,  150,   99,
98213  /*   100 */   100,  101,   76,  150,   49,   50,  105,  106,  107,   54,
98214  /*   110 */   110,  158,  165,  165,  161,  162,   26,   27,  165,  113,
98215  /*   120 */    16,  174,  175,   68,   69,   70,   71,   72,   73,   74,
98216  /*   130 */    75,   76,   77,   78,   79,   80,  118,   82,   83,   84,
98217  /*   140 */    85,   86,   87,   88,   89,   90,   91,   92,   19,   23,
98218  /*   150 */    92,   97,   98,   24,   96,   97,   98,   99,  100,  101,
98219  /*   160 */   102,   25,   97,  216,   60,   92,   62,  109,  221,   25,
98220  /*   170 */    97,   98,   99,  100,  101,  102,   86,   87,   49,   50,
98221  /*   180 */   118,  116,  109,   25,   94,   95,   32,   97,   88,   89,
98222  /*   190 */    90,   91,   92,  128,  104,   41,  106,   68,   69,   70,
98223  /*   200 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
98224  /*   210 */    11,   82,   83,   84,   85,   86,   87,   88,   89,   90,
98225  /*   220 */    91,   92,   19,   19,   86,   87,   88,   89,   90,   91,
98226  /*   230 */    92,   27,   96,  150,   66,   99,  100,  101,  112,  150,
98227  /*   240 */   114,  115,  138,  150,  161,  162,  110,  103,  165,  222,
98228  /*   250 */   223,  224,   49,   50,  165,   22,   57,   24,  165,  170,
98229  /*   260 */   171,  118,   94,  170,  171,   23,   98,   25,  185,  186,
98230  /*   270 */   243,   68,   69,   70,   71,   72,   73,   74,   75,   76,
98231  /*   280 */    77,   78,   79,   80,  126,   82,   83,   84,   85,   86,
98232  /*   290 */    87,   88,   89,   90,   91,   92,   19,  129,  130,  131,
98233  /*   300 */    88,   23,  172,  173,  105,  106,  107,  150,   22,   26,
98234  /*   310 */    27,  181,   26,   27,   22,  116,   26,   27,   26,  230,
98235  /*   320 */   231,  197,  165,  230,  231,  113,   49,   50,  204,  117,
98236  /*   330 */    96,  174,  175,   99,  100,  101,   22,   26,   27,  136,
98237  /*   340 */    26,   27,  118,   16,  110,   68,   69,   70,   71,   72,
98238  /*   350 */    73,   74,   75,   76,   77,   78,   79,   80,  118,   82,
98239  /*   360 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
98240  /*   370 */    19,  214,  215,  150,   23,   23,  155,   94,   95,   22,
98241  /*   380 */    94,   95,  116,  160,   94,   95,   94,   60,  165,   62,
98242  /*   390 */   112,   26,  114,  115,  128,   23,   36,  174,  175,   88,
98243  /*   400 */    49,   50,   57,  120,   22,   94,   95,   23,   94,   95,
98244  /*   410 */   120,   51,   25,  136,  169,  170,  171,  194,   58,   68,
98245  /*   420 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
98246  /*   430 */    79,   80,   23,   82,   83,   84,   85,   86,   87,   88,
98247  /*   440 */    89,   90,   91,   92,   19,  150,   12,   12,   23,  228,
98248  /*   450 */   105,  106,  107,   23,  233,   25,  165,   19,  150,   94,
98249  /*   460 */   165,  116,   28,   28,  112,  174,  114,  115,  108,  174,
98250  /*   470 */   175,   26,   27,  165,   49,   50,  231,   11,   44,   44,
98251  /*   480 */    46,   46,  174,  175,  112,  160,  114,  115,   50,   22,
98252  /*   490 */    23,   57,   25,   68,   69,   70,   71,   72,   73,   74,
98253  /*   500 */    75,   76,   77,   78,   79,   80,  119,   82,   83,   84,
98254  /*   510 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  194,
98255  /*   520 */   225,   23,   23,  215,   19,   95,  105,  106,  107,  150,
98256  /*   530 */    23,  150,   27,   23,   67,   25,  150,  206,  207,   94,
98257  /*   540 */    95,  166,  104,  218,  165,   22,  165,  109,   49,   50,
98258  /*   550 */   120,  165,   25,  174,  175,  174,  175,   23,   21,  234,
98259  /*   560 */   174,  175,   22,   23,  239,   25,   25,   68,   69,   70,
98260  /*   570 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
98261  /*   580 */   205,   82,   83,   84,   85,   86,   87,   88,   89,   90,
98262  /*   590 */    91,   92,   19,   22,   23,  216,   23,  222,  223,  224,
98263  /*   600 */    63,  220,   35,  150,  150,  163,  220,   67,  166,  167,
98264  /*   610 */   168,  150,  169,  170,  171,  161,  162,   25,  165,  165,
98265  /*   620 */   150,  113,   49,   50,   25,  117,  165,  174,  175,   35,
98266  /*   630 */     7,    8,    9,  160,  160,  165,  120,  100,   67,  247,
98267  /*   640 */   248,   68,   69,   70,   71,   72,   73,   74,   75,   76,
98268  /*   650 */    77,   78,   79,   80,  193,   82,   83,   84,   85,   86,
98269  /*   660 */    87,   88,   89,   90,   91,   92,   19,  194,  194,  150,
98270  /*   670 */   135,   24,  137,   35,  231,  138,  150,  129,  130,  206,
98271  /*   680 */   207,   30,   27,  213,  165,   34,  118,   95,    0,    1,
98272  /*   690 */     2,  165,  218,  174,  175,   50,   49,   50,   22,   48,
98273  /*   700 */   174,  175,   22,   23,   23,  244,  222,  223,  224,  166,
98274  /*   710 */   167,  168,  120,  239,   23,   68,   69,   70,   71,   72,
98275  /*   720 */    73,   74,   75,   76,   77,   78,   79,   80,  150,   82,
98276  /*   730 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
98277  /*   740 */    19,  150,  173,  165,  181,  182,   24,   67,   26,  104,
98278  /*   750 */   181,  188,  174,  175,  150,   39,  165,  150,   52,  150,
98279  /*   760 */   150,  150,  150,  144,  145,  174,  175,  249,  250,  165,
98280  /*   770 */    49,   50,  165,   52,  165,  165,  165,  165,  174,  175,
98281  /*   780 */    29,  174,  175,  174,  175,  174,  175,  160,   22,   68,
98282  /*   790 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
98283  /*   800 */    79,   80,  150,   82,   83,   84,   85,   86,   87,   88,
98284  /*   810 */    89,   90,   91,   92,   19,  150,   94,  165,  150,  150,
98285  /*   820 */   160,  194,  150,  213,  160,   52,  174,  175,   23,   23,
98286  /*   830 */   165,   25,   22,  165,  165,  150,  150,  165,   52,  174,
98287  /*   840 */   175,   22,  174,  175,   49,   50,  174,  175,  190,  191,
98288  /*   850 */   165,  165,  240,   23,  194,   25,  187,  109,  194,  174,
98289  /*   860 */   175,  190,  191,   68,   69,   70,   71,   72,   73,   74,
98290  /*   870 */    75,   76,   77,   78,   79,   80,  150,   82,   83,   84,
98291  /*   880 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  150,
98292  /*   890 */    22,  165,  150,   23,  150,   25,  150,  166,   91,   92,
98293  /*   900 */   174,  175,   22,  217,  165,  150,  102,  165,  150,  165,
98294  /*   910 */   150,  165,  150,  174,  175,   19,  174,  175,   49,   50,
98295  /*   920 */   165,   86,   87,  165,   23,  165,   25,  165,   24,  174,
98296  /*   930 */   175,  187,  174,  175,  174,  175,  205,   68,   69,   70,
98297  /*   940 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
98298  /*   950 */   150,   82,   83,   84,   85,   86,   87,   88,   89,   90,
98299  /*   960 */    91,   92,   19,  150,  150,  165,  150,  150,  166,   23,
98300  /*   970 */   150,   25,  160,   20,  174,  175,    1,    2,  165,  165,
98301  /*   980 */   104,  165,  165,   43,  150,  165,  240,  150,   49,   50,
98302  /*   990 */   174,  175,   49,   50,   23,   23,   25,   25,   53,  165,
98303  /*  1000 */   187,  187,  165,   23,  187,   25,  194,  205,  174,  175,
98304  /*  1010 */    71,   72,   69,   70,   71,   72,   73,   74,   75,   76,
98305  /*  1020 */    77,   78,   79,   80,  150,   82,   83,   84,   85,   86,
98306  /*  1030 */    87,   88,   89,   90,   91,   92,   19,   98,  150,  165,
98307  /*  1040 */   150,  160,  150,   59,   25,   53,  104,   22,  174,  175,
98308  /*  1050 */   213,  138,    5,  165,    1,  165,  150,  165,  150,  150,
98309  /*  1060 */   240,  150,  174,  175,  174,  175,   49,   50,  118,  150,
98310  /*  1070 */    35,  165,   27,  165,  165,  194,  165,  108,  127,   76,
98311  /*  1080 */   174,  175,  174,  175,  165,  174,  175,   70,   71,   72,
98312  /*  1090 */    73,   74,   75,   76,   77,   78,   79,   80,  166,   82,
98313  /*  1100 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
98314  /*  1110 */    19,   20,  193,   22,  150,  150,  150,   26,   27,   76,
98315  /*  1120 */   150,   22,    1,  150,  119,  121,  217,   20,   37,  165,
98316  /*  1130 */   165,  165,   16,   19,   20,  165,   22,  205,  165,  119,
98317  /*  1140 */    26,   27,  108,  128,  150,  150,  150,   56,  150,   22,
98318  /*  1150 */   150,   37,  150,  127,  160,   23,  150,   66,  193,  165,
98319  /*  1160 */   165,  165,   16,  165,   23,  165,  150,  165,  174,  175,
98320  /*  1170 */    56,  165,  150,   65,  174,  175,   15,   86,   87,   88,
98321  /*  1180 */    66,  165,  140,  150,   93,   94,   95,  165,  194,   98,
98322  /*  1190 */   174,  175,   22,    3,  164,  193,  174,  175,  165,  150,
98323  /*  1200 */    86,   87,    4,  180,  150,  248,  251,   93,   94,   95,
98324  /*  1210 */   216,  180,   98,  251,  165,  221,  150,  149,    6,  165,
98325  /*  1220 */   129,  130,  131,  132,  133,  134,  193,  150,  174,  175,
98326  /*  1230 */   116,  165,   19,   20,  150,   22,  149,  151,  150,   26,
98327  /*  1240 */    27,  149,  165,  129,  130,  131,  132,  133,  134,  165,
98328  /*  1250 */    37,  174,  175,  165,  149,   19,   20,   13,   22,  150,
98329  /*  1260 */   150,  150,   26,   27,  146,  147,  151,  150,   25,   56,
98330  /*  1270 */   152,  159,  154,   37,  165,  165,  165,  193,  160,   66,
98331  /*  1280 */   116,  193,  165,  174,  175,  174,  175,  194,  199,  150,
98332  /*  1290 */   200,  126,   56,  124,  123,  150,  201,  122,  150,   86,
98333  /*  1300 */    87,  150,   66,  193,  165,  202,   93,   94,   95,  150,
98334  /*  1310 */   165,   98,  194,  165,  125,   22,  165,  150,  150,   26,
98335  /*  1320 */    27,  135,   86,   87,  165,  174,  175,  203,  226,   93,
98336  /*  1330 */    94,   95,  165,  165,   98,  150,  218,  150,  193,  157,
98337  /*  1340 */   118,  157,  129,  130,  131,  132,  133,  134,    5,  104,
98338  /*  1350 */   165,  211,  165,   10,   11,   12,   13,   14,  150,   66,
98339  /*  1360 */    17,  174,  175,  210,  246,  129,  130,  131,  132,  133,
98340  /*  1370 */   134,  150,  210,  165,   31,  121,   33,  150,  150,   86,
98341  /*  1380 */    87,  176,  174,  175,  150,   42,  165,   94,  211,  210,
98342  /*  1390 */   150,   98,  165,  165,  211,  174,  175,  150,   55,  165,
98343  /*  1400 */    57,  150,  174,  175,   61,  165,  150,   64,  174,  175,
98344  /*  1410 */   150,  150,  165,  150,  174,  175,  165,  104,  150,  184,
98345  /*  1420 */   150,  165,  129,  130,  131,  165,  165,  150,  165,  150,
98346  /*  1430 */   150,  176,  150,  165,   47,  165,  150,  150,  176,  103,
98347  /*  1440 */   150,   22,  165,  178,  165,  165,  179,  165,  105,  106,
98348  /*  1450 */   107,  165,  165,  229,  111,  165,   92,  176,  229,  116,
98349  /*  1460 */   184,  176,  179,  156,  176,  176,   18,  157,  156,  237,
98350  /*  1470 */    45,  157,  156,  135,  157,  157,  238,  156,   68,  157,
98351  /*  1480 */   189,  189,  139,  219,   22,  157,   18,  192,  192,  192,
98352  /*  1490 */   192,  189,  219,  199,  157,  242,   40,  157,  199,  242,
98353  /*  1500 */   153,  157,   38,  245,  196,  166,  232,  198,  177,  177,
98354  /*  1510 */   232,  227,  209,  178,  166,  182,  166,  148,  177,  177,
98355  /*  1520 */   209,  196,  177,  199,  209,  199,  166,  208,   92,  195,
98356  /*  1530 */   174,  174,  183,  252,  183,  183,  252,  191,  252,  235,
98357  /*  1540 */   186,  241,  241,  252,  186,  252,  252,  252,  252,  252,
98358  /*  1550 */   252,  252,  252,  252,  252,  252,  236,
98359 };
98360 #define YY_SHIFT_USE_DFLT (-74)
98361 #define YY_SHIFT_COUNT (418)
98362 #define YY_SHIFT_MIN   (-73)
98363 #define YY_SHIFT_MAX   (1468)
98364 static const short yy_shift_ofst[] = {
98365  /*     0 */   975, 1114, 1343, 1114, 1213, 1213,   90,   90,    0,  -19,
98366  /*    10 */  1213, 1213, 1213, 1213, 1213,  345,  445,  721, 1091, 1213,
98367  /*    20 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
98368  /*    30 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
98369  /*    40 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1236, 1213, 1213,
98370  /*    50 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
98371  /*    60 */  1213,  199,  445,  445,  835,  835,  365, 1164,   55,  647,
98372  /*    70 */   573,  499,  425,  351,  277,  203,  129,  795,  795,  795,
98373  /*    80 */   795,  795,  795,  795,  795,  795,  795,  795,  795,  795,
98374  /*    90 */   795,  795,  795,  795,  795,  869,  795,  943, 1017, 1017,
98375  /*   100 */   -69,  -45,  -45,  -45,  -45,  -45,   -1,   58,  138,  100,
98376  /*   110 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
98377  /*   120 */   445,  445,  445,  445,  445,  445,  537,  438,  445,  445,
98378  /*   130 */   445,  445,  445,  365,  807, 1436,  -74,  -74,  -74, 1293,
98379  /*   140 */    73,  434,  434,  311,  314,  290,  283,  286,  540,  467,
98380  /*   150 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
98381  /*   160 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
98382  /*   170 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
98383  /*   180 */   445,  445,   65,  722,  722,  722,  688,  266, 1164, 1164,
98384  /*   190 */  1164,  -74,  -74,  -74,  136,  168,  168,  234,  360,  360,
98385  /*   200 */   360,  430,  372,  435,  352,  278,  126,  -36,  -36,  -36,
98386  /*   210 */   -36,  421,  651,  -36,  -36,  592,  292,  212,  623,  158,
98387  /*   220 */   204,  204,  505,  158,  505,  144,  365,  154,  365,  154,
98388  /*   230 */   645,  154,  204,  154,  154,  535,  548,  548,  365,  387,
98389  /*   240 */   508,  233, 1464, 1222, 1222, 1456, 1456, 1222, 1462, 1410,
98390  /*   250 */  1165, 1468, 1468, 1468, 1468, 1222, 1165, 1462, 1410, 1410,
98391  /*   260 */  1222, 1448, 1338, 1425, 1222, 1222, 1448, 1222, 1448, 1222,
98392  /*   270 */  1448, 1419, 1313, 1313, 1313, 1387, 1364, 1364, 1419, 1313,
98393  /*   280 */  1336, 1313, 1387, 1313, 1313, 1254, 1245, 1254, 1245, 1254,
98394  /*   290 */  1245, 1222, 1222, 1186, 1189, 1175, 1169, 1171, 1165, 1164,
98395  /*   300 */  1243, 1244, 1244, 1212, 1212, 1212, 1212,  -74,  -74,  -74,
98396  /*   310 */   -74,  -74,  -74,  939,  104,  680,  571,  327,    1,  980,
98397  /*   320 */    26,  972,  971,  946,  901,  870,  830,  806,   54,   21,
98398  /*   330 */   -73,  510,  242, 1198, 1190, 1170, 1042, 1161, 1108, 1146,
98399  /*   340 */  1141, 1132, 1015, 1127, 1026, 1034, 1020, 1107, 1004, 1116,
98400  /*   350 */  1121, 1005, 1099,  951, 1043, 1003,  969, 1045, 1035,  950,
98401  /*   360 */  1053, 1047, 1025,  942,  913,  992, 1019,  945,  984,  940,
98402  /*   370 */   876,  904,  953,  896,  748,  804,  880,  786,  868,  819,
98403  /*   380 */   805,  810,  773,  751,  766,  706,  716,  691,  681,  568,
98404  /*   390 */   655,  638,  676,  516,  541,  594,  599,  567,  541,  534,
98405  /*   400 */   507,  527,  498,  523,  466,  382,  409,  384,  357,    6,
98406  /*   410 */   240,  224,  143,   62,   18,   71,   39,    9,    5,
98407 };
98408 #define YY_REDUCE_USE_DFLT (-142)
98409 #define YY_REDUCE_COUNT (312)
98410 #define YY_REDUCE_MIN   (-141)
98411 #define YY_REDUCE_MAX   (1369)
98412 static const short yy_reduce_ofst[] = {
98413  /*     0 */  -141,  994, 1118,  223,  157,  -53,   93,   89,   83,  375,
98414  /*    10 */   386,  381,  379,  308,  295,  325,  -47,   27, 1240, 1234,
98415  /*    20 */  1228, 1221, 1208, 1187, 1151, 1111, 1109, 1077, 1054, 1022,
98416  /*    30 */  1016, 1000,  911,  908,  906,  890,  888,  874,  834,  816,
98417  /*    40 */   800,  760,  758,  755,  742,  739,  726,  685,  672,  668,
98418  /*    50 */   665,  652,  611,  609,  607,  604,  591,  578,  526,  519,
98419  /*    60 */   453,  474,  454,  461,  443,  245,  442,  473,  484,  484,
98420  /*    70 */   484,  484,  484,  484,  484,  484,  484,  484,  484,  484,
98421  /*    80 */   484,  484,  484,  484,  484,  484,  484,  484,  484,  484,
98422  /*    90 */   484,  484,  484,  484,  484,  484,  484,  484,  484,  484,
98423  /*   100 */   484,  484,  484,  484,  484,  484,  484,  130,  484,  484,
98424  /*   110 */  1145,  909, 1110, 1088, 1084, 1033, 1002,  965,  820,  837,
98425  /*   120 */   746,  686,  612,  817,  610,  919,  221,  563,  814,  813,
98426  /*   130 */   744,  669,  470,  543,  484,  484,  484,  484,  484,  291,
98427  /*   140 */   569,  671,  658,  970, 1290, 1287, 1286, 1282,  518,  518,
98428  /*   150 */  1280, 1279, 1277, 1270, 1268, 1263, 1261, 1260, 1256, 1251,
98429  /*   160 */  1247, 1227, 1185, 1168, 1167, 1159, 1148, 1139, 1117, 1066,
98430  /*   170 */  1049, 1006,  998,  996,  995,  973,  970,  966,  964,  892,
98431  /*   180 */   762,  -52,  881,  932,  802,  731,  619,  812,  664,  660,
98432  /*   190 */   627,  392,  331,  124, 1358, 1357, 1356, 1354, 1352, 1351,
98433  /*   200 */  1349, 1319, 1334, 1346, 1334, 1334, 1334, 1334, 1334, 1334,
98434  /*   210 */  1334, 1320, 1304, 1334, 1334, 1319, 1360, 1325, 1369, 1326,
98435  /*   220 */  1315, 1311, 1301, 1324, 1300, 1335, 1350, 1345, 1348, 1342,
98436  /*   230 */  1333, 1341, 1303, 1332, 1331, 1284, 1278, 1274, 1339, 1309,
98437  /*   240 */  1308, 1347, 1258, 1344, 1340, 1257, 1253, 1337, 1273, 1302,
98438  /*   250 */  1299, 1298, 1297, 1296, 1295, 1328, 1294, 1264, 1292, 1291,
98439  /*   260 */  1322, 1321, 1238, 1232, 1318, 1317, 1316, 1314, 1312, 1310,
98440  /*   270 */  1307, 1283, 1289, 1288, 1285, 1276, 1229, 1224, 1267, 1281,
98441  /*   280 */  1265, 1262, 1235, 1255, 1205, 1183, 1179, 1177, 1162, 1140,
98442  /*   290 */  1153, 1184, 1182, 1102, 1124, 1103, 1095, 1090, 1089, 1093,
98443  /*   300 */  1112, 1115, 1086, 1105, 1092, 1087, 1068,  962,  955,  957,
98444  /*   310 */  1031, 1023, 1030,
98445 };
98446 static const YYACTIONTYPE yy_default[] = {
98447  /*     0 */   635,  870,  959,  959,  959,  870,  899,  899,  959,  759,
98448  /*    10 */   959,  959,  959,  959,  868,  959,  959,  933,  959,  959,
98449  /*    20 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
98450  /*    30 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
98451  /*    40 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
98452  /*    50 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
98453  /*    60 */   959,  959,  959,  959,  899,  899,  674,  763,  794,  959,
98454  /*    70 */   959,  959,  959,  959,  959,  959,  959,  932,  934,  809,
98455  /*    80 */   808,  802,  801,  912,  774,  799,  792,  785,  796,  871,
98456  /*    90 */   864,  865,  863,  867,  872,  959,  795,  831,  848,  830,
98457  /*   100 */   842,  847,  854,  846,  843,  833,  832,  666,  834,  835,
98458  /*   110 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
98459  /*   120 */   959,  959,  959,  959,  959,  959,  661,  728,  959,  959,
98460  /*   130 */   959,  959,  959,  959,  836,  837,  851,  850,  849,  959,
98461  /*   140 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
98462  /*   150 */   959,  939,  937,  959,  883,  959,  959,  959,  959,  959,
98463  /*   160 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
98464  /*   170 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
98465  /*   180 */   959,  641,  959,  759,  759,  759,  635,  959,  959,  959,
98466  /*   190 */   959,  951,  763,  753,  719,  959,  959,  959,  959,  959,
98467  /*   200 */   959,  959,  959,  959,  959,  959,  959,  804,  742,  922,
98468  /*   210 */   924,  959,  905,  740,  663,  761,  676,  751,  643,  798,
98469  /*   220 */   776,  776,  917,  798,  917,  700,  959,  788,  959,  788,
98470  /*   230 */   697,  788,  776,  788,  788,  866,  959,  959,  959,  760,
98471  /*   240 */   751,  959,  944,  767,  767,  936,  936,  767,  810,  732,
98472  /*   250 */   798,  739,  739,  739,  739,  767,  798,  810,  732,  732,
98473  /*   260 */   767,  658,  911,  909,  767,  767,  658,  767,  658,  767,
98474  /*   270 */   658,  876,  730,  730,  730,  715,  880,  880,  876,  730,
98475  /*   280 */   700,  730,  715,  730,  730,  780,  775,  780,  775,  780,
98476  /*   290 */   775,  767,  767,  959,  793,  781,  791,  789,  798,  959,
98477  /*   300 */   718,  651,  651,  640,  640,  640,  640,  956,  956,  951,
98478  /*   310 */   702,  702,  684,  959,  959,  959,  959,  959,  959,  959,
98479  /*   320 */   885,  959,  959,  959,  959,  959,  959,  959,  959,  959,
98480  /*   330 */   959,  959,  959,  959,  636,  946,  959,  959,  943,  959,
98481  /*   340 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
98482  /*   350 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  915,
98483  /*   360 */   959,  959,  959,  959,  959,  959,  908,  907,  959,  959,
98484  /*   370 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
98485  /*   380 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
98486  /*   390 */   959,  959,  959,  959,  790,  959,  782,  959,  869,  959,
98487  /*   400 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  745,
98488  /*   410 */   819,  959,  818,  822,  817,  668,  959,  649,  959,  632,
98489  /*   420 */   637,  955,  958,  957,  954,  953,  952,  947,  945,  942,
98490  /*   430 */   941,  940,  938,  935,  931,  889,  887,  894,  893,  892,
98491  /*   440 */   891,  890,  888,  886,  884,  805,  803,  800,  797,  930,
98492  /*   450 */   882,  741,  738,  737,  657,  948,  914,  923,  921,  811,
98493  /*   460 */   920,  919,  918,  916,  913,  900,  807,  806,  733,  874,
98494  /*   470 */   873,  660,  904,  903,  902,  906,  910,  901,  769,  659,
98495  /*   480 */   656,  665,  722,  721,  729,  727,  726,  725,  724,  723,
98496  /*   490 */   720,  667,  675,  686,  714,  699,  698,  879,  881,  878,
98497  /*   500 */   877,  707,  706,  712,  711,  710,  709,  708,  705,  704,
98498  /*   510 */   703,  696,  695,  701,  694,  717,  716,  713,  693,  736,
98499  /*   520 */   735,  734,  731,  692,  691,  690,  822,  689,  688,  828,
98500  /*   530 */   827,  815,  858,  756,  755,  754,  766,  765,  778,  777,
98501  /*   540 */   813,  812,  779,  764,  758,  757,  773,  772,  771,  770,
98502  /*   550 */   762,  752,  784,  787,  786,  783,  860,  768,  857,  929,
98503  /*   560 */   928,  927,  926,  925,  862,  861,  829,  826,  679,  680,
98504  /*   570 */   898,  896,  897,  895,  682,  681,  678,  677,  859,  747,
98505  /*   580 */   746,  855,  852,  844,  840,  856,  853,  845,  841,  839,
98506  /*   590 */   838,  824,  823,  821,  820,  816,  825,  670,  748,  744,
98507  /*   600 */   743,  814,  750,  749,  687,  685,  683,  664,  662,  655,
98508  /*   610 */   653,  652,  654,  650,  648,  647,  646,  645,  644,  673,
98509  /*   620 */   672,  671,  669,  668,  642,  639,  638,  634,  633,  631,
98510 };
98511
98512 /* The next table maps tokens into fallback tokens.  If a construct
98513 ** like the following:
98514 ** 
98515 **      %fallback ID X Y Z.
98516 **
98517 ** appears in the grammar, then ID becomes a fallback token for X, Y,
98518 ** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
98519 ** but it does not parse, the type of the token is changed to ID and
98520 ** the parse is retried before an error is thrown.
98521 */
98522 #ifdef YYFALLBACK
98523 static const YYCODETYPE yyFallback[] = {
98524     0,  /*          $ => nothing */
98525     0,  /*       SEMI => nothing */
98526    26,  /*    EXPLAIN => ID */
98527    26,  /*      QUERY => ID */
98528    26,  /*       PLAN => ID */
98529    26,  /*      BEGIN => ID */
98530     0,  /* TRANSACTION => nothing */
98531    26,  /*   DEFERRED => ID */
98532    26,  /*  IMMEDIATE => ID */
98533    26,  /*  EXCLUSIVE => ID */
98534     0,  /*     COMMIT => nothing */
98535    26,  /*        END => ID */
98536    26,  /*   ROLLBACK => ID */
98537    26,  /*  SAVEPOINT => ID */
98538    26,  /*    RELEASE => ID */
98539     0,  /*         TO => nothing */
98540     0,  /*      TABLE => nothing */
98541     0,  /*     CREATE => nothing */
98542    26,  /*         IF => ID */
98543     0,  /*        NOT => nothing */
98544     0,  /*     EXISTS => nothing */
98545    26,  /*       TEMP => ID */
98546     0,  /*         LP => nothing */
98547     0,  /*         RP => nothing */
98548     0,  /*         AS => nothing */
98549     0,  /*      COMMA => nothing */
98550     0,  /*         ID => nothing */
98551     0,  /*    INDEXED => nothing */
98552    26,  /*      ABORT => ID */
98553    26,  /*     ACTION => ID */
98554    26,  /*      AFTER => ID */
98555    26,  /*    ANALYZE => ID */
98556    26,  /*        ASC => ID */
98557    26,  /*     ATTACH => ID */
98558    26,  /*     BEFORE => ID */
98559    26,  /*         BY => ID */
98560    26,  /*    CASCADE => ID */
98561    26,  /*       CAST => ID */
98562    26,  /*   COLUMNKW => ID */
98563    26,  /*   CONFLICT => ID */
98564    26,  /*   DATABASE => ID */
98565    26,  /*       DESC => ID */
98566    26,  /*     DETACH => ID */
98567    26,  /*       EACH => ID */
98568    26,  /*       FAIL => ID */
98569    26,  /*        FOR => ID */
98570    26,  /*     IGNORE => ID */
98571    26,  /*  INITIALLY => ID */
98572    26,  /*    INSTEAD => ID */
98573    26,  /*    LIKE_KW => ID */
98574    26,  /*      MATCH => ID */
98575    26,  /*         NO => ID */
98576    26,  /*        KEY => ID */
98577    26,  /*         OF => ID */
98578    26,  /*     OFFSET => ID */
98579    26,  /*     PRAGMA => ID */
98580    26,  /*      RAISE => ID */
98581    26,  /*    REPLACE => ID */
98582    26,  /*   RESTRICT => ID */
98583    26,  /*        ROW => ID */
98584    26,  /*    TRIGGER => ID */
98585    26,  /*     VACUUM => ID */
98586    26,  /*       VIEW => ID */
98587    26,  /*    VIRTUAL => ID */
98588    26,  /*    REINDEX => ID */
98589    26,  /*     RENAME => ID */
98590    26,  /*   CTIME_KW => ID */
98591 };
98592 #endif /* YYFALLBACK */
98593
98594 /* The following structure represents a single element of the
98595 ** parser's stack.  Information stored includes:
98596 **
98597 **   +  The state number for the parser at this level of the stack.
98598 **
98599 **   +  The value of the token stored at this level of the stack.
98600 **      (In other words, the "major" token.)
98601 **
98602 **   +  The semantic value stored at this level of the stack.  This is
98603 **      the information used by the action routines in the grammar.
98604 **      It is sometimes called the "minor" token.
98605 */
98606 struct yyStackEntry {
98607   YYACTIONTYPE stateno;  /* The state-number */
98608   YYCODETYPE major;      /* The major token value.  This is the code
98609                          ** number for the token at this stack level */
98610   YYMINORTYPE minor;     /* The user-supplied minor token value.  This
98611                          ** is the value of the token  */
98612 };
98613 typedef struct yyStackEntry yyStackEntry;
98614
98615 /* The state of the parser is completely contained in an instance of
98616 ** the following structure */
98617 struct yyParser {
98618   int yyidx;                    /* Index of top element in stack */
98619 #ifdef YYTRACKMAXSTACKDEPTH
98620   int yyidxMax;                 /* Maximum value of yyidx */
98621 #endif
98622   int yyerrcnt;                 /* Shifts left before out of the error */
98623   sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
98624 #if YYSTACKDEPTH<=0
98625   int yystksz;                  /* Current side of the stack */
98626   yyStackEntry *yystack;        /* The parser's stack */
98627 #else
98628   yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
98629 #endif
98630 };
98631 typedef struct yyParser yyParser;
98632
98633 #ifndef NDEBUG
98634 static FILE *yyTraceFILE = 0;
98635 static char *yyTracePrompt = 0;
98636 #endif /* NDEBUG */
98637
98638 #ifndef NDEBUG
98639 /* 
98640 ** Turn parser tracing on by giving a stream to which to write the trace
98641 ** and a prompt to preface each trace message.  Tracing is turned off
98642 ** by making either argument NULL 
98643 **
98644 ** Inputs:
98645 ** <ul>
98646 ** <li> A FILE* to which trace output should be written.
98647 **      If NULL, then tracing is turned off.
98648 ** <li> A prefix string written at the beginning of every
98649 **      line of trace output.  If NULL, then tracing is
98650 **      turned off.
98651 ** </ul>
98652 **
98653 ** Outputs:
98654 ** None.
98655 */
98656 SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
98657   yyTraceFILE = TraceFILE;
98658   yyTracePrompt = zTracePrompt;
98659   if( yyTraceFILE==0 ) yyTracePrompt = 0;
98660   else if( yyTracePrompt==0 ) yyTraceFILE = 0;
98661 }
98662 #endif /* NDEBUG */
98663
98664 #ifndef NDEBUG
98665 /* For tracing shifts, the names of all terminals and nonterminals
98666 ** are required.  The following table supplies these names */
98667 static const char *const yyTokenName[] = { 
98668   "$",             "SEMI",          "EXPLAIN",       "QUERY",       
98669   "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",    
98670   "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",         
98671   "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",          
98672   "TABLE",         "CREATE",        "IF",            "NOT",         
98673   "EXISTS",        "TEMP",          "LP",            "RP",          
98674   "AS",            "COMMA",         "ID",            "INDEXED",     
98675   "ABORT",         "ACTION",        "AFTER",         "ANALYZE",     
98676   "ASC",           "ATTACH",        "BEFORE",        "BY",          
98677   "CASCADE",       "CAST",          "COLUMNKW",      "CONFLICT",    
98678   "DATABASE",      "DESC",          "DETACH",        "EACH",        
98679   "FAIL",          "FOR",           "IGNORE",        "INITIALLY",   
98680   "INSTEAD",       "LIKE_KW",       "MATCH",         "NO",          
98681   "KEY",           "OF",            "OFFSET",        "PRAGMA",      
98682   "RAISE",         "REPLACE",       "RESTRICT",      "ROW",         
98683   "TRIGGER",       "VACUUM",        "VIEW",          "VIRTUAL",     
98684   "REINDEX",       "RENAME",        "CTIME_KW",      "ANY",         
98685   "OR",            "AND",           "IS",            "BETWEEN",     
98686   "IN",            "ISNULL",        "NOTNULL",       "NE",          
98687   "EQ",            "GT",            "LE",            "LT",          
98688   "GE",            "ESCAPE",        "BITAND",        "BITOR",       
98689   "LSHIFT",        "RSHIFT",        "PLUS",          "MINUS",       
98690   "STAR",          "SLASH",         "REM",           "CONCAT",      
98691   "COLLATE",       "BITNOT",        "STRING",        "JOIN_KW",     
98692   "CONSTRAINT",    "DEFAULT",       "NULL",          "PRIMARY",     
98693   "UNIQUE",        "CHECK",         "REFERENCES",    "AUTOINCR",    
98694   "ON",            "INSERT",        "DELETE",        "UPDATE",      
98695   "SET",           "DEFERRABLE",    "FOREIGN",       "DROP",        
98696   "UNION",         "ALL",           "EXCEPT",        "INTERSECT",   
98697   "SELECT",        "DISTINCT",      "DOT",           "FROM",        
98698   "JOIN",          "USING",         "ORDER",         "GROUP",       
98699   "HAVING",        "LIMIT",         "WHERE",         "INTO",        
98700   "VALUES",        "INTEGER",       "FLOAT",         "BLOB",        
98701   "REGISTER",      "VARIABLE",      "CASE",          "WHEN",        
98702   "THEN",          "ELSE",          "INDEX",         "ALTER",       
98703   "ADD",           "error",         "input",         "cmdlist",     
98704   "ecmd",          "explain",       "cmdx",          "cmd",         
98705   "transtype",     "trans_opt",     "nm",            "savepoint_opt",
98706   "create_table",  "create_table_args",  "createkw",      "temp",        
98707   "ifnotexists",   "dbnm",          "columnlist",    "conslist_opt",
98708   "select",        "column",        "columnid",      "type",        
98709   "carglist",      "id",            "ids",           "typetoken",   
98710   "typename",      "signed",        "plus_num",      "minus_num",   
98711   "carg",          "ccons",         "term",          "expr",        
98712   "onconf",        "sortorder",     "autoinc",       "idxlist_opt", 
98713   "refargs",       "defer_subclause",  "refarg",        "refact",      
98714   "init_deferred_pred_opt",  "conslist",      "tcons",         "idxlist",     
98715   "defer_subclause_opt",  "orconf",        "resolvetype",   "raisetype",   
98716   "ifexists",      "fullname",      "oneselect",     "multiselect_op",
98717   "distinct",      "selcollist",    "from",          "where_opt",   
98718   "groupby_opt",   "having_opt",    "orderby_opt",   "limit_opt",   
98719   "sclp",          "as",            "seltablist",    "stl_prefix",  
98720   "joinop",        "indexed_opt",   "on_opt",        "using_opt",   
98721   "joinop2",       "inscollist",    "sortlist",      "sortitem",    
98722   "nexprlist",     "setlist",       "insert_cmd",    "inscollist_opt",
98723   "itemlist",      "exprlist",      "likeop",        "between_op",  
98724   "in_op",         "case_operand",  "case_exprlist",  "case_else",   
98725   "uniqueflag",    "collate",       "nmnum",         "plus_opt",    
98726   "number",        "trigger_decl",  "trigger_cmd_list",  "trigger_time",
98727   "trigger_event",  "foreach_clause",  "when_clause",   "trigger_cmd", 
98728   "trnm",          "tridxby",       "database_kw_opt",  "key_opt",     
98729   "add_column_fullname",  "kwcolumn_opt",  "create_vtab",   "vtabarglist", 
98730   "vtabarg",       "vtabargtoken",  "lp",            "anylist",     
98731 };
98732 #endif /* NDEBUG */
98733
98734 #ifndef NDEBUG
98735 /* For tracing reduce actions, the names of all rules are required.
98736 */
98737 static const char *const yyRuleName[] = {
98738  /*   0 */ "input ::= cmdlist",
98739  /*   1 */ "cmdlist ::= cmdlist ecmd",
98740  /*   2 */ "cmdlist ::= ecmd",
98741  /*   3 */ "ecmd ::= SEMI",
98742  /*   4 */ "ecmd ::= explain cmdx SEMI",
98743  /*   5 */ "explain ::=",
98744  /*   6 */ "explain ::= EXPLAIN",
98745  /*   7 */ "explain ::= EXPLAIN QUERY PLAN",
98746  /*   8 */ "cmdx ::= cmd",
98747  /*   9 */ "cmd ::= BEGIN transtype trans_opt",
98748  /*  10 */ "trans_opt ::=",
98749  /*  11 */ "trans_opt ::= TRANSACTION",
98750  /*  12 */ "trans_opt ::= TRANSACTION nm",
98751  /*  13 */ "transtype ::=",
98752  /*  14 */ "transtype ::= DEFERRED",
98753  /*  15 */ "transtype ::= IMMEDIATE",
98754  /*  16 */ "transtype ::= EXCLUSIVE",
98755  /*  17 */ "cmd ::= COMMIT trans_opt",
98756  /*  18 */ "cmd ::= END trans_opt",
98757  /*  19 */ "cmd ::= ROLLBACK trans_opt",
98758  /*  20 */ "savepoint_opt ::= SAVEPOINT",
98759  /*  21 */ "savepoint_opt ::=",
98760  /*  22 */ "cmd ::= SAVEPOINT nm",
98761  /*  23 */ "cmd ::= RELEASE savepoint_opt nm",
98762  /*  24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
98763  /*  25 */ "cmd ::= create_table create_table_args",
98764  /*  26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
98765  /*  27 */ "createkw ::= CREATE",
98766  /*  28 */ "ifnotexists ::=",
98767  /*  29 */ "ifnotexists ::= IF NOT EXISTS",
98768  /*  30 */ "temp ::= TEMP",
98769  /*  31 */ "temp ::=",
98770  /*  32 */ "create_table_args ::= LP columnlist conslist_opt RP",
98771  /*  33 */ "create_table_args ::= AS select",
98772  /*  34 */ "columnlist ::= columnlist COMMA column",
98773  /*  35 */ "columnlist ::= column",
98774  /*  36 */ "column ::= columnid type carglist",
98775  /*  37 */ "columnid ::= nm",
98776  /*  38 */ "id ::= ID",
98777  /*  39 */ "id ::= INDEXED",
98778  /*  40 */ "ids ::= ID|STRING",
98779  /*  41 */ "nm ::= id",
98780  /*  42 */ "nm ::= STRING",
98781  /*  43 */ "nm ::= JOIN_KW",
98782  /*  44 */ "type ::=",
98783  /*  45 */ "type ::= typetoken",
98784  /*  46 */ "typetoken ::= typename",
98785  /*  47 */ "typetoken ::= typename LP signed RP",
98786  /*  48 */ "typetoken ::= typename LP signed COMMA signed RP",
98787  /*  49 */ "typename ::= ids",
98788  /*  50 */ "typename ::= typename ids",
98789  /*  51 */ "signed ::= plus_num",
98790  /*  52 */ "signed ::= minus_num",
98791  /*  53 */ "carglist ::= carglist carg",
98792  /*  54 */ "carglist ::=",
98793  /*  55 */ "carg ::= CONSTRAINT nm ccons",
98794  /*  56 */ "carg ::= ccons",
98795  /*  57 */ "ccons ::= DEFAULT term",
98796  /*  58 */ "ccons ::= DEFAULT LP expr RP",
98797  /*  59 */ "ccons ::= DEFAULT PLUS term",
98798  /*  60 */ "ccons ::= DEFAULT MINUS term",
98799  /*  61 */ "ccons ::= DEFAULT id",
98800  /*  62 */ "ccons ::= NULL onconf",
98801  /*  63 */ "ccons ::= NOT NULL onconf",
98802  /*  64 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
98803  /*  65 */ "ccons ::= UNIQUE onconf",
98804  /*  66 */ "ccons ::= CHECK LP expr RP",
98805  /*  67 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
98806  /*  68 */ "ccons ::= defer_subclause",
98807  /*  69 */ "ccons ::= COLLATE ids",
98808  /*  70 */ "autoinc ::=",
98809  /*  71 */ "autoinc ::= AUTOINCR",
98810  /*  72 */ "refargs ::=",
98811  /*  73 */ "refargs ::= refargs refarg",
98812  /*  74 */ "refarg ::= MATCH nm",
98813  /*  75 */ "refarg ::= ON INSERT refact",
98814  /*  76 */ "refarg ::= ON DELETE refact",
98815  /*  77 */ "refarg ::= ON UPDATE refact",
98816  /*  78 */ "refact ::= SET NULL",
98817  /*  79 */ "refact ::= SET DEFAULT",
98818  /*  80 */ "refact ::= CASCADE",
98819  /*  81 */ "refact ::= RESTRICT",
98820  /*  82 */ "refact ::= NO ACTION",
98821  /*  83 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
98822  /*  84 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
98823  /*  85 */ "init_deferred_pred_opt ::=",
98824  /*  86 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
98825  /*  87 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
98826  /*  88 */ "conslist_opt ::=",
98827  /*  89 */ "conslist_opt ::= COMMA conslist",
98828  /*  90 */ "conslist ::= conslist COMMA tcons",
98829  /*  91 */ "conslist ::= conslist tcons",
98830  /*  92 */ "conslist ::= tcons",
98831  /*  93 */ "tcons ::= CONSTRAINT nm",
98832  /*  94 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
98833  /*  95 */ "tcons ::= UNIQUE LP idxlist RP onconf",
98834  /*  96 */ "tcons ::= CHECK LP expr RP onconf",
98835  /*  97 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
98836  /*  98 */ "defer_subclause_opt ::=",
98837  /*  99 */ "defer_subclause_opt ::= defer_subclause",
98838  /* 100 */ "onconf ::=",
98839  /* 101 */ "onconf ::= ON CONFLICT resolvetype",
98840  /* 102 */ "orconf ::=",
98841  /* 103 */ "orconf ::= OR resolvetype",
98842  /* 104 */ "resolvetype ::= raisetype",
98843  /* 105 */ "resolvetype ::= IGNORE",
98844  /* 106 */ "resolvetype ::= REPLACE",
98845  /* 107 */ "cmd ::= DROP TABLE ifexists fullname",
98846  /* 108 */ "ifexists ::= IF EXISTS",
98847  /* 109 */ "ifexists ::=",
98848  /* 110 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
98849  /* 111 */ "cmd ::= DROP VIEW ifexists fullname",
98850  /* 112 */ "cmd ::= select",
98851  /* 113 */ "select ::= oneselect",
98852  /* 114 */ "select ::= select multiselect_op oneselect",
98853  /* 115 */ "multiselect_op ::= UNION",
98854  /* 116 */ "multiselect_op ::= UNION ALL",
98855  /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
98856  /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
98857  /* 119 */ "distinct ::= DISTINCT",
98858  /* 120 */ "distinct ::= ALL",
98859  /* 121 */ "distinct ::=",
98860  /* 122 */ "sclp ::= selcollist COMMA",
98861  /* 123 */ "sclp ::=",
98862  /* 124 */ "selcollist ::= sclp expr as",
98863  /* 125 */ "selcollist ::= sclp STAR",
98864  /* 126 */ "selcollist ::= sclp nm DOT STAR",
98865  /* 127 */ "as ::= AS nm",
98866  /* 128 */ "as ::= ids",
98867  /* 129 */ "as ::=",
98868  /* 130 */ "from ::=",
98869  /* 131 */ "from ::= FROM seltablist",
98870  /* 132 */ "stl_prefix ::= seltablist joinop",
98871  /* 133 */ "stl_prefix ::=",
98872  /* 134 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
98873  /* 135 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
98874  /* 136 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
98875  /* 137 */ "dbnm ::=",
98876  /* 138 */ "dbnm ::= DOT nm",
98877  /* 139 */ "fullname ::= nm dbnm",
98878  /* 140 */ "joinop ::= COMMA|JOIN",
98879  /* 141 */ "joinop ::= JOIN_KW JOIN",
98880  /* 142 */ "joinop ::= JOIN_KW nm JOIN",
98881  /* 143 */ "joinop ::= JOIN_KW nm nm JOIN",
98882  /* 144 */ "on_opt ::= ON expr",
98883  /* 145 */ "on_opt ::=",
98884  /* 146 */ "indexed_opt ::=",
98885  /* 147 */ "indexed_opt ::= INDEXED BY nm",
98886  /* 148 */ "indexed_opt ::= NOT INDEXED",
98887  /* 149 */ "using_opt ::= USING LP inscollist RP",
98888  /* 150 */ "using_opt ::=",
98889  /* 151 */ "orderby_opt ::=",
98890  /* 152 */ "orderby_opt ::= ORDER BY sortlist",
98891  /* 153 */ "sortlist ::= sortlist COMMA sortitem sortorder",
98892  /* 154 */ "sortlist ::= sortitem sortorder",
98893  /* 155 */ "sortitem ::= expr",
98894  /* 156 */ "sortorder ::= ASC",
98895  /* 157 */ "sortorder ::= DESC",
98896  /* 158 */ "sortorder ::=",
98897  /* 159 */ "groupby_opt ::=",
98898  /* 160 */ "groupby_opt ::= GROUP BY nexprlist",
98899  /* 161 */ "having_opt ::=",
98900  /* 162 */ "having_opt ::= HAVING expr",
98901  /* 163 */ "limit_opt ::=",
98902  /* 164 */ "limit_opt ::= LIMIT expr",
98903  /* 165 */ "limit_opt ::= LIMIT expr OFFSET expr",
98904  /* 166 */ "limit_opt ::= LIMIT expr COMMA expr",
98905  /* 167 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
98906  /* 168 */ "where_opt ::=",
98907  /* 169 */ "where_opt ::= WHERE expr",
98908  /* 170 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
98909  /* 171 */ "setlist ::= setlist COMMA nm EQ expr",
98910  /* 172 */ "setlist ::= nm EQ expr",
98911  /* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP",
98912  /* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
98913  /* 175 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
98914  /* 176 */ "insert_cmd ::= INSERT orconf",
98915  /* 177 */ "insert_cmd ::= REPLACE",
98916  /* 178 */ "itemlist ::= itemlist COMMA expr",
98917  /* 179 */ "itemlist ::= expr",
98918  /* 180 */ "inscollist_opt ::=",
98919  /* 181 */ "inscollist_opt ::= LP inscollist RP",
98920  /* 182 */ "inscollist ::= inscollist COMMA nm",
98921  /* 183 */ "inscollist ::= nm",
98922  /* 184 */ "expr ::= term",
98923  /* 185 */ "expr ::= LP expr RP",
98924  /* 186 */ "term ::= NULL",
98925  /* 187 */ "expr ::= id",
98926  /* 188 */ "expr ::= JOIN_KW",
98927  /* 189 */ "expr ::= nm DOT nm",
98928  /* 190 */ "expr ::= nm DOT nm DOT nm",
98929  /* 191 */ "term ::= INTEGER|FLOAT|BLOB",
98930  /* 192 */ "term ::= STRING",
98931  /* 193 */ "expr ::= REGISTER",
98932  /* 194 */ "expr ::= VARIABLE",
98933  /* 195 */ "expr ::= expr COLLATE ids",
98934  /* 196 */ "expr ::= CAST LP expr AS typetoken RP",
98935  /* 197 */ "expr ::= ID LP distinct exprlist RP",
98936  /* 198 */ "expr ::= ID LP STAR RP",
98937  /* 199 */ "term ::= CTIME_KW",
98938  /* 200 */ "expr ::= expr AND expr",
98939  /* 201 */ "expr ::= expr OR expr",
98940  /* 202 */ "expr ::= expr LT|GT|GE|LE expr",
98941  /* 203 */ "expr ::= expr EQ|NE expr",
98942  /* 204 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
98943  /* 205 */ "expr ::= expr PLUS|MINUS expr",
98944  /* 206 */ "expr ::= expr STAR|SLASH|REM expr",
98945  /* 207 */ "expr ::= expr CONCAT expr",
98946  /* 208 */ "likeop ::= LIKE_KW",
98947  /* 209 */ "likeop ::= NOT LIKE_KW",
98948  /* 210 */ "likeop ::= MATCH",
98949  /* 211 */ "likeop ::= NOT MATCH",
98950  /* 212 */ "expr ::= expr likeop expr",
98951  /* 213 */ "expr ::= expr likeop expr ESCAPE expr",
98952  /* 214 */ "expr ::= expr ISNULL|NOTNULL",
98953  /* 215 */ "expr ::= expr NOT NULL",
98954  /* 216 */ "expr ::= expr IS expr",
98955  /* 217 */ "expr ::= expr IS NOT expr",
98956  /* 218 */ "expr ::= NOT expr",
98957  /* 219 */ "expr ::= BITNOT expr",
98958  /* 220 */ "expr ::= MINUS expr",
98959  /* 221 */ "expr ::= PLUS expr",
98960  /* 222 */ "between_op ::= BETWEEN",
98961  /* 223 */ "between_op ::= NOT BETWEEN",
98962  /* 224 */ "expr ::= expr between_op expr AND expr",
98963  /* 225 */ "in_op ::= IN",
98964  /* 226 */ "in_op ::= NOT IN",
98965  /* 227 */ "expr ::= expr in_op LP exprlist RP",
98966  /* 228 */ "expr ::= LP select RP",
98967  /* 229 */ "expr ::= expr in_op LP select RP",
98968  /* 230 */ "expr ::= expr in_op nm dbnm",
98969  /* 231 */ "expr ::= EXISTS LP select RP",
98970  /* 232 */ "expr ::= CASE case_operand case_exprlist case_else END",
98971  /* 233 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
98972  /* 234 */ "case_exprlist ::= WHEN expr THEN expr",
98973  /* 235 */ "case_else ::= ELSE expr",
98974  /* 236 */ "case_else ::=",
98975  /* 237 */ "case_operand ::= expr",
98976  /* 238 */ "case_operand ::=",
98977  /* 239 */ "exprlist ::= nexprlist",
98978  /* 240 */ "exprlist ::=",
98979  /* 241 */ "nexprlist ::= nexprlist COMMA expr",
98980  /* 242 */ "nexprlist ::= expr",
98981  /* 243 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
98982  /* 244 */ "uniqueflag ::= UNIQUE",
98983  /* 245 */ "uniqueflag ::=",
98984  /* 246 */ "idxlist_opt ::=",
98985  /* 247 */ "idxlist_opt ::= LP idxlist RP",
98986  /* 248 */ "idxlist ::= idxlist COMMA nm collate sortorder",
98987  /* 249 */ "idxlist ::= nm collate sortorder",
98988  /* 250 */ "collate ::=",
98989  /* 251 */ "collate ::= COLLATE ids",
98990  /* 252 */ "cmd ::= DROP INDEX ifexists fullname",
98991  /* 253 */ "cmd ::= VACUUM",
98992  /* 254 */ "cmd ::= VACUUM nm",
98993  /* 255 */ "cmd ::= PRAGMA nm dbnm",
98994  /* 256 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
98995  /* 257 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
98996  /* 258 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
98997  /* 259 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
98998  /* 260 */ "nmnum ::= plus_num",
98999  /* 261 */ "nmnum ::= nm",
99000  /* 262 */ "nmnum ::= ON",
99001  /* 263 */ "nmnum ::= DELETE",
99002  /* 264 */ "nmnum ::= DEFAULT",
99003  /* 265 */ "plus_num ::= plus_opt number",
99004  /* 266 */ "minus_num ::= MINUS number",
99005  /* 267 */ "number ::= INTEGER|FLOAT",
99006  /* 268 */ "plus_opt ::= PLUS",
99007  /* 269 */ "plus_opt ::=",
99008  /* 270 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
99009  /* 271 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
99010  /* 272 */ "trigger_time ::= BEFORE",
99011  /* 273 */ "trigger_time ::= AFTER",
99012  /* 274 */ "trigger_time ::= INSTEAD OF",
99013  /* 275 */ "trigger_time ::=",
99014  /* 276 */ "trigger_event ::= DELETE|INSERT",
99015  /* 277 */ "trigger_event ::= UPDATE",
99016  /* 278 */ "trigger_event ::= UPDATE OF inscollist",
99017  /* 279 */ "foreach_clause ::=",
99018  /* 280 */ "foreach_clause ::= FOR EACH ROW",
99019  /* 281 */ "when_clause ::=",
99020  /* 282 */ "when_clause ::= WHEN expr",
99021  /* 283 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
99022  /* 284 */ "trigger_cmd_list ::= trigger_cmd SEMI",
99023  /* 285 */ "trnm ::= nm",
99024  /* 286 */ "trnm ::= nm DOT nm",
99025  /* 287 */ "tridxby ::=",
99026  /* 288 */ "tridxby ::= INDEXED BY nm",
99027  /* 289 */ "tridxby ::= NOT INDEXED",
99028  /* 290 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
99029  /* 291 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP",
99030  /* 292 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
99031  /* 293 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
99032  /* 294 */ "trigger_cmd ::= select",
99033  /* 295 */ "expr ::= RAISE LP IGNORE RP",
99034  /* 296 */ "expr ::= RAISE LP raisetype COMMA nm RP",
99035  /* 297 */ "raisetype ::= ROLLBACK",
99036  /* 298 */ "raisetype ::= ABORT",
99037  /* 299 */ "raisetype ::= FAIL",
99038  /* 300 */ "cmd ::= DROP TRIGGER ifexists fullname",
99039  /* 301 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
99040  /* 302 */ "cmd ::= DETACH database_kw_opt expr",
99041  /* 303 */ "key_opt ::=",
99042  /* 304 */ "key_opt ::= KEY expr",
99043  /* 305 */ "database_kw_opt ::= DATABASE",
99044  /* 306 */ "database_kw_opt ::=",
99045  /* 307 */ "cmd ::= REINDEX",
99046  /* 308 */ "cmd ::= REINDEX nm dbnm",
99047  /* 309 */ "cmd ::= ANALYZE",
99048  /* 310 */ "cmd ::= ANALYZE nm dbnm",
99049  /* 311 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
99050  /* 312 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
99051  /* 313 */ "add_column_fullname ::= fullname",
99052  /* 314 */ "kwcolumn_opt ::=",
99053  /* 315 */ "kwcolumn_opt ::= COLUMNKW",
99054  /* 316 */ "cmd ::= create_vtab",
99055  /* 317 */ "cmd ::= create_vtab LP vtabarglist RP",
99056  /* 318 */ "create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm",
99057  /* 319 */ "vtabarglist ::= vtabarg",
99058  /* 320 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
99059  /* 321 */ "vtabarg ::=",
99060  /* 322 */ "vtabarg ::= vtabarg vtabargtoken",
99061  /* 323 */ "vtabargtoken ::= ANY",
99062  /* 324 */ "vtabargtoken ::= lp anylist RP",
99063  /* 325 */ "lp ::= LP",
99064  /* 326 */ "anylist ::=",
99065  /* 327 */ "anylist ::= anylist LP anylist RP",
99066  /* 328 */ "anylist ::= anylist ANY",
99067 };
99068 #endif /* NDEBUG */
99069
99070
99071 #if YYSTACKDEPTH<=0
99072 /*
99073 ** Try to increase the size of the parser stack.
99074 */
99075 static void yyGrowStack(yyParser *p){
99076   int newSize;
99077   yyStackEntry *pNew;
99078
99079   newSize = p->yystksz*2 + 100;
99080   pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
99081   if( pNew ){
99082     p->yystack = pNew;
99083     p->yystksz = newSize;
99084 #ifndef NDEBUG
99085     if( yyTraceFILE ){
99086       fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
99087               yyTracePrompt, p->yystksz);
99088     }
99089 #endif
99090   }
99091 }
99092 #endif
99093
99094 /* 
99095 ** This function allocates a new parser.
99096 ** The only argument is a pointer to a function which works like
99097 ** malloc.
99098 **
99099 ** Inputs:
99100 ** A pointer to the function used to allocate memory.
99101 **
99102 ** Outputs:
99103 ** A pointer to a parser.  This pointer is used in subsequent calls
99104 ** to sqlite3Parser and sqlite3ParserFree.
99105 */
99106 SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
99107   yyParser *pParser;
99108   pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
99109   if( pParser ){
99110     pParser->yyidx = -1;
99111 #ifdef YYTRACKMAXSTACKDEPTH
99112     pParser->yyidxMax = 0;
99113 #endif
99114 #if YYSTACKDEPTH<=0
99115     pParser->yystack = NULL;
99116     pParser->yystksz = 0;
99117     yyGrowStack(pParser);
99118 #endif
99119   }
99120   return pParser;
99121 }
99122
99123 /* The following function deletes the value associated with a
99124 ** symbol.  The symbol can be either a terminal or nonterminal.
99125 ** "yymajor" is the symbol code, and "yypminor" is a pointer to
99126 ** the value.
99127 */
99128 static void yy_destructor(
99129   yyParser *yypParser,    /* The parser */
99130   YYCODETYPE yymajor,     /* Type code for object to destroy */
99131   YYMINORTYPE *yypminor   /* The object to be destroyed */
99132 ){
99133   sqlite3ParserARG_FETCH;
99134   switch( yymajor ){
99135     /* Here is inserted the actions which take place when a
99136     ** terminal or non-terminal is destroyed.  This can happen
99137     ** when the symbol is popped from the stack during a
99138     ** reduce or during error processing or when a parser is 
99139     ** being destroyed before it is finished parsing.
99140     **
99141     ** Note: during a reduce, the only symbols destroyed are those
99142     ** which appear on the RHS of the rule, but which are not used
99143     ** inside the C code.
99144     */
99145     case 160: /* select */
99146     case 194: /* oneselect */
99147 {
99148 sqlite3SelectDelete(pParse->db, (yypminor->yy387));
99149 }
99150       break;
99151     case 174: /* term */
99152     case 175: /* expr */
99153 {
99154 sqlite3ExprDelete(pParse->db, (yypminor->yy118).pExpr);
99155 }
99156       break;
99157     case 179: /* idxlist_opt */
99158     case 187: /* idxlist */
99159     case 197: /* selcollist */
99160     case 200: /* groupby_opt */
99161     case 202: /* orderby_opt */
99162     case 204: /* sclp */
99163     case 214: /* sortlist */
99164     case 216: /* nexprlist */
99165     case 217: /* setlist */
99166     case 220: /* itemlist */
99167     case 221: /* exprlist */
99168     case 226: /* case_exprlist */
99169 {
99170 sqlite3ExprListDelete(pParse->db, (yypminor->yy322));
99171 }
99172       break;
99173     case 193: /* fullname */
99174     case 198: /* from */
99175     case 206: /* seltablist */
99176     case 207: /* stl_prefix */
99177 {
99178 sqlite3SrcListDelete(pParse->db, (yypminor->yy259));
99179 }
99180       break;
99181     case 199: /* where_opt */
99182     case 201: /* having_opt */
99183     case 210: /* on_opt */
99184     case 215: /* sortitem */
99185     case 225: /* case_operand */
99186     case 227: /* case_else */
99187     case 238: /* when_clause */
99188     case 243: /* key_opt */
99189 {
99190 sqlite3ExprDelete(pParse->db, (yypminor->yy314));
99191 }
99192       break;
99193     case 211: /* using_opt */
99194     case 213: /* inscollist */
99195     case 219: /* inscollist_opt */
99196 {
99197 sqlite3IdListDelete(pParse->db, (yypminor->yy384));
99198 }
99199       break;
99200     case 234: /* trigger_cmd_list */
99201     case 239: /* trigger_cmd */
99202 {
99203 sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy203));
99204 }
99205       break;
99206     case 236: /* trigger_event */
99207 {
99208 sqlite3IdListDelete(pParse->db, (yypminor->yy90).b);
99209 }
99210       break;
99211     default:  break;   /* If no destructor action specified: do nothing */
99212   }
99213 }
99214
99215 /*
99216 ** Pop the parser's stack once.
99217 **
99218 ** If there is a destructor routine associated with the token which
99219 ** is popped from the stack, then call it.
99220 **
99221 ** Return the major token number for the symbol popped.
99222 */
99223 static int yy_pop_parser_stack(yyParser *pParser){
99224   YYCODETYPE yymajor;
99225   yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
99226
99227   /* There is no mechanism by which the parser stack can be popped below
99228   ** empty in SQLite.  */
99229   if( NEVER(pParser->yyidx<0) ) return 0;
99230 #ifndef NDEBUG
99231   if( yyTraceFILE && pParser->yyidx>=0 ){
99232     fprintf(yyTraceFILE,"%sPopping %s\n",
99233       yyTracePrompt,
99234       yyTokenName[yytos->major]);
99235   }
99236 #endif
99237   yymajor = yytos->major;
99238   yy_destructor(pParser, yymajor, &yytos->minor);
99239   pParser->yyidx--;
99240   return yymajor;
99241 }
99242
99243 /* 
99244 ** Deallocate and destroy a parser.  Destructors are all called for
99245 ** all stack elements before shutting the parser down.
99246 **
99247 ** Inputs:
99248 ** <ul>
99249 ** <li>  A pointer to the parser.  This should be a pointer
99250 **       obtained from sqlite3ParserAlloc.
99251 ** <li>  A pointer to a function used to reclaim memory obtained
99252 **       from malloc.
99253 ** </ul>
99254 */
99255 SQLITE_PRIVATE void sqlite3ParserFree(
99256   void *p,                    /* The parser to be deleted */
99257   void (*freeProc)(void*)     /* Function used to reclaim memory */
99258 ){
99259   yyParser *pParser = (yyParser*)p;
99260   /* In SQLite, we never try to destroy a parser that was not successfully
99261   ** created in the first place. */
99262   if( NEVER(pParser==0) ) return;
99263   while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
99264 #if YYSTACKDEPTH<=0
99265   free(pParser->yystack);
99266 #endif
99267   (*freeProc)((void*)pParser);
99268 }
99269
99270 /*
99271 ** Return the peak depth of the stack for a parser.
99272 */
99273 #ifdef YYTRACKMAXSTACKDEPTH
99274 SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
99275   yyParser *pParser = (yyParser*)p;
99276   return pParser->yyidxMax;
99277 }
99278 #endif
99279
99280 /*
99281 ** Find the appropriate action for a parser given the terminal
99282 ** look-ahead token iLookAhead.
99283 **
99284 ** If the look-ahead token is YYNOCODE, then check to see if the action is
99285 ** independent of the look-ahead.  If it is, return the action, otherwise
99286 ** return YY_NO_ACTION.
99287 */
99288 static int yy_find_shift_action(
99289   yyParser *pParser,        /* The parser */
99290   YYCODETYPE iLookAhead     /* The look-ahead token */
99291 ){
99292   int i;
99293   int stateno = pParser->yystack[pParser->yyidx].stateno;
99294  
99295   if( stateno>YY_SHIFT_COUNT
99296    || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
99297     return yy_default[stateno];
99298   }
99299   assert( iLookAhead!=YYNOCODE );
99300   i += iLookAhead;
99301   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
99302     if( iLookAhead>0 ){
99303 #ifdef YYFALLBACK
99304       YYCODETYPE iFallback;            /* Fallback token */
99305       if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
99306              && (iFallback = yyFallback[iLookAhead])!=0 ){
99307 #ifndef NDEBUG
99308         if( yyTraceFILE ){
99309           fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
99310              yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
99311         }
99312 #endif
99313         return yy_find_shift_action(pParser, iFallback);
99314       }
99315 #endif
99316 #ifdef YYWILDCARD
99317       {
99318         int j = i - iLookAhead + YYWILDCARD;
99319         if( 
99320 #if YY_SHIFT_MIN+YYWILDCARD<0
99321           j>=0 &&
99322 #endif
99323 #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
99324           j<YY_ACTTAB_COUNT &&
99325 #endif
99326           yy_lookahead[j]==YYWILDCARD
99327         ){
99328 #ifndef NDEBUG
99329           if( yyTraceFILE ){
99330             fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
99331                yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
99332           }
99333 #endif /* NDEBUG */
99334           return yy_action[j];
99335         }
99336       }
99337 #endif /* YYWILDCARD */
99338     }
99339     return yy_default[stateno];
99340   }else{
99341     return yy_action[i];
99342   }
99343 }
99344
99345 /*
99346 ** Find the appropriate action for a parser given the non-terminal
99347 ** look-ahead token iLookAhead.
99348 **
99349 ** If the look-ahead token is YYNOCODE, then check to see if the action is
99350 ** independent of the look-ahead.  If it is, return the action, otherwise
99351 ** return YY_NO_ACTION.
99352 */
99353 static int yy_find_reduce_action(
99354   int stateno,              /* Current state number */
99355   YYCODETYPE iLookAhead     /* The look-ahead token */
99356 ){
99357   int i;
99358 #ifdef YYERRORSYMBOL
99359   if( stateno>YY_REDUCE_COUNT ){
99360     return yy_default[stateno];
99361   }
99362 #else
99363   assert( stateno<=YY_REDUCE_COUNT );
99364 #endif
99365   i = yy_reduce_ofst[stateno];
99366   assert( i!=YY_REDUCE_USE_DFLT );
99367   assert( iLookAhead!=YYNOCODE );
99368   i += iLookAhead;
99369 #ifdef YYERRORSYMBOL
99370   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
99371     return yy_default[stateno];
99372   }
99373 #else
99374   assert( i>=0 && i<YY_ACTTAB_COUNT );
99375   assert( yy_lookahead[i]==iLookAhead );
99376 #endif
99377   return yy_action[i];
99378 }
99379
99380 /*
99381 ** The following routine is called if the stack overflows.
99382 */
99383 static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
99384    sqlite3ParserARG_FETCH;
99385    yypParser->yyidx--;
99386 #ifndef NDEBUG
99387    if( yyTraceFILE ){
99388      fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
99389    }
99390 #endif
99391    while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
99392    /* Here code is inserted which will execute if the parser
99393    ** stack every overflows */
99394
99395   UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
99396   sqlite3ErrorMsg(pParse, "parser stack overflow");
99397   pParse->parseError = 1;
99398    sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
99399 }
99400
99401 /*
99402 ** Perform a shift action.
99403 */
99404 static void yy_shift(
99405   yyParser *yypParser,          /* The parser to be shifted */
99406   int yyNewState,               /* The new state to shift in */
99407   int yyMajor,                  /* The major token to shift in */
99408   YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */
99409 ){
99410   yyStackEntry *yytos;
99411   yypParser->yyidx++;
99412 #ifdef YYTRACKMAXSTACKDEPTH
99413   if( yypParser->yyidx>yypParser->yyidxMax ){
99414     yypParser->yyidxMax = yypParser->yyidx;
99415   }
99416 #endif
99417 #if YYSTACKDEPTH>0 
99418   if( yypParser->yyidx>=YYSTACKDEPTH ){
99419     yyStackOverflow(yypParser, yypMinor);
99420     return;
99421   }
99422 #else
99423   if( yypParser->yyidx>=yypParser->yystksz ){
99424     yyGrowStack(yypParser);
99425     if( yypParser->yyidx>=yypParser->yystksz ){
99426       yyStackOverflow(yypParser, yypMinor);
99427       return;
99428     }
99429   }
99430 #endif
99431   yytos = &yypParser->yystack[yypParser->yyidx];
99432   yytos->stateno = (YYACTIONTYPE)yyNewState;
99433   yytos->major = (YYCODETYPE)yyMajor;
99434   yytos->minor = *yypMinor;
99435 #ifndef NDEBUG
99436   if( yyTraceFILE && yypParser->yyidx>0 ){
99437     int i;
99438     fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
99439     fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
99440     for(i=1; i<=yypParser->yyidx; i++)
99441       fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
99442     fprintf(yyTraceFILE,"\n");
99443   }
99444 #endif
99445 }
99446
99447 /* The following table contains information about every rule that
99448 ** is used during the reduce.
99449 */
99450 static const struct {
99451   YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
99452   unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
99453 } yyRuleInfo[] = {
99454   { 142, 1 },
99455   { 143, 2 },
99456   { 143, 1 },
99457   { 144, 1 },
99458   { 144, 3 },
99459   { 145, 0 },
99460   { 145, 1 },
99461   { 145, 3 },
99462   { 146, 1 },
99463   { 147, 3 },
99464   { 149, 0 },
99465   { 149, 1 },
99466   { 149, 2 },
99467   { 148, 0 },
99468   { 148, 1 },
99469   { 148, 1 },
99470   { 148, 1 },
99471   { 147, 2 },
99472   { 147, 2 },
99473   { 147, 2 },
99474   { 151, 1 },
99475   { 151, 0 },
99476   { 147, 2 },
99477   { 147, 3 },
99478   { 147, 5 },
99479   { 147, 2 },
99480   { 152, 6 },
99481   { 154, 1 },
99482   { 156, 0 },
99483   { 156, 3 },
99484   { 155, 1 },
99485   { 155, 0 },
99486   { 153, 4 },
99487   { 153, 2 },
99488   { 158, 3 },
99489   { 158, 1 },
99490   { 161, 3 },
99491   { 162, 1 },
99492   { 165, 1 },
99493   { 165, 1 },
99494   { 166, 1 },
99495   { 150, 1 },
99496   { 150, 1 },
99497   { 150, 1 },
99498   { 163, 0 },
99499   { 163, 1 },
99500   { 167, 1 },
99501   { 167, 4 },
99502   { 167, 6 },
99503   { 168, 1 },
99504   { 168, 2 },
99505   { 169, 1 },
99506   { 169, 1 },
99507   { 164, 2 },
99508   { 164, 0 },
99509   { 172, 3 },
99510   { 172, 1 },
99511   { 173, 2 },
99512   { 173, 4 },
99513   { 173, 3 },
99514   { 173, 3 },
99515   { 173, 2 },
99516   { 173, 2 },
99517   { 173, 3 },
99518   { 173, 5 },
99519   { 173, 2 },
99520   { 173, 4 },
99521   { 173, 4 },
99522   { 173, 1 },
99523   { 173, 2 },
99524   { 178, 0 },
99525   { 178, 1 },
99526   { 180, 0 },
99527   { 180, 2 },
99528   { 182, 2 },
99529   { 182, 3 },
99530   { 182, 3 },
99531   { 182, 3 },
99532   { 183, 2 },
99533   { 183, 2 },
99534   { 183, 1 },
99535   { 183, 1 },
99536   { 183, 2 },
99537   { 181, 3 },
99538   { 181, 2 },
99539   { 184, 0 },
99540   { 184, 2 },
99541   { 184, 2 },
99542   { 159, 0 },
99543   { 159, 2 },
99544   { 185, 3 },
99545   { 185, 2 },
99546   { 185, 1 },
99547   { 186, 2 },
99548   { 186, 7 },
99549   { 186, 5 },
99550   { 186, 5 },
99551   { 186, 10 },
99552   { 188, 0 },
99553   { 188, 1 },
99554   { 176, 0 },
99555   { 176, 3 },
99556   { 189, 0 },
99557   { 189, 2 },
99558   { 190, 1 },
99559   { 190, 1 },
99560   { 190, 1 },
99561   { 147, 4 },
99562   { 192, 2 },
99563   { 192, 0 },
99564   { 147, 8 },
99565   { 147, 4 },
99566   { 147, 1 },
99567   { 160, 1 },
99568   { 160, 3 },
99569   { 195, 1 },
99570   { 195, 2 },
99571   { 195, 1 },
99572   { 194, 9 },
99573   { 196, 1 },
99574   { 196, 1 },
99575   { 196, 0 },
99576   { 204, 2 },
99577   { 204, 0 },
99578   { 197, 3 },
99579   { 197, 2 },
99580   { 197, 4 },
99581   { 205, 2 },
99582   { 205, 1 },
99583   { 205, 0 },
99584   { 198, 0 },
99585   { 198, 2 },
99586   { 207, 2 },
99587   { 207, 0 },
99588   { 206, 7 },
99589   { 206, 7 },
99590   { 206, 7 },
99591   { 157, 0 },
99592   { 157, 2 },
99593   { 193, 2 },
99594   { 208, 1 },
99595   { 208, 2 },
99596   { 208, 3 },
99597   { 208, 4 },
99598   { 210, 2 },
99599   { 210, 0 },
99600   { 209, 0 },
99601   { 209, 3 },
99602   { 209, 2 },
99603   { 211, 4 },
99604   { 211, 0 },
99605   { 202, 0 },
99606   { 202, 3 },
99607   { 214, 4 },
99608   { 214, 2 },
99609   { 215, 1 },
99610   { 177, 1 },
99611   { 177, 1 },
99612   { 177, 0 },
99613   { 200, 0 },
99614   { 200, 3 },
99615   { 201, 0 },
99616   { 201, 2 },
99617   { 203, 0 },
99618   { 203, 2 },
99619   { 203, 4 },
99620   { 203, 4 },
99621   { 147, 5 },
99622   { 199, 0 },
99623   { 199, 2 },
99624   { 147, 7 },
99625   { 217, 5 },
99626   { 217, 3 },
99627   { 147, 8 },
99628   { 147, 5 },
99629   { 147, 6 },
99630   { 218, 2 },
99631   { 218, 1 },
99632   { 220, 3 },
99633   { 220, 1 },
99634   { 219, 0 },
99635   { 219, 3 },
99636   { 213, 3 },
99637   { 213, 1 },
99638   { 175, 1 },
99639   { 175, 3 },
99640   { 174, 1 },
99641   { 175, 1 },
99642   { 175, 1 },
99643   { 175, 3 },
99644   { 175, 5 },
99645   { 174, 1 },
99646   { 174, 1 },
99647   { 175, 1 },
99648   { 175, 1 },
99649   { 175, 3 },
99650   { 175, 6 },
99651   { 175, 5 },
99652   { 175, 4 },
99653   { 174, 1 },
99654   { 175, 3 },
99655   { 175, 3 },
99656   { 175, 3 },
99657   { 175, 3 },
99658   { 175, 3 },
99659   { 175, 3 },
99660   { 175, 3 },
99661   { 175, 3 },
99662   { 222, 1 },
99663   { 222, 2 },
99664   { 222, 1 },
99665   { 222, 2 },
99666   { 175, 3 },
99667   { 175, 5 },
99668   { 175, 2 },
99669   { 175, 3 },
99670   { 175, 3 },
99671   { 175, 4 },
99672   { 175, 2 },
99673   { 175, 2 },
99674   { 175, 2 },
99675   { 175, 2 },
99676   { 223, 1 },
99677   { 223, 2 },
99678   { 175, 5 },
99679   { 224, 1 },
99680   { 224, 2 },
99681   { 175, 5 },
99682   { 175, 3 },
99683   { 175, 5 },
99684   { 175, 4 },
99685   { 175, 4 },
99686   { 175, 5 },
99687   { 226, 5 },
99688   { 226, 4 },
99689   { 227, 2 },
99690   { 227, 0 },
99691   { 225, 1 },
99692   { 225, 0 },
99693   { 221, 1 },
99694   { 221, 0 },
99695   { 216, 3 },
99696   { 216, 1 },
99697   { 147, 11 },
99698   { 228, 1 },
99699   { 228, 0 },
99700   { 179, 0 },
99701   { 179, 3 },
99702   { 187, 5 },
99703   { 187, 3 },
99704   { 229, 0 },
99705   { 229, 2 },
99706   { 147, 4 },
99707   { 147, 1 },
99708   { 147, 2 },
99709   { 147, 3 },
99710   { 147, 5 },
99711   { 147, 6 },
99712   { 147, 5 },
99713   { 147, 6 },
99714   { 230, 1 },
99715   { 230, 1 },
99716   { 230, 1 },
99717   { 230, 1 },
99718   { 230, 1 },
99719   { 170, 2 },
99720   { 171, 2 },
99721   { 232, 1 },
99722   { 231, 1 },
99723   { 231, 0 },
99724   { 147, 5 },
99725   { 233, 11 },
99726   { 235, 1 },
99727   { 235, 1 },
99728   { 235, 2 },
99729   { 235, 0 },
99730   { 236, 1 },
99731   { 236, 1 },
99732   { 236, 3 },
99733   { 237, 0 },
99734   { 237, 3 },
99735   { 238, 0 },
99736   { 238, 2 },
99737   { 234, 3 },
99738   { 234, 2 },
99739   { 240, 1 },
99740   { 240, 3 },
99741   { 241, 0 },
99742   { 241, 3 },
99743   { 241, 2 },
99744   { 239, 7 },
99745   { 239, 8 },
99746   { 239, 5 },
99747   { 239, 5 },
99748   { 239, 1 },
99749   { 175, 4 },
99750   { 175, 6 },
99751   { 191, 1 },
99752   { 191, 1 },
99753   { 191, 1 },
99754   { 147, 4 },
99755   { 147, 6 },
99756   { 147, 3 },
99757   { 243, 0 },
99758   { 243, 2 },
99759   { 242, 1 },
99760   { 242, 0 },
99761   { 147, 1 },
99762   { 147, 3 },
99763   { 147, 1 },
99764   { 147, 3 },
99765   { 147, 6 },
99766   { 147, 6 },
99767   { 244, 1 },
99768   { 245, 0 },
99769   { 245, 1 },
99770   { 147, 1 },
99771   { 147, 4 },
99772   { 246, 7 },
99773   { 247, 1 },
99774   { 247, 3 },
99775   { 248, 0 },
99776   { 248, 2 },
99777   { 249, 1 },
99778   { 249, 3 },
99779   { 250, 1 },
99780   { 251, 0 },
99781   { 251, 4 },
99782   { 251, 2 },
99783 };
99784
99785 static void yy_accept(yyParser*);  /* Forward Declaration */
99786
99787 /*
99788 ** Perform a reduce action and the shift that must immediately
99789 ** follow the reduce.
99790 */
99791 static void yy_reduce(
99792   yyParser *yypParser,         /* The parser */
99793   int yyruleno                 /* Number of the rule by which to reduce */
99794 ){
99795   int yygoto;                     /* The next state */
99796   int yyact;                      /* The next action */
99797   YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
99798   yyStackEntry *yymsp;            /* The top of the parser's stack */
99799   int yysize;                     /* Amount to pop the stack */
99800   sqlite3ParserARG_FETCH;
99801   yymsp = &yypParser->yystack[yypParser->yyidx];
99802 #ifndef NDEBUG
99803   if( yyTraceFILE && yyruleno>=0 
99804         && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
99805     fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
99806       yyRuleName[yyruleno]);
99807   }
99808 #endif /* NDEBUG */
99809
99810   /* Silence complaints from purify about yygotominor being uninitialized
99811   ** in some cases when it is copied into the stack after the following
99812   ** switch.  yygotominor is uninitialized when a rule reduces that does
99813   ** not set the value of its left-hand side nonterminal.  Leaving the
99814   ** value of the nonterminal uninitialized is utterly harmless as long
99815   ** as the value is never used.  So really the only thing this code
99816   ** accomplishes is to quieten purify.  
99817   **
99818   ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
99819   ** without this code, their parser segfaults.  I'm not sure what there
99820   ** parser is doing to make this happen.  This is the second bug report
99821   ** from wireshark this week.  Clearly they are stressing Lemon in ways
99822   ** that it has not been previously stressed...  (SQLite ticket #2172)
99823   */
99824   /*memset(&yygotominor, 0, sizeof(yygotominor));*/
99825   yygotominor = yyzerominor;
99826
99827
99828   switch( yyruleno ){
99829   /* Beginning here are the reduction cases.  A typical example
99830   ** follows:
99831   **   case 0:
99832   **  #line <lineno> <grammarfile>
99833   **     { ... }           // User supplied code
99834   **  #line <lineno> <thisfile>
99835   **     break;
99836   */
99837       case 5: /* explain ::= */
99838 { sqlite3BeginParse(pParse, 0); }
99839         break;
99840       case 6: /* explain ::= EXPLAIN */
99841 { sqlite3BeginParse(pParse, 1); }
99842         break;
99843       case 7: /* explain ::= EXPLAIN QUERY PLAN */
99844 { sqlite3BeginParse(pParse, 2); }
99845         break;
99846       case 8: /* cmdx ::= cmd */
99847 { sqlite3FinishCoding(pParse); }
99848         break;
99849       case 9: /* cmd ::= BEGIN transtype trans_opt */
99850 {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy4);}
99851         break;
99852       case 13: /* transtype ::= */
99853 {yygotominor.yy4 = TK_DEFERRED;}
99854         break;
99855       case 14: /* transtype ::= DEFERRED */
99856       case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
99857       case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
99858       case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
99859       case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
99860 {yygotominor.yy4 = yymsp[0].major;}
99861         break;
99862       case 17: /* cmd ::= COMMIT trans_opt */
99863       case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
99864 {sqlite3CommitTransaction(pParse);}
99865         break;
99866       case 19: /* cmd ::= ROLLBACK trans_opt */
99867 {sqlite3RollbackTransaction(pParse);}
99868         break;
99869       case 22: /* cmd ::= SAVEPOINT nm */
99870 {
99871   sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
99872 }
99873         break;
99874       case 23: /* cmd ::= RELEASE savepoint_opt nm */
99875 {
99876   sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
99877 }
99878         break;
99879       case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
99880 {
99881   sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
99882 }
99883         break;
99884       case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
99885 {
99886    sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy4,0,0,yymsp[-2].minor.yy4);
99887 }
99888         break;
99889       case 27: /* createkw ::= CREATE */
99890 {
99891   pParse->db->lookaside.bEnabled = 0;
99892   yygotominor.yy0 = yymsp[0].minor.yy0;
99893 }
99894         break;
99895       case 28: /* ifnotexists ::= */
99896       case 31: /* temp ::= */ yytestcase(yyruleno==31);
99897       case 70: /* autoinc ::= */ yytestcase(yyruleno==70);
99898       case 83: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==83);
99899       case 85: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==85);
99900       case 87: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==87);
99901       case 98: /* defer_subclause_opt ::= */ yytestcase(yyruleno==98);
99902       case 109: /* ifexists ::= */ yytestcase(yyruleno==109);
99903       case 120: /* distinct ::= ALL */ yytestcase(yyruleno==120);
99904       case 121: /* distinct ::= */ yytestcase(yyruleno==121);
99905       case 222: /* between_op ::= BETWEEN */ yytestcase(yyruleno==222);
99906       case 225: /* in_op ::= IN */ yytestcase(yyruleno==225);
99907 {yygotominor.yy4 = 0;}
99908         break;
99909       case 29: /* ifnotexists ::= IF NOT EXISTS */
99910       case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
99911       case 71: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==71);
99912       case 86: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==86);
99913       case 108: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==108);
99914       case 119: /* distinct ::= DISTINCT */ yytestcase(yyruleno==119);
99915       case 223: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==223);
99916       case 226: /* in_op ::= NOT IN */ yytestcase(yyruleno==226);
99917 {yygotominor.yy4 = 1;}
99918         break;
99919       case 32: /* create_table_args ::= LP columnlist conslist_opt RP */
99920 {
99921   sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
99922 }
99923         break;
99924       case 33: /* create_table_args ::= AS select */
99925 {
99926   sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy387);
99927   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy387);
99928 }
99929         break;
99930       case 36: /* column ::= columnid type carglist */
99931 {
99932   yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
99933   yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
99934 }
99935         break;
99936       case 37: /* columnid ::= nm */
99937 {
99938   sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
99939   yygotominor.yy0 = yymsp[0].minor.yy0;
99940 }
99941         break;
99942       case 38: /* id ::= ID */
99943       case 39: /* id ::= INDEXED */ yytestcase(yyruleno==39);
99944       case 40: /* ids ::= ID|STRING */ yytestcase(yyruleno==40);
99945       case 41: /* nm ::= id */ yytestcase(yyruleno==41);
99946       case 42: /* nm ::= STRING */ yytestcase(yyruleno==42);
99947       case 43: /* nm ::= JOIN_KW */ yytestcase(yyruleno==43);
99948       case 46: /* typetoken ::= typename */ yytestcase(yyruleno==46);
99949       case 49: /* typename ::= ids */ yytestcase(yyruleno==49);
99950       case 127: /* as ::= AS nm */ yytestcase(yyruleno==127);
99951       case 128: /* as ::= ids */ yytestcase(yyruleno==128);
99952       case 138: /* dbnm ::= DOT nm */ yytestcase(yyruleno==138);
99953       case 147: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==147);
99954       case 251: /* collate ::= COLLATE ids */ yytestcase(yyruleno==251);
99955       case 260: /* nmnum ::= plus_num */ yytestcase(yyruleno==260);
99956       case 261: /* nmnum ::= nm */ yytestcase(yyruleno==261);
99957       case 262: /* nmnum ::= ON */ yytestcase(yyruleno==262);
99958       case 263: /* nmnum ::= DELETE */ yytestcase(yyruleno==263);
99959       case 264: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==264);
99960       case 265: /* plus_num ::= plus_opt number */ yytestcase(yyruleno==265);
99961       case 266: /* minus_num ::= MINUS number */ yytestcase(yyruleno==266);
99962       case 267: /* number ::= INTEGER|FLOAT */ yytestcase(yyruleno==267);
99963       case 285: /* trnm ::= nm */ yytestcase(yyruleno==285);
99964 {yygotominor.yy0 = yymsp[0].minor.yy0;}
99965         break;
99966       case 45: /* type ::= typetoken */
99967 {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
99968         break;
99969       case 47: /* typetoken ::= typename LP signed RP */
99970 {
99971   yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
99972   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
99973 }
99974         break;
99975       case 48: /* typetoken ::= typename LP signed COMMA signed RP */
99976 {
99977   yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
99978   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
99979 }
99980         break;
99981       case 50: /* typename ::= typename ids */
99982 {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);}
99983         break;
99984       case 57: /* ccons ::= DEFAULT term */
99985       case 59: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==59);
99986 {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy118);}
99987         break;
99988       case 58: /* ccons ::= DEFAULT LP expr RP */
99989 {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy118);}
99990         break;
99991       case 60: /* ccons ::= DEFAULT MINUS term */
99992 {
99993   ExprSpan v;
99994   v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy118.pExpr, 0, 0);
99995   v.zStart = yymsp[-1].minor.yy0.z;
99996   v.zEnd = yymsp[0].minor.yy118.zEnd;
99997   sqlite3AddDefaultValue(pParse,&v);
99998 }
99999         break;
100000       case 61: /* ccons ::= DEFAULT id */
100001 {
100002   ExprSpan v;
100003   spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
100004   sqlite3AddDefaultValue(pParse,&v);
100005 }
100006         break;
100007       case 63: /* ccons ::= NOT NULL onconf */
100008 {sqlite3AddNotNull(pParse, yymsp[0].minor.yy4);}
100009         break;
100010       case 64: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
100011 {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy4,yymsp[0].minor.yy4,yymsp[-2].minor.yy4);}
100012         break;
100013       case 65: /* ccons ::= UNIQUE onconf */
100014 {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy4,0,0,0,0);}
100015         break;
100016       case 66: /* ccons ::= CHECK LP expr RP */
100017 {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy118.pExpr);}
100018         break;
100019       case 67: /* ccons ::= REFERENCES nm idxlist_opt refargs */
100020 {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy322,yymsp[0].minor.yy4);}
100021         break;
100022       case 68: /* ccons ::= defer_subclause */
100023 {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy4);}
100024         break;
100025       case 69: /* ccons ::= COLLATE ids */
100026 {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
100027         break;
100028       case 72: /* refargs ::= */
100029 { yygotominor.yy4 = OE_None*0x0101; /* EV: R-19803-45884 */}
100030         break;
100031       case 73: /* refargs ::= refargs refarg */
100032 { yygotominor.yy4 = (yymsp[-1].minor.yy4 & ~yymsp[0].minor.yy215.mask) | yymsp[0].minor.yy215.value; }
100033         break;
100034       case 74: /* refarg ::= MATCH nm */
100035       case 75: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==75);
100036 { yygotominor.yy215.value = 0;     yygotominor.yy215.mask = 0x000000; }
100037         break;
100038       case 76: /* refarg ::= ON DELETE refact */
100039 { yygotominor.yy215.value = yymsp[0].minor.yy4;     yygotominor.yy215.mask = 0x0000ff; }
100040         break;
100041       case 77: /* refarg ::= ON UPDATE refact */
100042 { yygotominor.yy215.value = yymsp[0].minor.yy4<<8;  yygotominor.yy215.mask = 0x00ff00; }
100043         break;
100044       case 78: /* refact ::= SET NULL */
100045 { yygotominor.yy4 = OE_SetNull;  /* EV: R-33326-45252 */}
100046         break;
100047       case 79: /* refact ::= SET DEFAULT */
100048 { yygotominor.yy4 = OE_SetDflt;  /* EV: R-33326-45252 */}
100049         break;
100050       case 80: /* refact ::= CASCADE */
100051 { yygotominor.yy4 = OE_Cascade;  /* EV: R-33326-45252 */}
100052         break;
100053       case 81: /* refact ::= RESTRICT */
100054 { yygotominor.yy4 = OE_Restrict; /* EV: R-33326-45252 */}
100055         break;
100056       case 82: /* refact ::= NO ACTION */
100057 { yygotominor.yy4 = OE_None;     /* EV: R-33326-45252 */}
100058         break;
100059       case 84: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
100060       case 99: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==99);
100061       case 101: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==101);
100062       case 104: /* resolvetype ::= raisetype */ yytestcase(yyruleno==104);
100063 {yygotominor.yy4 = yymsp[0].minor.yy4;}
100064         break;
100065       case 88: /* conslist_opt ::= */
100066 {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
100067         break;
100068       case 89: /* conslist_opt ::= COMMA conslist */
100069 {yygotominor.yy0 = yymsp[-1].minor.yy0;}
100070         break;
100071       case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
100072 {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy322,yymsp[0].minor.yy4,yymsp[-2].minor.yy4,0);}
100073         break;
100074       case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */
100075 {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy322,yymsp[0].minor.yy4,0,0,0,0);}
100076         break;
100077       case 96: /* tcons ::= CHECK LP expr RP onconf */
100078 {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy118.pExpr);}
100079         break;
100080       case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
100081 {
100082     sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy322, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy322, yymsp[-1].minor.yy4);
100083     sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy4);
100084 }
100085         break;
100086       case 100: /* onconf ::= */
100087 {yygotominor.yy4 = OE_Default;}
100088         break;
100089       case 102: /* orconf ::= */
100090 {yygotominor.yy210 = OE_Default;}
100091         break;
100092       case 103: /* orconf ::= OR resolvetype */
100093 {yygotominor.yy210 = (u8)yymsp[0].minor.yy4;}
100094         break;
100095       case 105: /* resolvetype ::= IGNORE */
100096 {yygotominor.yy4 = OE_Ignore;}
100097         break;
100098       case 106: /* resolvetype ::= REPLACE */
100099 {yygotominor.yy4 = OE_Replace;}
100100         break;
100101       case 107: /* cmd ::= DROP TABLE ifexists fullname */
100102 {
100103   sqlite3DropTable(pParse, yymsp[0].minor.yy259, 0, yymsp[-1].minor.yy4);
100104 }
100105         break;
100106       case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
100107 {
100108   sqlite3CreateView(pParse, &yymsp[-7].minor.yy0, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, yymsp[0].minor.yy387, yymsp[-6].minor.yy4, yymsp[-4].minor.yy4);
100109 }
100110         break;
100111       case 111: /* cmd ::= DROP VIEW ifexists fullname */
100112 {
100113   sqlite3DropTable(pParse, yymsp[0].minor.yy259, 1, yymsp[-1].minor.yy4);
100114 }
100115         break;
100116       case 112: /* cmd ::= select */
100117 {
100118   SelectDest dest = {SRT_Output, 0, 0, 0, 0};
100119   sqlite3Select(pParse, yymsp[0].minor.yy387, &dest);
100120   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy387);
100121 }
100122         break;
100123       case 113: /* select ::= oneselect */
100124 {yygotominor.yy387 = yymsp[0].minor.yy387;}
100125         break;
100126       case 114: /* select ::= select multiselect_op oneselect */
100127 {
100128   if( yymsp[0].minor.yy387 ){
100129     yymsp[0].minor.yy387->op = (u8)yymsp[-1].minor.yy4;
100130     yymsp[0].minor.yy387->pPrior = yymsp[-2].minor.yy387;
100131   }else{
100132     sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy387);
100133   }
100134   yygotominor.yy387 = yymsp[0].minor.yy387;
100135 }
100136         break;
100137       case 116: /* multiselect_op ::= UNION ALL */
100138 {yygotominor.yy4 = TK_ALL;}
100139         break;
100140       case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
100141 {
100142   yygotominor.yy387 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy322,yymsp[-5].minor.yy259,yymsp[-4].minor.yy314,yymsp[-3].minor.yy322,yymsp[-2].minor.yy314,yymsp[-1].minor.yy322,yymsp[-7].minor.yy4,yymsp[0].minor.yy292.pLimit,yymsp[0].minor.yy292.pOffset);
100143 }
100144         break;
100145       case 122: /* sclp ::= selcollist COMMA */
100146       case 247: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==247);
100147 {yygotominor.yy322 = yymsp[-1].minor.yy322;}
100148         break;
100149       case 123: /* sclp ::= */
100150       case 151: /* orderby_opt ::= */ yytestcase(yyruleno==151);
100151       case 159: /* groupby_opt ::= */ yytestcase(yyruleno==159);
100152       case 240: /* exprlist ::= */ yytestcase(yyruleno==240);
100153       case 246: /* idxlist_opt ::= */ yytestcase(yyruleno==246);
100154 {yygotominor.yy322 = 0;}
100155         break;
100156       case 124: /* selcollist ::= sclp expr as */
100157 {
100158    yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy322, yymsp[-1].minor.yy118.pExpr);
100159    if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[0].minor.yy0, 1);
100160    sqlite3ExprListSetSpan(pParse,yygotominor.yy322,&yymsp[-1].minor.yy118);
100161 }
100162         break;
100163       case 125: /* selcollist ::= sclp STAR */
100164 {
100165   Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
100166   yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy322, p);
100167 }
100168         break;
100169       case 126: /* selcollist ::= sclp nm DOT STAR */
100170 {
100171   Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
100172   Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
100173   Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
100174   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy322, pDot);
100175 }
100176         break;
100177       case 129: /* as ::= */
100178 {yygotominor.yy0.n = 0;}
100179         break;
100180       case 130: /* from ::= */
100181 {yygotominor.yy259 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy259));}
100182         break;
100183       case 131: /* from ::= FROM seltablist */
100184 {
100185   yygotominor.yy259 = yymsp[0].minor.yy259;
100186   sqlite3SrcListShiftJoinType(yygotominor.yy259);
100187 }
100188         break;
100189       case 132: /* stl_prefix ::= seltablist joinop */
100190 {
100191    yygotominor.yy259 = yymsp[-1].minor.yy259;
100192    if( ALWAYS(yygotominor.yy259 && yygotominor.yy259->nSrc>0) ) yygotominor.yy259->a[yygotominor.yy259->nSrc-1].jointype = (u8)yymsp[0].minor.yy4;
100193 }
100194         break;
100195       case 133: /* stl_prefix ::= */
100196 {yygotominor.yy259 = 0;}
100197         break;
100198       case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
100199 {
100200   yygotominor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
100201   sqlite3SrcListIndexedBy(pParse, yygotominor.yy259, &yymsp[-2].minor.yy0);
100202 }
100203         break;
100204       case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
100205 {
100206     yygotominor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy387,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
100207   }
100208         break;
100209       case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
100210 {
100211     if( yymsp[-6].minor.yy259==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy314==0 && yymsp[0].minor.yy384==0 ){
100212       yygotominor.yy259 = yymsp[-4].minor.yy259;
100213     }else{
100214       Select *pSubquery;
100215       sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy259);
100216       pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy259,0,0,0,0,0,0,0);
100217       yygotominor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
100218     }
100219   }
100220         break;
100221       case 137: /* dbnm ::= */
100222       case 146: /* indexed_opt ::= */ yytestcase(yyruleno==146);
100223 {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
100224         break;
100225       case 139: /* fullname ::= nm dbnm */
100226 {yygotominor.yy259 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
100227         break;
100228       case 140: /* joinop ::= COMMA|JOIN */
100229 { yygotominor.yy4 = JT_INNER; }
100230         break;
100231       case 141: /* joinop ::= JOIN_KW JOIN */
100232 { yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
100233         break;
100234       case 142: /* joinop ::= JOIN_KW nm JOIN */
100235 { yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
100236         break;
100237       case 143: /* joinop ::= JOIN_KW nm nm JOIN */
100238 { yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
100239         break;
100240       case 144: /* on_opt ::= ON expr */
100241       case 155: /* sortitem ::= expr */ yytestcase(yyruleno==155);
100242       case 162: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==162);
100243       case 169: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==169);
100244       case 235: /* case_else ::= ELSE expr */ yytestcase(yyruleno==235);
100245       case 237: /* case_operand ::= expr */ yytestcase(yyruleno==237);
100246 {yygotominor.yy314 = yymsp[0].minor.yy118.pExpr;}
100247         break;
100248       case 145: /* on_opt ::= */
100249       case 161: /* having_opt ::= */ yytestcase(yyruleno==161);
100250       case 168: /* where_opt ::= */ yytestcase(yyruleno==168);
100251       case 236: /* case_else ::= */ yytestcase(yyruleno==236);
100252       case 238: /* case_operand ::= */ yytestcase(yyruleno==238);
100253 {yygotominor.yy314 = 0;}
100254         break;
100255       case 148: /* indexed_opt ::= NOT INDEXED */
100256 {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
100257         break;
100258       case 149: /* using_opt ::= USING LP inscollist RP */
100259       case 181: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==181);
100260 {yygotominor.yy384 = yymsp[-1].minor.yy384;}
100261         break;
100262       case 150: /* using_opt ::= */
100263       case 180: /* inscollist_opt ::= */ yytestcase(yyruleno==180);
100264 {yygotominor.yy384 = 0;}
100265         break;
100266       case 152: /* orderby_opt ::= ORDER BY sortlist */
100267       case 160: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==160);
100268       case 239: /* exprlist ::= nexprlist */ yytestcase(yyruleno==239);
100269 {yygotominor.yy322 = yymsp[0].minor.yy322;}
100270         break;
100271       case 153: /* sortlist ::= sortlist COMMA sortitem sortorder */
100272 {
100273   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy322,yymsp[-1].minor.yy314);
100274   if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
100275 }
100276         break;
100277       case 154: /* sortlist ::= sortitem sortorder */
100278 {
100279   yygotominor.yy322 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy314);
100280   if( yygotominor.yy322 && ALWAYS(yygotominor.yy322->a) ) yygotominor.yy322->a[0].sortOrder = (u8)yymsp[0].minor.yy4;
100281 }
100282         break;
100283       case 156: /* sortorder ::= ASC */
100284       case 158: /* sortorder ::= */ yytestcase(yyruleno==158);
100285 {yygotominor.yy4 = SQLITE_SO_ASC;}
100286         break;
100287       case 157: /* sortorder ::= DESC */
100288 {yygotominor.yy4 = SQLITE_SO_DESC;}
100289         break;
100290       case 163: /* limit_opt ::= */
100291 {yygotominor.yy292.pLimit = 0; yygotominor.yy292.pOffset = 0;}
100292         break;
100293       case 164: /* limit_opt ::= LIMIT expr */
100294 {yygotominor.yy292.pLimit = yymsp[0].minor.yy118.pExpr; yygotominor.yy292.pOffset = 0;}
100295         break;
100296       case 165: /* limit_opt ::= LIMIT expr OFFSET expr */
100297 {yygotominor.yy292.pLimit = yymsp[-2].minor.yy118.pExpr; yygotominor.yy292.pOffset = yymsp[0].minor.yy118.pExpr;}
100298         break;
100299       case 166: /* limit_opt ::= LIMIT expr COMMA expr */
100300 {yygotominor.yy292.pOffset = yymsp[-2].minor.yy118.pExpr; yygotominor.yy292.pLimit = yymsp[0].minor.yy118.pExpr;}
100301         break;
100302       case 167: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
100303 {
100304   sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy259, &yymsp[-1].minor.yy0);
100305   sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy259,yymsp[0].minor.yy314);
100306 }
100307         break;
100308       case 170: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
100309 {
100310   sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy259, &yymsp[-3].minor.yy0);
100311   sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy322,"set list"); 
100312   sqlite3Update(pParse,yymsp[-4].minor.yy259,yymsp[-1].minor.yy322,yymsp[0].minor.yy314,yymsp[-5].minor.yy210);
100313 }
100314         break;
100315       case 171: /* setlist ::= setlist COMMA nm EQ expr */
100316 {
100317   yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy322, yymsp[0].minor.yy118.pExpr);
100318   sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
100319 }
100320         break;
100321       case 172: /* setlist ::= nm EQ expr */
100322 {
100323   yygotominor.yy322 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy118.pExpr);
100324   sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
100325 }
100326         break;
100327       case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP */
100328 {sqlite3Insert(pParse, yymsp[-5].minor.yy259, yymsp[-1].minor.yy322, 0, yymsp[-4].minor.yy384, yymsp[-7].minor.yy210);}
100329         break;
100330       case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
100331 {sqlite3Insert(pParse, yymsp[-2].minor.yy259, 0, yymsp[0].minor.yy387, yymsp[-1].minor.yy384, yymsp[-4].minor.yy210);}
100332         break;
100333       case 175: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
100334 {sqlite3Insert(pParse, yymsp[-3].minor.yy259, 0, 0, yymsp[-2].minor.yy384, yymsp[-5].minor.yy210);}
100335         break;
100336       case 176: /* insert_cmd ::= INSERT orconf */
100337 {yygotominor.yy210 = yymsp[0].minor.yy210;}
100338         break;
100339       case 177: /* insert_cmd ::= REPLACE */
100340 {yygotominor.yy210 = OE_Replace;}
100341         break;
100342       case 178: /* itemlist ::= itemlist COMMA expr */
100343       case 241: /* nexprlist ::= nexprlist COMMA expr */ yytestcase(yyruleno==241);
100344 {yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy322,yymsp[0].minor.yy118.pExpr);}
100345         break;
100346       case 179: /* itemlist ::= expr */
100347       case 242: /* nexprlist ::= expr */ yytestcase(yyruleno==242);
100348 {yygotominor.yy322 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy118.pExpr);}
100349         break;
100350       case 182: /* inscollist ::= inscollist COMMA nm */
100351 {yygotominor.yy384 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy384,&yymsp[0].minor.yy0);}
100352         break;
100353       case 183: /* inscollist ::= nm */
100354 {yygotominor.yy384 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
100355         break;
100356       case 184: /* expr ::= term */
100357 {yygotominor.yy118 = yymsp[0].minor.yy118;}
100358         break;
100359       case 185: /* expr ::= LP expr RP */
100360 {yygotominor.yy118.pExpr = yymsp[-1].minor.yy118.pExpr; spanSet(&yygotominor.yy118,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
100361         break;
100362       case 186: /* term ::= NULL */
100363       case 191: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==191);
100364       case 192: /* term ::= STRING */ yytestcase(yyruleno==192);
100365 {spanExpr(&yygotominor.yy118, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
100366         break;
100367       case 187: /* expr ::= id */
100368       case 188: /* expr ::= JOIN_KW */ yytestcase(yyruleno==188);
100369 {spanExpr(&yygotominor.yy118, pParse, TK_ID, &yymsp[0].minor.yy0);}
100370         break;
100371       case 189: /* expr ::= nm DOT nm */
100372 {
100373   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
100374   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
100375   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
100376   spanSet(&yygotominor.yy118,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
100377 }
100378         break;
100379       case 190: /* expr ::= nm DOT nm DOT nm */
100380 {
100381   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
100382   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
100383   Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
100384   Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
100385   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
100386   spanSet(&yygotominor.yy118,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
100387 }
100388         break;
100389       case 193: /* expr ::= REGISTER */
100390 {
100391   /* When doing a nested parse, one can include terms in an expression
100392   ** that look like this:   #1 #2 ...  These terms refer to registers
100393   ** in the virtual machine.  #N is the N-th register. */
100394   if( pParse->nested==0 ){
100395     sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
100396     yygotominor.yy118.pExpr = 0;
100397   }else{
100398     yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
100399     if( yygotominor.yy118.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy118.pExpr->iTable);
100400   }
100401   spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
100402 }
100403         break;
100404       case 194: /* expr ::= VARIABLE */
100405 {
100406   spanExpr(&yygotominor.yy118, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
100407   sqlite3ExprAssignVarNumber(pParse, yygotominor.yy118.pExpr);
100408   spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
100409 }
100410         break;
100411       case 195: /* expr ::= expr COLLATE ids */
100412 {
100413   yygotominor.yy118.pExpr = sqlite3ExprSetColl(pParse, yymsp[-2].minor.yy118.pExpr, &yymsp[0].minor.yy0);
100414   yygotominor.yy118.zStart = yymsp[-2].minor.yy118.zStart;
100415   yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
100416 }
100417         break;
100418       case 196: /* expr ::= CAST LP expr AS typetoken RP */
100419 {
100420   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy118.pExpr, 0, &yymsp[-1].minor.yy0);
100421   spanSet(&yygotominor.yy118,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
100422 }
100423         break;
100424       case 197: /* expr ::= ID LP distinct exprlist RP */
100425 {
100426   if( yymsp[-1].minor.yy322 && yymsp[-1].minor.yy322->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
100427     sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
100428   }
100429   yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy322, &yymsp[-4].minor.yy0);
100430   spanSet(&yygotominor.yy118,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
100431   if( yymsp[-2].minor.yy4 && yygotominor.yy118.pExpr ){
100432     yygotominor.yy118.pExpr->flags |= EP_Distinct;
100433   }
100434 }
100435         break;
100436       case 198: /* expr ::= ID LP STAR RP */
100437 {
100438   yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
100439   spanSet(&yygotominor.yy118,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
100440 }
100441         break;
100442       case 199: /* term ::= CTIME_KW */
100443 {
100444   /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
100445   ** treated as functions that return constants */
100446   yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
100447   if( yygotominor.yy118.pExpr ){
100448     yygotominor.yy118.pExpr->op = TK_CONST_FUNC;  
100449   }
100450   spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
100451 }
100452         break;
100453       case 200: /* expr ::= expr AND expr */
100454       case 201: /* expr ::= expr OR expr */ yytestcase(yyruleno==201);
100455       case 202: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==202);
100456       case 203: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==203);
100457       case 204: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==204);
100458       case 205: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==205);
100459       case 206: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==206);
100460       case 207: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==207);
100461 {spanBinaryExpr(&yygotominor.yy118,pParse,yymsp[-1].major,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy118);}
100462         break;
100463       case 208: /* likeop ::= LIKE_KW */
100464       case 210: /* likeop ::= MATCH */ yytestcase(yyruleno==210);
100465 {yygotominor.yy342.eOperator = yymsp[0].minor.yy0; yygotominor.yy342.not = 0;}
100466         break;
100467       case 209: /* likeop ::= NOT LIKE_KW */
100468       case 211: /* likeop ::= NOT MATCH */ yytestcase(yyruleno==211);
100469 {yygotominor.yy342.eOperator = yymsp[0].minor.yy0; yygotominor.yy342.not = 1;}
100470         break;
100471       case 212: /* expr ::= expr likeop expr */
100472 {
100473   ExprList *pList;
100474   pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy118.pExpr);
100475   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy118.pExpr);
100476   yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy342.eOperator);
100477   if( yymsp[-1].minor.yy342.not ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
100478   yygotominor.yy118.zStart = yymsp[-2].minor.yy118.zStart;
100479   yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
100480   if( yygotominor.yy118.pExpr ) yygotominor.yy118.pExpr->flags |= EP_InfixFunc;
100481 }
100482         break;
100483       case 213: /* expr ::= expr likeop expr ESCAPE expr */
100484 {
100485   ExprList *pList;
100486   pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
100487   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy118.pExpr);
100488   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy118.pExpr);
100489   yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy342.eOperator);
100490   if( yymsp[-3].minor.yy342.not ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
100491   yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
100492   yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
100493   if( yygotominor.yy118.pExpr ) yygotominor.yy118.pExpr->flags |= EP_InfixFunc;
100494 }
100495         break;
100496       case 214: /* expr ::= expr ISNULL|NOTNULL */
100497 {spanUnaryPostfix(&yygotominor.yy118,pParse,yymsp[0].major,&yymsp[-1].minor.yy118,&yymsp[0].minor.yy0);}
100498         break;
100499       case 215: /* expr ::= expr NOT NULL */
100500 {spanUnaryPostfix(&yygotominor.yy118,pParse,TK_NOTNULL,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy0);}
100501         break;
100502       case 216: /* expr ::= expr IS expr */
100503 {
100504   spanBinaryExpr(&yygotominor.yy118,pParse,TK_IS,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy118);
100505   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy118.pExpr, yygotominor.yy118.pExpr, TK_ISNULL);
100506 }
100507         break;
100508       case 217: /* expr ::= expr IS NOT expr */
100509 {
100510   spanBinaryExpr(&yygotominor.yy118,pParse,TK_ISNOT,&yymsp[-3].minor.yy118,&yymsp[0].minor.yy118);
100511   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy118.pExpr, yygotominor.yy118.pExpr, TK_NOTNULL);
100512 }
100513         break;
100514       case 218: /* expr ::= NOT expr */
100515       case 219: /* expr ::= BITNOT expr */ yytestcase(yyruleno==219);
100516 {spanUnaryPrefix(&yygotominor.yy118,pParse,yymsp[-1].major,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
100517         break;
100518       case 220: /* expr ::= MINUS expr */
100519 {spanUnaryPrefix(&yygotominor.yy118,pParse,TK_UMINUS,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
100520         break;
100521       case 221: /* expr ::= PLUS expr */
100522 {spanUnaryPrefix(&yygotominor.yy118,pParse,TK_UPLUS,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
100523         break;
100524       case 224: /* expr ::= expr between_op expr AND expr */
100525 {
100526   ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
100527   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy118.pExpr);
100528   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy118.pExpr, 0, 0);
100529   if( yygotominor.yy118.pExpr ){
100530     yygotominor.yy118.pExpr->x.pList = pList;
100531   }else{
100532     sqlite3ExprListDelete(pParse->db, pList);
100533   } 
100534   if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
100535   yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
100536   yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
100537 }
100538         break;
100539       case 227: /* expr ::= expr in_op LP exprlist RP */
100540 {
100541     if( yymsp[-1].minor.yy322==0 ){
100542       /* Expressions of the form
100543       **
100544       **      expr1 IN ()
100545       **      expr1 NOT IN ()
100546       **
100547       ** simplify to constants 0 (false) and 1 (true), respectively,
100548       ** regardless of the value of expr1.
100549       */
100550       yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy4]);
100551       sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy118.pExpr);
100552     }else{
100553       yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy118.pExpr, 0, 0);
100554       if( yygotominor.yy118.pExpr ){
100555         yygotominor.yy118.pExpr->x.pList = yymsp[-1].minor.yy322;
100556         sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
100557       }else{
100558         sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy322);
100559       }
100560       if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
100561     }
100562     yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
100563     yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
100564   }
100565         break;
100566       case 228: /* expr ::= LP select RP */
100567 {
100568     yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
100569     if( yygotominor.yy118.pExpr ){
100570       yygotominor.yy118.pExpr->x.pSelect = yymsp[-1].minor.yy387;
100571       ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
100572       sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
100573     }else{
100574       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
100575     }
100576     yygotominor.yy118.zStart = yymsp[-2].minor.yy0.z;
100577     yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
100578   }
100579         break;
100580       case 229: /* expr ::= expr in_op LP select RP */
100581 {
100582     yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy118.pExpr, 0, 0);
100583     if( yygotominor.yy118.pExpr ){
100584       yygotominor.yy118.pExpr->x.pSelect = yymsp[-1].minor.yy387;
100585       ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
100586       sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
100587     }else{
100588       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
100589     }
100590     if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
100591     yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
100592     yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
100593   }
100594         break;
100595       case 230: /* expr ::= expr in_op nm dbnm */
100596 {
100597     SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
100598     yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy118.pExpr, 0, 0);
100599     if( yygotominor.yy118.pExpr ){
100600       yygotominor.yy118.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
100601       ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
100602       sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
100603     }else{
100604       sqlite3SrcListDelete(pParse->db, pSrc);
100605     }
100606     if( yymsp[-2].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
100607     yygotominor.yy118.zStart = yymsp[-3].minor.yy118.zStart;
100608     yygotominor.yy118.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];
100609   }
100610         break;
100611       case 231: /* expr ::= EXISTS LP select RP */
100612 {
100613     Expr *p = yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
100614     if( p ){
100615       p->x.pSelect = yymsp[-1].minor.yy387;
100616       ExprSetProperty(p, EP_xIsSelect);
100617       sqlite3ExprSetHeight(pParse, p);
100618     }else{
100619       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
100620     }
100621     yygotominor.yy118.zStart = yymsp[-3].minor.yy0.z;
100622     yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
100623   }
100624         break;
100625       case 232: /* expr ::= CASE case_operand case_exprlist case_else END */
100626 {
100627   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy314, yymsp[-1].minor.yy314, 0);
100628   if( yygotominor.yy118.pExpr ){
100629     yygotominor.yy118.pExpr->x.pList = yymsp[-2].minor.yy322;
100630     sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
100631   }else{
100632     sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy322);
100633   }
100634   yygotominor.yy118.zStart = yymsp[-4].minor.yy0.z;
100635   yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
100636 }
100637         break;
100638       case 233: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
100639 {
100640   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, yymsp[-2].minor.yy118.pExpr);
100641   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yygotominor.yy322, yymsp[0].minor.yy118.pExpr);
100642 }
100643         break;
100644       case 234: /* case_exprlist ::= WHEN expr THEN expr */
100645 {
100646   yygotominor.yy322 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
100647   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yygotominor.yy322, yymsp[0].minor.yy118.pExpr);
100648 }
100649         break;
100650       case 243: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
100651 {
100652   sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0, 
100653                      sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy322, yymsp[-9].minor.yy4,
100654                       &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy4);
100655 }
100656         break;
100657       case 244: /* uniqueflag ::= UNIQUE */
100658       case 298: /* raisetype ::= ABORT */ yytestcase(yyruleno==298);
100659 {yygotominor.yy4 = OE_Abort;}
100660         break;
100661       case 245: /* uniqueflag ::= */
100662 {yygotominor.yy4 = OE_None;}
100663         break;
100664       case 248: /* idxlist ::= idxlist COMMA nm collate sortorder */
100665 {
100666   Expr *p = 0;
100667   if( yymsp[-1].minor.yy0.n>0 ){
100668     p = sqlite3Expr(pParse->db, TK_COLUMN, 0);
100669     sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy0);
100670   }
100671   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, p);
100672   sqlite3ExprListSetName(pParse,yygotominor.yy322,&yymsp[-2].minor.yy0,1);
100673   sqlite3ExprListCheckLength(pParse, yygotominor.yy322, "index");
100674   if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
100675 }
100676         break;
100677       case 249: /* idxlist ::= nm collate sortorder */
100678 {
100679   Expr *p = 0;
100680   if( yymsp[-1].minor.yy0.n>0 ){
100681     p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
100682     sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy0);
100683   }
100684   yygotominor.yy322 = sqlite3ExprListAppend(pParse,0, p);
100685   sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
100686   sqlite3ExprListCheckLength(pParse, yygotominor.yy322, "index");
100687   if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
100688 }
100689         break;
100690       case 250: /* collate ::= */
100691 {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
100692         break;
100693       case 252: /* cmd ::= DROP INDEX ifexists fullname */
100694 {sqlite3DropIndex(pParse, yymsp[0].minor.yy259, yymsp[-1].minor.yy4);}
100695         break;
100696       case 253: /* cmd ::= VACUUM */
100697       case 254: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==254);
100698 {sqlite3Vacuum(pParse);}
100699         break;
100700       case 255: /* cmd ::= PRAGMA nm dbnm */
100701 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
100702         break;
100703       case 256: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
100704 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
100705         break;
100706       case 257: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
100707 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
100708         break;
100709       case 258: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
100710 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
100711         break;
100712       case 259: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
100713 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
100714         break;
100715       case 270: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
100716 {
100717   Token all;
100718   all.z = yymsp[-3].minor.yy0.z;
100719   all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
100720   sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy203, &all);
100721 }
100722         break;
100723       case 271: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
100724 {
100725   sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy4, yymsp[-4].minor.yy90.a, yymsp[-4].minor.yy90.b, yymsp[-2].minor.yy259, yymsp[0].minor.yy314, yymsp[-10].minor.yy4, yymsp[-8].minor.yy4);
100726   yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
100727 }
100728         break;
100729       case 272: /* trigger_time ::= BEFORE */
100730       case 275: /* trigger_time ::= */ yytestcase(yyruleno==275);
100731 { yygotominor.yy4 = TK_BEFORE; }
100732         break;
100733       case 273: /* trigger_time ::= AFTER */
100734 { yygotominor.yy4 = TK_AFTER;  }
100735         break;
100736       case 274: /* trigger_time ::= INSTEAD OF */
100737 { yygotominor.yy4 = TK_INSTEAD;}
100738         break;
100739       case 276: /* trigger_event ::= DELETE|INSERT */
100740       case 277: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==277);
100741 {yygotominor.yy90.a = yymsp[0].major; yygotominor.yy90.b = 0;}
100742         break;
100743       case 278: /* trigger_event ::= UPDATE OF inscollist */
100744 {yygotominor.yy90.a = TK_UPDATE; yygotominor.yy90.b = yymsp[0].minor.yy384;}
100745         break;
100746       case 281: /* when_clause ::= */
100747       case 303: /* key_opt ::= */ yytestcase(yyruleno==303);
100748 { yygotominor.yy314 = 0; }
100749         break;
100750       case 282: /* when_clause ::= WHEN expr */
100751       case 304: /* key_opt ::= KEY expr */ yytestcase(yyruleno==304);
100752 { yygotominor.yy314 = yymsp[0].minor.yy118.pExpr; }
100753         break;
100754       case 283: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
100755 {
100756   assert( yymsp[-2].minor.yy203!=0 );
100757   yymsp[-2].minor.yy203->pLast->pNext = yymsp[-1].minor.yy203;
100758   yymsp[-2].minor.yy203->pLast = yymsp[-1].minor.yy203;
100759   yygotominor.yy203 = yymsp[-2].minor.yy203;
100760 }
100761         break;
100762       case 284: /* trigger_cmd_list ::= trigger_cmd SEMI */
100763
100764   assert( yymsp[-1].minor.yy203!=0 );
100765   yymsp[-1].minor.yy203->pLast = yymsp[-1].minor.yy203;
100766   yygotominor.yy203 = yymsp[-1].minor.yy203;
100767 }
100768         break;
100769       case 286: /* trnm ::= nm DOT nm */
100770 {
100771   yygotominor.yy0 = yymsp[0].minor.yy0;
100772   sqlite3ErrorMsg(pParse, 
100773         "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
100774         "statements within triggers");
100775 }
100776         break;
100777       case 288: /* tridxby ::= INDEXED BY nm */
100778 {
100779   sqlite3ErrorMsg(pParse,
100780         "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
100781         "within triggers");
100782 }
100783         break;
100784       case 289: /* tridxby ::= NOT INDEXED */
100785 {
100786   sqlite3ErrorMsg(pParse,
100787         "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
100788         "within triggers");
100789 }
100790         break;
100791       case 290: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
100792 { yygotominor.yy203 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy322, yymsp[0].minor.yy314, yymsp[-5].minor.yy210); }
100793         break;
100794       case 291: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP */
100795 {yygotominor.yy203 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy384, yymsp[-1].minor.yy322, 0, yymsp[-7].minor.yy210);}
100796         break;
100797       case 292: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
100798 {yygotominor.yy203 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy384, 0, yymsp[0].minor.yy387, yymsp[-4].minor.yy210);}
100799         break;
100800       case 293: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
100801 {yygotominor.yy203 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy314);}
100802         break;
100803       case 294: /* trigger_cmd ::= select */
100804 {yygotominor.yy203 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy387); }
100805         break;
100806       case 295: /* expr ::= RAISE LP IGNORE RP */
100807 {
100808   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0); 
100809   if( yygotominor.yy118.pExpr ){
100810     yygotominor.yy118.pExpr->affinity = OE_Ignore;
100811   }
100812   yygotominor.yy118.zStart = yymsp[-3].minor.yy0.z;
100813   yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
100814 }
100815         break;
100816       case 296: /* expr ::= RAISE LP raisetype COMMA nm RP */
100817 {
100818   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0); 
100819   if( yygotominor.yy118.pExpr ) {
100820     yygotominor.yy118.pExpr->affinity = (char)yymsp[-3].minor.yy4;
100821   }
100822   yygotominor.yy118.zStart = yymsp[-5].minor.yy0.z;
100823   yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
100824 }
100825         break;
100826       case 297: /* raisetype ::= ROLLBACK */
100827 {yygotominor.yy4 = OE_Rollback;}
100828         break;
100829       case 299: /* raisetype ::= FAIL */
100830 {yygotominor.yy4 = OE_Fail;}
100831         break;
100832       case 300: /* cmd ::= DROP TRIGGER ifexists fullname */
100833 {
100834   sqlite3DropTrigger(pParse,yymsp[0].minor.yy259,yymsp[-1].minor.yy4);
100835 }
100836         break;
100837       case 301: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
100838 {
100839   sqlite3Attach(pParse, yymsp[-3].minor.yy118.pExpr, yymsp[-1].minor.yy118.pExpr, yymsp[0].minor.yy314);
100840 }
100841         break;
100842       case 302: /* cmd ::= DETACH database_kw_opt expr */
100843 {
100844   sqlite3Detach(pParse, yymsp[0].minor.yy118.pExpr);
100845 }
100846         break;
100847       case 307: /* cmd ::= REINDEX */
100848 {sqlite3Reindex(pParse, 0, 0);}
100849         break;
100850       case 308: /* cmd ::= REINDEX nm dbnm */
100851 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
100852         break;
100853       case 309: /* cmd ::= ANALYZE */
100854 {sqlite3Analyze(pParse, 0, 0);}
100855         break;
100856       case 310: /* cmd ::= ANALYZE nm dbnm */
100857 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
100858         break;
100859       case 311: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
100860 {
100861   sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy259,&yymsp[0].minor.yy0);
100862 }
100863         break;
100864       case 312: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
100865 {
100866   sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
100867 }
100868         break;
100869       case 313: /* add_column_fullname ::= fullname */
100870 {
100871   pParse->db->lookaside.bEnabled = 0;
100872   sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy259);
100873 }
100874         break;
100875       case 316: /* cmd ::= create_vtab */
100876 {sqlite3VtabFinishParse(pParse,0);}
100877         break;
100878       case 317: /* cmd ::= create_vtab LP vtabarglist RP */
100879 {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
100880         break;
100881       case 318: /* create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm */
100882 {
100883     sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);
100884 }
100885         break;
100886       case 321: /* vtabarg ::= */
100887 {sqlite3VtabArgInit(pParse);}
100888         break;
100889       case 323: /* vtabargtoken ::= ANY */
100890       case 324: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==324);
100891       case 325: /* lp ::= LP */ yytestcase(yyruleno==325);
100892 {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
100893         break;
100894       default:
100895       /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
100896       /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
100897       /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
100898       /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
100899       /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
100900       /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
100901       /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
100902       /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
100903       /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
100904       /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
100905       /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
100906       /* (34) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==34);
100907       /* (35) columnlist ::= column */ yytestcase(yyruleno==35);
100908       /* (44) type ::= */ yytestcase(yyruleno==44);
100909       /* (51) signed ::= plus_num */ yytestcase(yyruleno==51);
100910       /* (52) signed ::= minus_num */ yytestcase(yyruleno==52);
100911       /* (53) carglist ::= carglist carg */ yytestcase(yyruleno==53);
100912       /* (54) carglist ::= */ yytestcase(yyruleno==54);
100913       /* (55) carg ::= CONSTRAINT nm ccons */ yytestcase(yyruleno==55);
100914       /* (56) carg ::= ccons */ yytestcase(yyruleno==56);
100915       /* (62) ccons ::= NULL onconf */ yytestcase(yyruleno==62);
100916       /* (90) conslist ::= conslist COMMA tcons */ yytestcase(yyruleno==90);
100917       /* (91) conslist ::= conslist tcons */ yytestcase(yyruleno==91);
100918       /* (92) conslist ::= tcons */ yytestcase(yyruleno==92);
100919       /* (93) tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==93);
100920       /* (268) plus_opt ::= PLUS */ yytestcase(yyruleno==268);
100921       /* (269) plus_opt ::= */ yytestcase(yyruleno==269);
100922       /* (279) foreach_clause ::= */ yytestcase(yyruleno==279);
100923       /* (280) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==280);
100924       /* (287) tridxby ::= */ yytestcase(yyruleno==287);
100925       /* (305) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==305);
100926       /* (306) database_kw_opt ::= */ yytestcase(yyruleno==306);
100927       /* (314) kwcolumn_opt ::= */ yytestcase(yyruleno==314);
100928       /* (315) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==315);
100929       /* (319) vtabarglist ::= vtabarg */ yytestcase(yyruleno==319);
100930       /* (320) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==320);
100931       /* (322) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==322);
100932       /* (326) anylist ::= */ yytestcase(yyruleno==326);
100933       /* (327) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==327);
100934       /* (328) anylist ::= anylist ANY */ yytestcase(yyruleno==328);
100935         break;
100936   };
100937   yygoto = yyRuleInfo[yyruleno].lhs;
100938   yysize = yyRuleInfo[yyruleno].nrhs;
100939   yypParser->yyidx -= yysize;
100940   yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
100941   if( yyact < YYNSTATE ){
100942 #ifdef NDEBUG
100943     /* If we are not debugging and the reduce action popped at least
100944     ** one element off the stack, then we can push the new element back
100945     ** onto the stack here, and skip the stack overflow test in yy_shift().
100946     ** That gives a significant speed improvement. */
100947     if( yysize ){
100948       yypParser->yyidx++;
100949       yymsp -= yysize-1;
100950       yymsp->stateno = (YYACTIONTYPE)yyact;
100951       yymsp->major = (YYCODETYPE)yygoto;
100952       yymsp->minor = yygotominor;
100953     }else
100954 #endif
100955     {
100956       yy_shift(yypParser,yyact,yygoto,&yygotominor);
100957     }
100958   }else{
100959     assert( yyact == YYNSTATE + YYNRULE + 1 );
100960     yy_accept(yypParser);
100961   }
100962 }
100963
100964 /*
100965 ** The following code executes when the parse fails
100966 */
100967 #ifndef YYNOERRORRECOVERY
100968 static void yy_parse_failed(
100969   yyParser *yypParser           /* The parser */
100970 ){
100971   sqlite3ParserARG_FETCH;
100972 #ifndef NDEBUG
100973   if( yyTraceFILE ){
100974     fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
100975   }
100976 #endif
100977   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
100978   /* Here code is inserted which will be executed whenever the
100979   ** parser fails */
100980   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
100981 }
100982 #endif /* YYNOERRORRECOVERY */
100983
100984 /*
100985 ** The following code executes when a syntax error first occurs.
100986 */
100987 static void yy_syntax_error(
100988   yyParser *yypParser,           /* The parser */
100989   int yymajor,                   /* The major type of the error token */
100990   YYMINORTYPE yyminor            /* The minor type of the error token */
100991 ){
100992   sqlite3ParserARG_FETCH;
100993 #define TOKEN (yyminor.yy0)
100994
100995   UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
100996   assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
100997   sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
100998   pParse->parseError = 1;
100999   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
101000 }
101001
101002 /*
101003 ** The following is executed when the parser accepts
101004 */
101005 static void yy_accept(
101006   yyParser *yypParser           /* The parser */
101007 ){
101008   sqlite3ParserARG_FETCH;
101009 #ifndef NDEBUG
101010   if( yyTraceFILE ){
101011     fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
101012   }
101013 #endif
101014   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
101015   /* Here code is inserted which will be executed whenever the
101016   ** parser accepts */
101017   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
101018 }
101019
101020 /* The main parser program.
101021 ** The first argument is a pointer to a structure obtained from
101022 ** "sqlite3ParserAlloc" which describes the current state of the parser.
101023 ** The second argument is the major token number.  The third is
101024 ** the minor token.  The fourth optional argument is whatever the
101025 ** user wants (and specified in the grammar) and is available for
101026 ** use by the action routines.
101027 **
101028 ** Inputs:
101029 ** <ul>
101030 ** <li> A pointer to the parser (an opaque structure.)
101031 ** <li> The major token number.
101032 ** <li> The minor token number.
101033 ** <li> An option argument of a grammar-specified type.
101034 ** </ul>
101035 **
101036 ** Outputs:
101037 ** None.
101038 */
101039 SQLITE_PRIVATE void sqlite3Parser(
101040   void *yyp,                   /* The parser */
101041   int yymajor,                 /* The major token code number */
101042   sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
101043   sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
101044 ){
101045   YYMINORTYPE yyminorunion;
101046   int yyact;            /* The parser action. */
101047   int yyendofinput;     /* True if we are at the end of input */
101048 #ifdef YYERRORSYMBOL
101049   int yyerrorhit = 0;   /* True if yymajor has invoked an error */
101050 #endif
101051   yyParser *yypParser;  /* The parser */
101052
101053   /* (re)initialize the parser, if necessary */
101054   yypParser = (yyParser*)yyp;
101055   if( yypParser->yyidx<0 ){
101056 #if YYSTACKDEPTH<=0
101057     if( yypParser->yystksz <=0 ){
101058       /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
101059       yyminorunion = yyzerominor;
101060       yyStackOverflow(yypParser, &yyminorunion);
101061       return;
101062     }
101063 #endif
101064     yypParser->yyidx = 0;
101065     yypParser->yyerrcnt = -1;
101066     yypParser->yystack[0].stateno = 0;
101067     yypParser->yystack[0].major = 0;
101068   }
101069   yyminorunion.yy0 = yyminor;
101070   yyendofinput = (yymajor==0);
101071   sqlite3ParserARG_STORE;
101072
101073 #ifndef NDEBUG
101074   if( yyTraceFILE ){
101075     fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
101076   }
101077 #endif
101078
101079   do{
101080     yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
101081     if( yyact<YYNSTATE ){
101082       assert( !yyendofinput );  /* Impossible to shift the $ token */
101083       yy_shift(yypParser,yyact,yymajor,&yyminorunion);
101084       yypParser->yyerrcnt--;
101085       yymajor = YYNOCODE;
101086     }else if( yyact < YYNSTATE + YYNRULE ){
101087       yy_reduce(yypParser,yyact-YYNSTATE);
101088     }else{
101089       assert( yyact == YY_ERROR_ACTION );
101090 #ifdef YYERRORSYMBOL
101091       int yymx;
101092 #endif
101093 #ifndef NDEBUG
101094       if( yyTraceFILE ){
101095         fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
101096       }
101097 #endif
101098 #ifdef YYERRORSYMBOL
101099       /* A syntax error has occurred.
101100       ** The response to an error depends upon whether or not the
101101       ** grammar defines an error token "ERROR".  
101102       **
101103       ** This is what we do if the grammar does define ERROR:
101104       **
101105       **  * Call the %syntax_error function.
101106       **
101107       **  * Begin popping the stack until we enter a state where
101108       **    it is legal to shift the error symbol, then shift
101109       **    the error symbol.
101110       **
101111       **  * Set the error count to three.
101112       **
101113       **  * Begin accepting and shifting new tokens.  No new error
101114       **    processing will occur until three tokens have been
101115       **    shifted successfully.
101116       **
101117       */
101118       if( yypParser->yyerrcnt<0 ){
101119         yy_syntax_error(yypParser,yymajor,yyminorunion);
101120       }
101121       yymx = yypParser->yystack[yypParser->yyidx].major;
101122       if( yymx==YYERRORSYMBOL || yyerrorhit ){
101123 #ifndef NDEBUG
101124         if( yyTraceFILE ){
101125           fprintf(yyTraceFILE,"%sDiscard input token %s\n",
101126              yyTracePrompt,yyTokenName[yymajor]);
101127         }
101128 #endif
101129         yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
101130         yymajor = YYNOCODE;
101131       }else{
101132          while(
101133           yypParser->yyidx >= 0 &&
101134           yymx != YYERRORSYMBOL &&
101135           (yyact = yy_find_reduce_action(
101136                         yypParser->yystack[yypParser->yyidx].stateno,
101137                         YYERRORSYMBOL)) >= YYNSTATE
101138         ){
101139           yy_pop_parser_stack(yypParser);
101140         }
101141         if( yypParser->yyidx < 0 || yymajor==0 ){
101142           yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
101143           yy_parse_failed(yypParser);
101144           yymajor = YYNOCODE;
101145         }else if( yymx!=YYERRORSYMBOL ){
101146           YYMINORTYPE u2;
101147           u2.YYERRSYMDT = 0;
101148           yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
101149         }
101150       }
101151       yypParser->yyerrcnt = 3;
101152       yyerrorhit = 1;
101153 #elif defined(YYNOERRORRECOVERY)
101154       /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
101155       ** do any kind of error recovery.  Instead, simply invoke the syntax
101156       ** error routine and continue going as if nothing had happened.
101157       **
101158       ** Applications can set this macro (for example inside %include) if
101159       ** they intend to abandon the parse upon the first syntax error seen.
101160       */
101161       yy_syntax_error(yypParser,yymajor,yyminorunion);
101162       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
101163       yymajor = YYNOCODE;
101164       
101165 #else  /* YYERRORSYMBOL is not defined */
101166       /* This is what we do if the grammar does not define ERROR:
101167       **
101168       **  * Report an error message, and throw away the input token.
101169       **
101170       **  * If the input token is $, then fail the parse.
101171       **
101172       ** As before, subsequent error messages are suppressed until
101173       ** three input tokens have been successfully shifted.
101174       */
101175       if( yypParser->yyerrcnt<=0 ){
101176         yy_syntax_error(yypParser,yymajor,yyminorunion);
101177       }
101178       yypParser->yyerrcnt = 3;
101179       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
101180       if( yyendofinput ){
101181         yy_parse_failed(yypParser);
101182       }
101183       yymajor = YYNOCODE;
101184 #endif
101185     }
101186   }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
101187   return;
101188 }
101189
101190 /************** End of parse.c ***********************************************/
101191 /************** Begin file tokenize.c ****************************************/
101192 /*
101193 ** 2001 September 15
101194 **
101195 ** The author disclaims copyright to this source code.  In place of
101196 ** a legal notice, here is a blessing:
101197 **
101198 **    May you do good and not evil.
101199 **    May you find forgiveness for yourself and forgive others.
101200 **    May you share freely, never taking more than you give.
101201 **
101202 *************************************************************************
101203 ** An tokenizer for SQL
101204 **
101205 ** This file contains C code that splits an SQL input string up into
101206 ** individual tokens and sends those tokens one-by-one over to the
101207 ** parser for analysis.
101208 */
101209
101210 /*
101211 ** The charMap() macro maps alphabetic characters into their
101212 ** lower-case ASCII equivalent.  On ASCII machines, this is just
101213 ** an upper-to-lower case map.  On EBCDIC machines we also need
101214 ** to adjust the encoding.  Only alphabetic characters and underscores
101215 ** need to be translated.
101216 */
101217 #ifdef SQLITE_ASCII
101218 # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
101219 #endif
101220 #ifdef SQLITE_EBCDIC
101221 # define charMap(X) ebcdicToAscii[(unsigned char)X]
101222 const unsigned char ebcdicToAscii[] = {
101223 /* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
101224    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
101225    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
101226    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
101227    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
101228    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
101229    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
101230    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
101231    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
101232    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
101233    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
101234    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
101235    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
101236    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
101237    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
101238    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
101239    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
101240 };
101241 #endif
101242
101243 /*
101244 ** The sqlite3KeywordCode function looks up an identifier to determine if
101245 ** it is a keyword.  If it is a keyword, the token code of that keyword is 
101246 ** returned.  If the input is not a keyword, TK_ID is returned.
101247 **
101248 ** The implementation of this routine was generated by a program,
101249 ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
101250 ** The output of the mkkeywordhash.c program is written into a file
101251 ** named keywordhash.h and then included into this source file by
101252 ** the #include below.
101253 */
101254 /************** Include keywordhash.h in the middle of tokenize.c ************/
101255 /************** Begin file keywordhash.h *************************************/
101256 /***** This file contains automatically generated code ******
101257 **
101258 ** The code in this file has been automatically generated by
101259 **
101260 **   sqlite/tool/mkkeywordhash.c
101261 **
101262 ** The code in this file implements a function that determines whether
101263 ** or not a given identifier is really an SQL keyword.  The same thing
101264 ** might be implemented more directly using a hand-written hash table.
101265 ** But by using this automatically generated code, the size of the code
101266 ** is substantially reduced.  This is important for embedded applications
101267 ** on platforms with limited memory.
101268 */
101269 /* Hash score: 175 */
101270 static int keywordCode(const char *z, int n){
101271   /* zText[] encodes 811 bytes of keywords in 541 bytes */
101272   /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
101273   /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
101274   /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
101275   /*   UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE          */
101276   /*   CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN        */
101277   /*   SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME         */
101278   /*   AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS     */
101279   /*   CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF      */
101280   /*   ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW         */
101281   /*   INITIALLY                                                          */
101282   static const char zText[540] = {
101283     'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
101284     'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
101285     'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
101286     'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
101287     'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
101288     'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
101289     'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
101290     'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
101291     'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
101292     'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
101293     'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
101294     'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
101295     'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
101296     'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
101297     'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
101298     'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
101299     'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
101300     'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
101301     'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
101302     'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
101303     'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
101304     'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
101305     'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
101306     'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
101307     'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
101308     'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
101309     'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
101310     'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
101311     'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
101312     'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
101313   };
101314   static const unsigned char aHash[127] = {
101315       72, 101, 114,  70,   0,  45,   0,   0,  78,   0,  73,   0,   0,
101316       42,  12,  74,  15,   0, 113,  81,  50, 108,   0,  19,   0,   0,
101317      118,   0, 116, 111,   0,  22,  89,   0,   9,   0,   0,  66,  67,
101318        0,  65,   6,   0,  48,  86,  98,   0, 115,  97,   0,   0,  44,
101319        0,  99,  24,   0,  17,   0, 119,  49,  23,   0,   5, 106,  25,
101320       92,   0,   0, 121, 102,  56, 120,  53,  28,  51,   0,  87,   0,
101321       96,  26,   0,  95,   0,   0,   0,  91,  88,  93,  84, 105,  14,
101322       39, 104,   0,  77,   0,  18,  85, 107,  32,   0, 117,  76, 109,
101323       58,  46,  80,   0,   0,  90,  40,   0, 112,   0,  36,   0,   0,
101324       29,   0,  82,  59,  60,   0,  20,  57,   0,  52,
101325   };
101326   static const unsigned char aNext[121] = {
101327        0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
101328        0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
101329        0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
101330        0,   0,   0,   0,  33,   0,  21,   0,   0,   0,  43,   3,  47,
101331        0,   0,   0,   0,  30,   0,  54,   0,  38,   0,   0,   0,   1,
101332       62,   0,   0,  63,   0,  41,   0,   0,   0,   0,   0,   0,   0,
101333       61,   0,   0,   0,   0,  31,  55,  16,  34,  10,   0,   0,   0,
101334        0,   0,   0,   0,  11,  68,  75,   0,   8,   0, 100,  94,   0,
101335      103,   0,  83,   0,  71,   0,   0, 110,  27,  37,  69,  79,   0,
101336       35,  64,   0,   0,
101337   };
101338   static const unsigned char aLen[121] = {
101339        7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
101340        7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
101341       11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
101342        4,   6,   2,   3,   9,   4,   2,   6,   5,   6,   6,   5,   6,
101343        5,   5,   7,   7,   7,   3,   2,   4,   4,   7,   3,   6,   4,
101344        7,   6,  12,   6,   9,   4,   6,   5,   4,   7,   6,   5,   6,
101345        7,   5,   4,   5,   6,   5,   7,   3,   7,  13,   2,   2,   4,
101346        6,   6,   8,   5,  17,  12,   7,   8,   8,   2,   4,   4,   4,
101347        4,   4,   2,   2,   6,   5,   8,   5,   5,   8,   3,   5,   5,
101348        6,   4,   9,   3,
101349   };
101350   static const unsigned short int aOffset[121] = {
101351        0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
101352       36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
101353       86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
101354      159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197,
101355      203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244,
101356      248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320,
101357      326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383,
101358      387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458,
101359      462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516,
101360      521, 527, 531, 536,
101361   };
101362   static const unsigned char aCode[121] = {
101363     TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,     
101364     TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,    
101365     TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,    
101366     TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,      
101367     TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,       
101368     TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,    
101369     TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,  
101370     TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,       
101371     TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,       
101372     TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_ATTACH,     TK_HAVING,     
101373     TK_GROUP,      TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RELEASE,    
101374     TK_BETWEEN,    TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,       
101375     TK_LIKE_KW,    TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,       
101376     TK_COLLATE,    TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,  
101377     TK_JOIN,       TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,    
101378     TK_PRAGMA,     TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,      
101379     TK_WHEN,       TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,    
101380     TK_AND,        TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,         
101381     TK_CAST,       TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,    
101382     TK_CTIME_KW,   TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,   
101383     TK_IS,         TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,    
101384     TK_LIKE_KW,    TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,      
101385     TK_RESTRICT,   TK_JOIN_KW,    TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,        
101386     TK_UNION,      TK_USING,      TK_VACUUM,     TK_VIEW,       TK_INITIALLY,  
101387     TK_ALL,        
101388   };
101389   int h, i;
101390   if( n<2 ) return TK_ID;
101391   h = ((charMap(z[0])*4) ^
101392       (charMap(z[n-1])*3) ^
101393       n) % 127;
101394   for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
101395     if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
101396       testcase( i==0 ); /* REINDEX */
101397       testcase( i==1 ); /* INDEXED */
101398       testcase( i==2 ); /* INDEX */
101399       testcase( i==3 ); /* DESC */
101400       testcase( i==4 ); /* ESCAPE */
101401       testcase( i==5 ); /* EACH */
101402       testcase( i==6 ); /* CHECK */
101403       testcase( i==7 ); /* KEY */
101404       testcase( i==8 ); /* BEFORE */
101405       testcase( i==9 ); /* FOREIGN */
101406       testcase( i==10 ); /* FOR */
101407       testcase( i==11 ); /* IGNORE */
101408       testcase( i==12 ); /* REGEXP */
101409       testcase( i==13 ); /* EXPLAIN */
101410       testcase( i==14 ); /* INSTEAD */
101411       testcase( i==15 ); /* ADD */
101412       testcase( i==16 ); /* DATABASE */
101413       testcase( i==17 ); /* AS */
101414       testcase( i==18 ); /* SELECT */
101415       testcase( i==19 ); /* TABLE */
101416       testcase( i==20 ); /* LEFT */
101417       testcase( i==21 ); /* THEN */
101418       testcase( i==22 ); /* END */
101419       testcase( i==23 ); /* DEFERRABLE */
101420       testcase( i==24 ); /* ELSE */
101421       testcase( i==25 ); /* EXCEPT */
101422       testcase( i==26 ); /* TRANSACTION */
101423       testcase( i==27 ); /* ACTION */
101424       testcase( i==28 ); /* ON */
101425       testcase( i==29 ); /* NATURAL */
101426       testcase( i==30 ); /* ALTER */
101427       testcase( i==31 ); /* RAISE */
101428       testcase( i==32 ); /* EXCLUSIVE */
101429       testcase( i==33 ); /* EXISTS */
101430       testcase( i==34 ); /* SAVEPOINT */
101431       testcase( i==35 ); /* INTERSECT */
101432       testcase( i==36 ); /* TRIGGER */
101433       testcase( i==37 ); /* REFERENCES */
101434       testcase( i==38 ); /* CONSTRAINT */
101435       testcase( i==39 ); /* INTO */
101436       testcase( i==40 ); /* OFFSET */
101437       testcase( i==41 ); /* OF */
101438       testcase( i==42 ); /* SET */
101439       testcase( i==43 ); /* TEMPORARY */
101440       testcase( i==44 ); /* TEMP */
101441       testcase( i==45 ); /* OR */
101442       testcase( i==46 ); /* UNIQUE */
101443       testcase( i==47 ); /* QUERY */
101444       testcase( i==48 ); /* ATTACH */
101445       testcase( i==49 ); /* HAVING */
101446       testcase( i==50 ); /* GROUP */
101447       testcase( i==51 ); /* UPDATE */
101448       testcase( i==52 ); /* BEGIN */
101449       testcase( i==53 ); /* INNER */
101450       testcase( i==54 ); /* RELEASE */
101451       testcase( i==55 ); /* BETWEEN */
101452       testcase( i==56 ); /* NOTNULL */
101453       testcase( i==57 ); /* NOT */
101454       testcase( i==58 ); /* NO */
101455       testcase( i==59 ); /* NULL */
101456       testcase( i==60 ); /* LIKE */
101457       testcase( i==61 ); /* CASCADE */
101458       testcase( i==62 ); /* ASC */
101459       testcase( i==63 ); /* DELETE */
101460       testcase( i==64 ); /* CASE */
101461       testcase( i==65 ); /* COLLATE */
101462       testcase( i==66 ); /* CREATE */
101463       testcase( i==67 ); /* CURRENT_DATE */
101464       testcase( i==68 ); /* DETACH */
101465       testcase( i==69 ); /* IMMEDIATE */
101466       testcase( i==70 ); /* JOIN */
101467       testcase( i==71 ); /* INSERT */
101468       testcase( i==72 ); /* MATCH */
101469       testcase( i==73 ); /* PLAN */
101470       testcase( i==74 ); /* ANALYZE */
101471       testcase( i==75 ); /* PRAGMA */
101472       testcase( i==76 ); /* ABORT */
101473       testcase( i==77 ); /* VALUES */
101474       testcase( i==78 ); /* VIRTUAL */
101475       testcase( i==79 ); /* LIMIT */
101476       testcase( i==80 ); /* WHEN */
101477       testcase( i==81 ); /* WHERE */
101478       testcase( i==82 ); /* RENAME */
101479       testcase( i==83 ); /* AFTER */
101480       testcase( i==84 ); /* REPLACE */
101481       testcase( i==85 ); /* AND */
101482       testcase( i==86 ); /* DEFAULT */
101483       testcase( i==87 ); /* AUTOINCREMENT */
101484       testcase( i==88 ); /* TO */
101485       testcase( i==89 ); /* IN */
101486       testcase( i==90 ); /* CAST */
101487       testcase( i==91 ); /* COLUMN */
101488       testcase( i==92 ); /* COMMIT */
101489       testcase( i==93 ); /* CONFLICT */
101490       testcase( i==94 ); /* CROSS */
101491       testcase( i==95 ); /* CURRENT_TIMESTAMP */
101492       testcase( i==96 ); /* CURRENT_TIME */
101493       testcase( i==97 ); /* PRIMARY */
101494       testcase( i==98 ); /* DEFERRED */
101495       testcase( i==99 ); /* DISTINCT */
101496       testcase( i==100 ); /* IS */
101497       testcase( i==101 ); /* DROP */
101498       testcase( i==102 ); /* FAIL */
101499       testcase( i==103 ); /* FROM */
101500       testcase( i==104 ); /* FULL */
101501       testcase( i==105 ); /* GLOB */
101502       testcase( i==106 ); /* BY */
101503       testcase( i==107 ); /* IF */
101504       testcase( i==108 ); /* ISNULL */
101505       testcase( i==109 ); /* ORDER */
101506       testcase( i==110 ); /* RESTRICT */
101507       testcase( i==111 ); /* OUTER */
101508       testcase( i==112 ); /* RIGHT */
101509       testcase( i==113 ); /* ROLLBACK */
101510       testcase( i==114 ); /* ROW */
101511       testcase( i==115 ); /* UNION */
101512       testcase( i==116 ); /* USING */
101513       testcase( i==117 ); /* VACUUM */
101514       testcase( i==118 ); /* VIEW */
101515       testcase( i==119 ); /* INITIALLY */
101516       testcase( i==120 ); /* ALL */
101517       return aCode[i];
101518     }
101519   }
101520   return TK_ID;
101521 }
101522 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
101523   return keywordCode((char*)z, n);
101524 }
101525 #define SQLITE_N_KEYWORD 121
101526
101527 /************** End of keywordhash.h *****************************************/
101528 /************** Continuing where we left off in tokenize.c *******************/
101529
101530
101531 /*
101532 ** If X is a character that can be used in an identifier then
101533 ** IdChar(X) will be true.  Otherwise it is false.
101534 **
101535 ** For ASCII, any character with the high-order bit set is
101536 ** allowed in an identifier.  For 7-bit characters, 
101537 ** sqlite3IsIdChar[X] must be 1.
101538 **
101539 ** For EBCDIC, the rules are more complex but have the same
101540 ** end result.
101541 **
101542 ** Ticket #1066.  the SQL standard does not allow '$' in the
101543 ** middle of identfiers.  But many SQL implementations do. 
101544 ** SQLite will allow '$' in identifiers for compatibility.
101545 ** But the feature is undocumented.
101546 */
101547 #ifdef SQLITE_ASCII
101548 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
101549 #endif
101550 #ifdef SQLITE_EBCDIC
101551 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
101552 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
101553     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
101554     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
101555     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
101556     0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
101557     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
101558     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
101559     1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
101560     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
101561     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
101562     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
101563     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
101564     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
101565 };
101566 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
101567 #endif
101568
101569
101570 /*
101571 ** Return the length of the token that begins at z[0]. 
101572 ** Store the token type in *tokenType before returning.
101573 */
101574 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
101575   int i, c;
101576   switch( *z ){
101577     case ' ': case '\t': case '\n': case '\f': case '\r': {
101578       testcase( z[0]==' ' );
101579       testcase( z[0]=='\t' );
101580       testcase( z[0]=='\n' );
101581       testcase( z[0]=='\f' );
101582       testcase( z[0]=='\r' );
101583       for(i=1; sqlite3Isspace(z[i]); i++){}
101584       *tokenType = TK_SPACE;
101585       return i;
101586     }
101587     case '-': {
101588       if( z[1]=='-' ){
101589         /* IMP: R-15891-05542 -- syntax diagram for comments */
101590         for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
101591         *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
101592         return i;
101593       }
101594       *tokenType = TK_MINUS;
101595       return 1;
101596     }
101597     case '(': {
101598       *tokenType = TK_LP;
101599       return 1;
101600     }
101601     case ')': {
101602       *tokenType = TK_RP;
101603       return 1;
101604     }
101605     case ';': {
101606       *tokenType = TK_SEMI;
101607       return 1;
101608     }
101609     case '+': {
101610       *tokenType = TK_PLUS;
101611       return 1;
101612     }
101613     case '*': {
101614       *tokenType = TK_STAR;
101615       return 1;
101616     }
101617     case '/': {
101618       if( z[1]!='*' || z[2]==0 ){
101619         *tokenType = TK_SLASH;
101620         return 1;
101621       }
101622       /* IMP: R-15891-05542 -- syntax diagram for comments */
101623       for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
101624       if( c ) i++;
101625       *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
101626       return i;
101627     }
101628     case '%': {
101629       *tokenType = TK_REM;
101630       return 1;
101631     }
101632     case '=': {
101633       *tokenType = TK_EQ;
101634       return 1 + (z[1]=='=');
101635     }
101636     case '<': {
101637       if( (c=z[1])=='=' ){
101638         *tokenType = TK_LE;
101639         return 2;
101640       }else if( c=='>' ){
101641         *tokenType = TK_NE;
101642         return 2;
101643       }else if( c=='<' ){
101644         *tokenType = TK_LSHIFT;
101645         return 2;
101646       }else{
101647         *tokenType = TK_LT;
101648         return 1;
101649       }
101650     }
101651     case '>': {
101652       if( (c=z[1])=='=' ){
101653         *tokenType = TK_GE;
101654         return 2;
101655       }else if( c=='>' ){
101656         *tokenType = TK_RSHIFT;
101657         return 2;
101658       }else{
101659         *tokenType = TK_GT;
101660         return 1;
101661       }
101662     }
101663     case '!': {
101664       if( z[1]!='=' ){
101665         *tokenType = TK_ILLEGAL;
101666         return 2;
101667       }else{
101668         *tokenType = TK_NE;
101669         return 2;
101670       }
101671     }
101672     case '|': {
101673       if( z[1]!='|' ){
101674         *tokenType = TK_BITOR;
101675         return 1;
101676       }else{
101677         *tokenType = TK_CONCAT;
101678         return 2;
101679       }
101680     }
101681     case ',': {
101682       *tokenType = TK_COMMA;
101683       return 1;
101684     }
101685     case '&': {
101686       *tokenType = TK_BITAND;
101687       return 1;
101688     }
101689     case '~': {
101690       *tokenType = TK_BITNOT;
101691       return 1;
101692     }
101693     case '`':
101694     case '\'':
101695     case '"': {
101696       int delim = z[0];
101697       testcase( delim=='`' );
101698       testcase( delim=='\'' );
101699       testcase( delim=='"' );
101700       for(i=1; (c=z[i])!=0; i++){
101701         if( c==delim ){
101702           if( z[i+1]==delim ){
101703             i++;
101704           }else{
101705             break;
101706           }
101707         }
101708       }
101709       if( c=='\'' ){
101710         *tokenType = TK_STRING;
101711         return i+1;
101712       }else if( c!=0 ){
101713         *tokenType = TK_ID;
101714         return i+1;
101715       }else{
101716         *tokenType = TK_ILLEGAL;
101717         return i;
101718       }
101719     }
101720     case '.': {
101721 #ifndef SQLITE_OMIT_FLOATING_POINT
101722       if( !sqlite3Isdigit(z[1]) )
101723 #endif
101724       {
101725         *tokenType = TK_DOT;
101726         return 1;
101727       }
101728       /* If the next character is a digit, this is a floating point
101729       ** number that begins with ".".  Fall thru into the next case */
101730     }
101731     case '0': case '1': case '2': case '3': case '4':
101732     case '5': case '6': case '7': case '8': case '9': {
101733       testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
101734       testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
101735       testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
101736       testcase( z[0]=='9' );
101737       *tokenType = TK_INTEGER;
101738       for(i=0; sqlite3Isdigit(z[i]); i++){}
101739 #ifndef SQLITE_OMIT_FLOATING_POINT
101740       if( z[i]=='.' ){
101741         i++;
101742         while( sqlite3Isdigit(z[i]) ){ i++; }
101743         *tokenType = TK_FLOAT;
101744       }
101745       if( (z[i]=='e' || z[i]=='E') &&
101746            ( sqlite3Isdigit(z[i+1]) 
101747             || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
101748            )
101749       ){
101750         i += 2;
101751         while( sqlite3Isdigit(z[i]) ){ i++; }
101752         *tokenType = TK_FLOAT;
101753       }
101754 #endif
101755       while( IdChar(z[i]) ){
101756         *tokenType = TK_ILLEGAL;
101757         i++;
101758       }
101759       return i;
101760     }
101761     case '[': {
101762       for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
101763       *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
101764       return i;
101765     }
101766     case '?': {
101767       *tokenType = TK_VARIABLE;
101768       for(i=1; sqlite3Isdigit(z[i]); i++){}
101769       return i;
101770     }
101771     case '#': {
101772       for(i=1; sqlite3Isdigit(z[i]); i++){}
101773       if( i>1 ){
101774         /* Parameters of the form #NNN (where NNN is a number) are used
101775         ** internally by sqlite3NestedParse.  */
101776         *tokenType = TK_REGISTER;
101777         return i;
101778       }
101779       /* Fall through into the next case if the '#' is not followed by
101780       ** a digit. Try to match #AAAA where AAAA is a parameter name. */
101781     }
101782 #ifndef SQLITE_OMIT_TCL_VARIABLE
101783     case '$':
101784 #endif
101785     case '@':  /* For compatibility with MS SQL Server */
101786     case ':': {
101787       int n = 0;
101788       testcase( z[0]=='$' );  testcase( z[0]=='@' );  testcase( z[0]==':' );
101789       *tokenType = TK_VARIABLE;
101790       for(i=1; (c=z[i])!=0; i++){
101791         if( IdChar(c) ){
101792           n++;
101793 #ifndef SQLITE_OMIT_TCL_VARIABLE
101794         }else if( c=='(' && n>0 ){
101795           do{
101796             i++;
101797           }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
101798           if( c==')' ){
101799             i++;
101800           }else{
101801             *tokenType = TK_ILLEGAL;
101802           }
101803           break;
101804         }else if( c==':' && z[i+1]==':' ){
101805           i++;
101806 #endif
101807         }else{
101808           break;
101809         }
101810       }
101811       if( n==0 ) *tokenType = TK_ILLEGAL;
101812       return i;
101813     }
101814 #ifndef SQLITE_OMIT_BLOB_LITERAL
101815     case 'x': case 'X': {
101816       testcase( z[0]=='x' ); testcase( z[0]=='X' );
101817       if( z[1]=='\'' ){
101818         *tokenType = TK_BLOB;
101819         for(i=2; (c=z[i])!=0 && c!='\''; i++){
101820           if( !sqlite3Isxdigit(c) ){
101821             *tokenType = TK_ILLEGAL;
101822           }
101823         }
101824         if( i%2 || !c ) *tokenType = TK_ILLEGAL;
101825         if( c ) i++;
101826         return i;
101827       }
101828       /* Otherwise fall through to the next case */
101829     }
101830 #endif
101831     default: {
101832       if( !IdChar(*z) ){
101833         break;
101834       }
101835       for(i=1; IdChar(z[i]); i++){}
101836       *tokenType = keywordCode((char*)z, i);
101837       return i;
101838     }
101839   }
101840   *tokenType = TK_ILLEGAL;
101841   return 1;
101842 }
101843
101844 /*
101845 ** Run the parser on the given SQL string.  The parser structure is
101846 ** passed in.  An SQLITE_ status code is returned.  If an error occurs
101847 ** then an and attempt is made to write an error message into 
101848 ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
101849 ** error message.
101850 */
101851 SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
101852   int nErr = 0;                   /* Number of errors encountered */
101853   int i;                          /* Loop counter */
101854   void *pEngine;                  /* The LEMON-generated LALR(1) parser */
101855   int tokenType;                  /* type of the next token */
101856   int lastTokenParsed = -1;       /* type of the previous token */
101857   u8 enableLookaside;             /* Saved value of db->lookaside.bEnabled */
101858   sqlite3 *db = pParse->db;       /* The database connection */
101859   int mxSqlLen;                   /* Max length of an SQL string */
101860
101861
101862   mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
101863   if( db->activeVdbeCnt==0 ){
101864     db->u1.isInterrupted = 0;
101865   }
101866   pParse->rc = SQLITE_OK;
101867   pParse->zTail = zSql;
101868   i = 0;
101869   assert( pzErrMsg!=0 );
101870   pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
101871   if( pEngine==0 ){
101872     db->mallocFailed = 1;
101873     return SQLITE_NOMEM;
101874   }
101875   assert( pParse->pNewTable==0 );
101876   assert( pParse->pNewTrigger==0 );
101877   assert( pParse->nVar==0 );
101878   assert( pParse->nVarExpr==0 );
101879   assert( pParse->nVarExprAlloc==0 );
101880   assert( pParse->apVarExpr==0 );
101881   enableLookaside = db->lookaside.bEnabled;
101882   if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
101883   while( !db->mallocFailed && zSql[i]!=0 ){
101884     assert( i>=0 );
101885     pParse->sLastToken.z = &zSql[i];
101886     pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
101887     i += pParse->sLastToken.n;
101888     if( i>mxSqlLen ){
101889       pParse->rc = SQLITE_TOOBIG;
101890       break;
101891     }
101892     switch( tokenType ){
101893       case TK_SPACE: {
101894         if( db->u1.isInterrupted ){
101895           sqlite3ErrorMsg(pParse, "interrupt");
101896           pParse->rc = SQLITE_INTERRUPT;
101897           goto abort_parse;
101898         }
101899         break;
101900       }
101901       case TK_ILLEGAL: {
101902         sqlite3DbFree(db, *pzErrMsg);
101903         *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
101904                         &pParse->sLastToken);
101905         nErr++;
101906         goto abort_parse;
101907       }
101908       case TK_SEMI: {
101909         pParse->zTail = &zSql[i];
101910         /* Fall thru into the default case */
101911       }
101912       default: {
101913         sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
101914         lastTokenParsed = tokenType;
101915         if( pParse->rc!=SQLITE_OK ){
101916           goto abort_parse;
101917         }
101918         break;
101919       }
101920     }
101921   }
101922 abort_parse:
101923   if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
101924     if( lastTokenParsed!=TK_SEMI ){
101925       sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
101926       pParse->zTail = &zSql[i];
101927     }
101928     sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
101929   }
101930 #ifdef YYTRACKMAXSTACKDEPTH
101931   sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
101932       sqlite3ParserStackPeak(pEngine)
101933   );
101934 #endif /* YYDEBUG */
101935   sqlite3ParserFree(pEngine, sqlite3_free);
101936   db->lookaside.bEnabled = enableLookaside;
101937   if( db->mallocFailed ){
101938     pParse->rc = SQLITE_NOMEM;
101939   }
101940   if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
101941     sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
101942   }
101943   assert( pzErrMsg!=0 );
101944   if( pParse->zErrMsg ){
101945     *pzErrMsg = pParse->zErrMsg;
101946     sqlite3_log(pParse->rc, "%s", *pzErrMsg);
101947     pParse->zErrMsg = 0;
101948     nErr++;
101949   }
101950   if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
101951     sqlite3VdbeDelete(pParse->pVdbe);
101952     pParse->pVdbe = 0;
101953   }
101954 #ifndef SQLITE_OMIT_SHARED_CACHE
101955   if( pParse->nested==0 ){
101956     sqlite3DbFree(db, pParse->aTableLock);
101957     pParse->aTableLock = 0;
101958     pParse->nTableLock = 0;
101959   }
101960 #endif
101961 #ifndef SQLITE_OMIT_VIRTUALTABLE
101962   sqlite3DbFree(db, pParse->apVtabLock);
101963 #endif
101964
101965   if( !IN_DECLARE_VTAB ){
101966     /* If the pParse->declareVtab flag is set, do not delete any table 
101967     ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
101968     ** will take responsibility for freeing the Table structure.
101969     */
101970     sqlite3DeleteTable(pParse->pNewTable);
101971   }
101972
101973   sqlite3DeleteTrigger(db, pParse->pNewTrigger);
101974   sqlite3DbFree(db, pParse->apVarExpr);
101975   sqlite3DbFree(db, pParse->aAlias);
101976   while( pParse->pAinc ){
101977     AutoincInfo *p = pParse->pAinc;
101978     pParse->pAinc = p->pNext;
101979     sqlite3DbFree(db, p);
101980   }
101981   while( pParse->pZombieTab ){
101982     Table *p = pParse->pZombieTab;
101983     pParse->pZombieTab = p->pNextZombie;
101984     sqlite3DeleteTable(p);
101985   }
101986   if( nErr>0 && pParse->rc==SQLITE_OK ){
101987     pParse->rc = SQLITE_ERROR;
101988   }
101989   return nErr;
101990 }
101991
101992 /************** End of tokenize.c ********************************************/
101993 /************** Begin file complete.c ****************************************/
101994 /*
101995 ** 2001 September 15
101996 **
101997 ** The author disclaims copyright to this source code.  In place of
101998 ** a legal notice, here is a blessing:
101999 **
102000 **    May you do good and not evil.
102001 **    May you find forgiveness for yourself and forgive others.
102002 **    May you share freely, never taking more than you give.
102003 **
102004 *************************************************************************
102005 ** An tokenizer for SQL
102006 **
102007 ** This file contains C code that implements the sqlite3_complete() API.
102008 ** This code used to be part of the tokenizer.c source file.  But by
102009 ** separating it out, the code will be automatically omitted from
102010 ** static links that do not use it.
102011 */
102012 #ifndef SQLITE_OMIT_COMPLETE
102013
102014 /*
102015 ** This is defined in tokenize.c.  We just have to import the definition.
102016 */
102017 #ifndef SQLITE_AMALGAMATION
102018 #ifdef SQLITE_ASCII
102019 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
102020 #endif
102021 #ifdef SQLITE_EBCDIC
102022 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
102023 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
102024 #endif
102025 #endif /* SQLITE_AMALGAMATION */
102026
102027
102028 /*
102029 ** Token types used by the sqlite3_complete() routine.  See the header
102030 ** comments on that procedure for additional information.
102031 */
102032 #define tkSEMI    0
102033 #define tkWS      1
102034 #define tkOTHER   2
102035 #ifndef SQLITE_OMIT_TRIGGER
102036 #define tkEXPLAIN 3
102037 #define tkCREATE  4
102038 #define tkTEMP    5
102039 #define tkTRIGGER 6
102040 #define tkEND     7
102041 #endif
102042
102043 /*
102044 ** Return TRUE if the given SQL string ends in a semicolon.
102045 **
102046 ** Special handling is require for CREATE TRIGGER statements.
102047 ** Whenever the CREATE TRIGGER keywords are seen, the statement
102048 ** must end with ";END;".
102049 **
102050 ** This implementation uses a state machine with 8 states:
102051 **
102052 **   (0) INVALID   We have not yet seen a non-whitespace character.
102053 **
102054 **   (1) START     At the beginning or end of an SQL statement.  This routine
102055 **                 returns 1 if it ends in the START state and 0 if it ends
102056 **                 in any other state.
102057 **
102058 **   (2) NORMAL    We are in the middle of statement which ends with a single
102059 **                 semicolon.
102060 **
102061 **   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of 
102062 **                 a statement.
102063 **
102064 **   (4) CREATE    The keyword CREATE has been seen at the beginning of a
102065 **                 statement, possibly preceeded by EXPLAIN and/or followed by
102066 **                 TEMP or TEMPORARY
102067 **
102068 **   (5) TRIGGER   We are in the middle of a trigger definition that must be
102069 **                 ended by a semicolon, the keyword END, and another semicolon.
102070 **
102071 **   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
102072 **                 the end of a trigger definition.
102073 **
102074 **   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
102075 **                 of a trigger difinition.
102076 **
102077 ** Transitions between states above are determined by tokens extracted
102078 ** from the input.  The following tokens are significant:
102079 **
102080 **   (0) tkSEMI      A semicolon.
102081 **   (1) tkWS        Whitespace.
102082 **   (2) tkOTHER     Any other SQL token.
102083 **   (3) tkEXPLAIN   The "explain" keyword.
102084 **   (4) tkCREATE    The "create" keyword.
102085 **   (5) tkTEMP      The "temp" or "temporary" keyword.
102086 **   (6) tkTRIGGER   The "trigger" keyword.
102087 **   (7) tkEND       The "end" keyword.
102088 **
102089 ** Whitespace never causes a state transition and is always ignored.
102090 ** This means that a SQL string of all whitespace is invalid.
102091 **
102092 ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
102093 ** to recognize the end of a trigger can be omitted.  All we have to do
102094 ** is look for a semicolon that is not part of an string or comment.
102095 */
102096 SQLITE_API int sqlite3_complete(const char *zSql){
102097   u8 state = 0;   /* Current state, using numbers defined in header comment */
102098   u8 token;       /* Value of the next token */
102099
102100 #ifndef SQLITE_OMIT_TRIGGER
102101   /* A complex statement machine used to detect the end of a CREATE TRIGGER
102102   ** statement.  This is the normal case.
102103   */
102104   static const u8 trans[8][8] = {
102105                      /* Token:                                                */
102106      /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
102107      /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
102108      /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
102109      /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
102110      /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
102111      /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
102112      /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
102113      /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
102114      /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
102115   };
102116 #else
102117   /* If triggers are not supported by this compile then the statement machine
102118   ** used to detect the end of a statement is much simplier
102119   */
102120   static const u8 trans[3][3] = {
102121                      /* Token:           */
102122      /* State:       **  SEMI  WS  OTHER */
102123      /* 0 INVALID: */ {    1,  0,     2, },
102124      /* 1   START: */ {    1,  1,     2, },
102125      /* 2  NORMAL: */ {    1,  2,     2, },
102126   };
102127 #endif /* SQLITE_OMIT_TRIGGER */
102128
102129   while( *zSql ){
102130     switch( *zSql ){
102131       case ';': {  /* A semicolon */
102132         token = tkSEMI;
102133         break;
102134       }
102135       case ' ':
102136       case '\r':
102137       case '\t':
102138       case '\n':
102139       case '\f': {  /* White space is ignored */
102140         token = tkWS;
102141         break;
102142       }
102143       case '/': {   /* C-style comments */
102144         if( zSql[1]!='*' ){
102145           token = tkOTHER;
102146           break;
102147         }
102148         zSql += 2;
102149         while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
102150         if( zSql[0]==0 ) return 0;
102151         zSql++;
102152         token = tkWS;
102153         break;
102154       }
102155       case '-': {   /* SQL-style comments from "--" to end of line */
102156         if( zSql[1]!='-' ){
102157           token = tkOTHER;
102158           break;
102159         }
102160         while( *zSql && *zSql!='\n' ){ zSql++; }
102161         if( *zSql==0 ) return state==1;
102162         token = tkWS;
102163         break;
102164       }
102165       case '[': {   /* Microsoft-style identifiers in [...] */
102166         zSql++;
102167         while( *zSql && *zSql!=']' ){ zSql++; }
102168         if( *zSql==0 ) return 0;
102169         token = tkOTHER;
102170         break;
102171       }
102172       case '`':     /* Grave-accent quoted symbols used by MySQL */
102173       case '"':     /* single- and double-quoted strings */
102174       case '\'': {
102175         int c = *zSql;
102176         zSql++;
102177         while( *zSql && *zSql!=c ){ zSql++; }
102178         if( *zSql==0 ) return 0;
102179         token = tkOTHER;
102180         break;
102181       }
102182       default: {
102183 #ifdef SQLITE_EBCDIC
102184         unsigned char c;
102185 #endif
102186         if( IdChar((u8)*zSql) ){
102187           /* Keywords and unquoted identifiers */
102188           int nId;
102189           for(nId=1; IdChar(zSql[nId]); nId++){}
102190 #ifdef SQLITE_OMIT_TRIGGER
102191           token = tkOTHER;
102192 #else
102193           switch( *zSql ){
102194             case 'c': case 'C': {
102195               if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
102196                 token = tkCREATE;
102197               }else{
102198                 token = tkOTHER;
102199               }
102200               break;
102201             }
102202             case 't': case 'T': {
102203               if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
102204                 token = tkTRIGGER;
102205               }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
102206                 token = tkTEMP;
102207               }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
102208                 token = tkTEMP;
102209               }else{
102210                 token = tkOTHER;
102211               }
102212               break;
102213             }
102214             case 'e':  case 'E': {
102215               if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
102216                 token = tkEND;
102217               }else
102218 #ifndef SQLITE_OMIT_EXPLAIN
102219               if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
102220                 token = tkEXPLAIN;
102221               }else
102222 #endif
102223               {
102224                 token = tkOTHER;
102225               }
102226               break;
102227             }
102228             default: {
102229               token = tkOTHER;
102230               break;
102231             }
102232           }
102233 #endif /* SQLITE_OMIT_TRIGGER */
102234           zSql += nId-1;
102235         }else{
102236           /* Operators and special symbols */
102237           token = tkOTHER;
102238         }
102239         break;
102240       }
102241     }
102242     state = trans[state][token];
102243     zSql++;
102244   }
102245   return state==1;
102246 }
102247
102248 #ifndef SQLITE_OMIT_UTF16
102249 /*
102250 ** This routine is the same as the sqlite3_complete() routine described
102251 ** above, except that the parameter is required to be UTF-16 encoded, not
102252 ** UTF-8.
102253 */
102254 SQLITE_API int sqlite3_complete16(const void *zSql){
102255   sqlite3_value *pVal;
102256   char const *zSql8;
102257   int rc = SQLITE_NOMEM;
102258
102259 #ifndef SQLITE_OMIT_AUTOINIT
102260   rc = sqlite3_initialize();
102261   if( rc ) return rc;
102262 #endif
102263   pVal = sqlite3ValueNew(0);
102264   sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
102265   zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
102266   if( zSql8 ){
102267     rc = sqlite3_complete(zSql8);
102268   }else{
102269     rc = SQLITE_NOMEM;
102270   }
102271   sqlite3ValueFree(pVal);
102272   return sqlite3ApiExit(0, rc);
102273 }
102274 #endif /* SQLITE_OMIT_UTF16 */
102275 #endif /* SQLITE_OMIT_COMPLETE */
102276
102277 /************** End of complete.c ********************************************/
102278 /************** Begin file main.c ********************************************/
102279 /*
102280 ** 2001 September 15
102281 **
102282 ** The author disclaims copyright to this source code.  In place of
102283 ** a legal notice, here is a blessing:
102284 **
102285 **    May you do good and not evil.
102286 **    May you find forgiveness for yourself and forgive others.
102287 **    May you share freely, never taking more than you give.
102288 **
102289 *************************************************************************
102290 ** Main file for the SQLite library.  The routines in this file
102291 ** implement the programmer interface to the library.  Routines in
102292 ** other files are for internal use by SQLite and should not be
102293 ** accessed by users of the library.
102294 */
102295
102296 #ifdef SQLITE_ENABLE_FTS3
102297 /************** Include fts3.h in the middle of main.c ***********************/
102298 /************** Begin file fts3.h ********************************************/
102299 /*
102300 ** 2006 Oct 10
102301 **
102302 ** The author disclaims copyright to this source code.  In place of
102303 ** a legal notice, here is a blessing:
102304 **
102305 **    May you do good and not evil.
102306 **    May you find forgiveness for yourself and forgive others.
102307 **    May you share freely, never taking more than you give.
102308 **
102309 ******************************************************************************
102310 **
102311 ** This header file is used by programs that want to link against the
102312 ** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
102313 */
102314
102315 #if 0
102316 extern "C" {
102317 #endif  /* __cplusplus */
102318
102319 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
102320
102321 #if 0
102322 }  /* extern "C" */
102323 #endif  /* __cplusplus */
102324
102325 /************** End of fts3.h ************************************************/
102326 /************** Continuing where we left off in main.c ***********************/
102327 #endif
102328 #ifdef SQLITE_ENABLE_RTREE
102329 /************** Include rtree.h in the middle of main.c **********************/
102330 /************** Begin file rtree.h *******************************************/
102331 /*
102332 ** 2008 May 26
102333 **
102334 ** The author disclaims copyright to this source code.  In place of
102335 ** a legal notice, here is a blessing:
102336 **
102337 **    May you do good and not evil.
102338 **    May you find forgiveness for yourself and forgive others.
102339 **    May you share freely, never taking more than you give.
102340 **
102341 ******************************************************************************
102342 **
102343 ** This header file is used by programs that want to link against the
102344 ** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
102345 */
102346
102347 #if 0
102348 extern "C" {
102349 #endif  /* __cplusplus */
102350
102351 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
102352
102353 #if 0
102354 }  /* extern "C" */
102355 #endif  /* __cplusplus */
102356
102357 /************** End of rtree.h ***********************************************/
102358 /************** Continuing where we left off in main.c ***********************/
102359 #endif
102360 #ifdef SQLITE_ENABLE_ICU
102361 /************** Include sqliteicu.h in the middle of main.c ******************/
102362 /************** Begin file sqliteicu.h ***************************************/
102363 /*
102364 ** 2008 May 26
102365 **
102366 ** The author disclaims copyright to this source code.  In place of
102367 ** a legal notice, here is a blessing:
102368 **
102369 **    May you do good and not evil.
102370 **    May you find forgiveness for yourself and forgive others.
102371 **    May you share freely, never taking more than you give.
102372 **
102373 ******************************************************************************
102374 **
102375 ** This header file is used by programs that want to link against the
102376 ** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
102377 */
102378
102379 #if 0
102380 extern "C" {
102381 #endif  /* __cplusplus */
102382
102383 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
102384
102385 #if 0
102386 }  /* extern "C" */
102387 #endif  /* __cplusplus */
102388
102389
102390 /************** End of sqliteicu.h *******************************************/
102391 /************** Continuing where we left off in main.c ***********************/
102392 #endif
102393
102394 /*
102395 ** The version of the library
102396 */
102397 #ifndef SQLITE_AMALGAMATION
102398 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
102399 #endif
102400 SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
102401 SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
102402 SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
102403 SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
102404
102405 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
102406 /*
102407 ** If the following function pointer is not NULL and if
102408 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
102409 ** I/O active are written using this function.  These messages
102410 ** are intended for debugging activity only.
102411 */
102412 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
102413 #endif
102414
102415 /*
102416 ** If the following global variable points to a string which is the
102417 ** name of a directory, then that directory will be used to store
102418 ** temporary files.
102419 **
102420 ** See also the "PRAGMA temp_store_directory" SQL command.
102421 */
102422 SQLITE_API char *sqlite3_temp_directory = 0;
102423
102424 /*
102425 ** Initialize SQLite.  
102426 **
102427 ** This routine must be called to initialize the memory allocation,
102428 ** VFS, and mutex subsystems prior to doing any serious work with
102429 ** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
102430 ** this routine will be called automatically by key routines such as
102431 ** sqlite3_open().  
102432 **
102433 ** This routine is a no-op except on its very first call for the process,
102434 ** or for the first call after a call to sqlite3_shutdown.
102435 **
102436 ** The first thread to call this routine runs the initialization to
102437 ** completion.  If subsequent threads call this routine before the first
102438 ** thread has finished the initialization process, then the subsequent
102439 ** threads must block until the first thread finishes with the initialization.
102440 **
102441 ** The first thread might call this routine recursively.  Recursive
102442 ** calls to this routine should not block, of course.  Otherwise the
102443 ** initialization process would never complete.
102444 **
102445 ** Let X be the first thread to enter this routine.  Let Y be some other
102446 ** thread.  Then while the initial invocation of this routine by X is
102447 ** incomplete, it is required that:
102448 **
102449 **    *  Calls to this routine from Y must block until the outer-most
102450 **       call by X completes.
102451 **
102452 **    *  Recursive calls to this routine from thread X return immediately
102453 **       without blocking.
102454 */
102455 SQLITE_API int sqlite3_initialize(void){
102456   sqlite3_mutex *pMaster;                      /* The main static mutex */
102457   int rc;                                      /* Result code */
102458
102459 #ifdef SQLITE_OMIT_WSD
102460   rc = sqlite3_wsd_init(4096, 24);
102461   if( rc!=SQLITE_OK ){
102462     return rc;
102463   }
102464 #endif
102465
102466   /* If SQLite is already completely initialized, then this call
102467   ** to sqlite3_initialize() should be a no-op.  But the initialization
102468   ** must be complete.  So isInit must not be set until the very end
102469   ** of this routine.
102470   */
102471   if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
102472
102473   /* Make sure the mutex subsystem is initialized.  If unable to 
102474   ** initialize the mutex subsystem, return early with the error.
102475   ** If the system is so sick that we are unable to allocate a mutex,
102476   ** there is not much SQLite is going to be able to do.
102477   **
102478   ** The mutex subsystem must take care of serializing its own
102479   ** initialization.
102480   */
102481   rc = sqlite3MutexInit();
102482   if( rc ) return rc;
102483
102484   /* Initialize the malloc() system and the recursive pInitMutex mutex.
102485   ** This operation is protected by the STATIC_MASTER mutex.  Note that
102486   ** MutexAlloc() is called for a static mutex prior to initializing the
102487   ** malloc subsystem - this implies that the allocation of a static
102488   ** mutex must not require support from the malloc subsystem.
102489   */
102490   pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
102491   sqlite3_mutex_enter(pMaster);
102492   sqlite3GlobalConfig.isMutexInit = 1;
102493   if( !sqlite3GlobalConfig.isMallocInit ){
102494     rc = sqlite3MallocInit();
102495   }
102496   if( rc==SQLITE_OK ){
102497     sqlite3GlobalConfig.isMallocInit = 1;
102498     if( !sqlite3GlobalConfig.pInitMutex ){
102499       sqlite3GlobalConfig.pInitMutex =
102500            sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
102501       if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
102502         rc = SQLITE_NOMEM;
102503       }
102504     }
102505   }
102506   if( rc==SQLITE_OK ){
102507     sqlite3GlobalConfig.nRefInitMutex++;
102508   }
102509   sqlite3_mutex_leave(pMaster);
102510
102511   /* If rc is not SQLITE_OK at this point, then either the malloc
102512   ** subsystem could not be initialized or the system failed to allocate
102513   ** the pInitMutex mutex. Return an error in either case.  */
102514   if( rc!=SQLITE_OK ){
102515     return rc;
102516   }
102517
102518   /* Do the rest of the initialization under the recursive mutex so
102519   ** that we will be able to handle recursive calls into
102520   ** sqlite3_initialize().  The recursive calls normally come through
102521   ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
102522   ** recursive calls might also be possible.
102523   */
102524   sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
102525   if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
102526     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
102527     sqlite3GlobalConfig.inProgress = 1;
102528     memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
102529     sqlite3RegisterGlobalFunctions();
102530     if( sqlite3GlobalConfig.isPCacheInit==0 ){
102531       rc = sqlite3PcacheInitialize();
102532     }
102533     if( rc==SQLITE_OK ){
102534       sqlite3GlobalConfig.isPCacheInit = 1;
102535       rc = sqlite3OsInit();
102536     }
102537     if( rc==SQLITE_OK ){
102538       sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage, 
102539           sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
102540       sqlite3GlobalConfig.isInit = 1;
102541     }
102542     sqlite3GlobalConfig.inProgress = 0;
102543   }
102544   sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
102545
102546   /* Go back under the static mutex and clean up the recursive
102547   ** mutex to prevent a resource leak.
102548   */
102549   sqlite3_mutex_enter(pMaster);
102550   sqlite3GlobalConfig.nRefInitMutex--;
102551   if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
102552     assert( sqlite3GlobalConfig.nRefInitMutex==0 );
102553     sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
102554     sqlite3GlobalConfig.pInitMutex = 0;
102555   }
102556   sqlite3_mutex_leave(pMaster);
102557
102558   /* The following is just a sanity check to make sure SQLite has
102559   ** been compiled correctly.  It is important to run this code, but
102560   ** we don't want to run it too often and soak up CPU cycles for no
102561   ** reason.  So we run it once during initialization.
102562   */
102563 #ifndef NDEBUG
102564 #ifndef SQLITE_OMIT_FLOATING_POINT
102565   /* This section of code's only "output" is via assert() statements. */
102566   if ( rc==SQLITE_OK ){
102567     u64 x = (((u64)1)<<63)-1;
102568     double y;
102569     assert(sizeof(x)==8);
102570     assert(sizeof(x)==sizeof(y));
102571     memcpy(&y, &x, 8);
102572     assert( sqlite3IsNaN(y) );
102573   }
102574 #endif
102575 #endif
102576
102577   return rc;
102578 }
102579
102580 /*
102581 ** Undo the effects of sqlite3_initialize().  Must not be called while
102582 ** there are outstanding database connections or memory allocations or
102583 ** while any part of SQLite is otherwise in use in any thread.  This
102584 ** routine is not threadsafe.  But it is safe to invoke this routine
102585 ** on when SQLite is already shut down.  If SQLite is already shut down
102586 ** when this routine is invoked, then this routine is a harmless no-op.
102587 */
102588 SQLITE_API int sqlite3_shutdown(void){
102589   if( sqlite3GlobalConfig.isInit ){
102590     sqlite3_os_end();
102591     sqlite3_reset_auto_extension();
102592     sqlite3GlobalConfig.isInit = 0;
102593   }
102594   if( sqlite3GlobalConfig.isPCacheInit ){
102595     sqlite3PcacheShutdown();
102596     sqlite3GlobalConfig.isPCacheInit = 0;
102597   }
102598   if( sqlite3GlobalConfig.isMallocInit ){
102599     sqlite3MallocEnd();
102600     sqlite3GlobalConfig.isMallocInit = 0;
102601   }
102602   if( sqlite3GlobalConfig.isMutexInit ){
102603     sqlite3MutexEnd();
102604     sqlite3GlobalConfig.isMutexInit = 0;
102605   }
102606
102607   return SQLITE_OK;
102608 }
102609
102610 /*
102611 ** This API allows applications to modify the global configuration of
102612 ** the SQLite library at run-time.
102613 **
102614 ** This routine should only be called when there are no outstanding
102615 ** database connections or memory allocations.  This routine is not
102616 ** threadsafe.  Failure to heed these warnings can lead to unpredictable
102617 ** behavior.
102618 */
102619 SQLITE_API int sqlite3_config(int op, ...){
102620   va_list ap;
102621   int rc = SQLITE_OK;
102622
102623   /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
102624   ** the SQLite library is in use. */
102625   if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
102626
102627   va_start(ap, op);
102628   switch( op ){
102629
102630     /* Mutex configuration options are only available in a threadsafe
102631     ** compile. 
102632     */
102633 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
102634     case SQLITE_CONFIG_SINGLETHREAD: {
102635       /* Disable all mutexing */
102636       sqlite3GlobalConfig.bCoreMutex = 0;
102637       sqlite3GlobalConfig.bFullMutex = 0;
102638       break;
102639     }
102640     case SQLITE_CONFIG_MULTITHREAD: {
102641       /* Disable mutexing of database connections */
102642       /* Enable mutexing of core data structures */
102643       sqlite3GlobalConfig.bCoreMutex = 1;
102644       sqlite3GlobalConfig.bFullMutex = 0;
102645       break;
102646     }
102647     case SQLITE_CONFIG_SERIALIZED: {
102648       /* Enable all mutexing */
102649       sqlite3GlobalConfig.bCoreMutex = 1;
102650       sqlite3GlobalConfig.bFullMutex = 1;
102651       break;
102652     }
102653     case SQLITE_CONFIG_MUTEX: {
102654       /* Specify an alternative mutex implementation */
102655       sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
102656       break;
102657     }
102658     case SQLITE_CONFIG_GETMUTEX: {
102659       /* Retrieve the current mutex implementation */
102660       *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
102661       break;
102662     }
102663 #endif
102664
102665
102666     case SQLITE_CONFIG_MALLOC: {
102667       /* Specify an alternative malloc implementation */
102668       sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
102669       break;
102670     }
102671     case SQLITE_CONFIG_GETMALLOC: {
102672       /* Retrieve the current malloc() implementation */
102673       if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
102674       *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
102675       break;
102676     }
102677     case SQLITE_CONFIG_MEMSTATUS: {
102678       /* Enable or disable the malloc status collection */
102679       sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
102680       break;
102681     }
102682     case SQLITE_CONFIG_SCRATCH: {
102683       /* Designate a buffer for scratch memory space */
102684       sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
102685       sqlite3GlobalConfig.szScratch = va_arg(ap, int);
102686       sqlite3GlobalConfig.nScratch = va_arg(ap, int);
102687       break;
102688     }
102689     case SQLITE_CONFIG_PAGECACHE: {
102690       /* Designate a buffer for page cache memory space */
102691       sqlite3GlobalConfig.pPage = va_arg(ap, void*);
102692       sqlite3GlobalConfig.szPage = va_arg(ap, int);
102693       sqlite3GlobalConfig.nPage = va_arg(ap, int);
102694       break;
102695     }
102696
102697     case SQLITE_CONFIG_PCACHE: {
102698       /* Specify an alternative page cache implementation */
102699       sqlite3GlobalConfig.pcache = *va_arg(ap, sqlite3_pcache_methods*);
102700       break;
102701     }
102702
102703     case SQLITE_CONFIG_GETPCACHE: {
102704       if( sqlite3GlobalConfig.pcache.xInit==0 ){
102705         sqlite3PCacheSetDefault();
102706       }
102707       *va_arg(ap, sqlite3_pcache_methods*) = sqlite3GlobalConfig.pcache;
102708       break;
102709     }
102710
102711 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
102712     case SQLITE_CONFIG_HEAP: {
102713       /* Designate a buffer for heap memory space */
102714       sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
102715       sqlite3GlobalConfig.nHeap = va_arg(ap, int);
102716       sqlite3GlobalConfig.mnReq = va_arg(ap, int);
102717
102718       if( sqlite3GlobalConfig.pHeap==0 ){
102719         /* If the heap pointer is NULL, then restore the malloc implementation
102720         ** back to NULL pointers too.  This will cause the malloc to go
102721         ** back to its default implementation when sqlite3_initialize() is
102722         ** run.
102723         */
102724         memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
102725       }else{
102726         /* The heap pointer is not NULL, then install one of the
102727         ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
102728         ** ENABLE_MEMSYS5 is defined, return an error.
102729         */
102730 #ifdef SQLITE_ENABLE_MEMSYS3
102731         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
102732 #endif
102733 #ifdef SQLITE_ENABLE_MEMSYS5
102734         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
102735 #endif
102736       }
102737       break;
102738     }
102739 #endif
102740
102741     case SQLITE_CONFIG_LOOKASIDE: {
102742       sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
102743       sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
102744       break;
102745     }
102746     
102747     /* Record a pointer to the logger funcction and its first argument.
102748     ** The default is NULL.  Logging is disabled if the function pointer is
102749     ** NULL.
102750     */
102751     case SQLITE_CONFIG_LOG: {
102752       /* MSVC is picky about pulling func ptrs from va lists.
102753       ** http://support.microsoft.com/kb/47961
102754       ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
102755       */
102756       typedef void(*LOGFUNC_t)(void*,int,const char*);
102757       sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
102758       sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
102759       break;
102760     }
102761
102762     default: {
102763       rc = SQLITE_ERROR;
102764       break;
102765     }
102766   }
102767   va_end(ap);
102768   return rc;
102769 }
102770
102771 /*
102772 ** Set up the lookaside buffers for a database connection.
102773 ** Return SQLITE_OK on success.  
102774 ** If lookaside is already active, return SQLITE_BUSY.
102775 **
102776 ** The sz parameter is the number of bytes in each lookaside slot.
102777 ** The cnt parameter is the number of slots.  If pStart is NULL the
102778 ** space for the lookaside memory is obtained from sqlite3_malloc().
102779 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
102780 ** the lookaside memory.
102781 */
102782 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
102783   void *pStart;
102784   if( db->lookaside.nOut ){
102785     return SQLITE_BUSY;
102786   }
102787   /* Free any existing lookaside buffer for this handle before
102788   ** allocating a new one so we don't have to have space for 
102789   ** both at the same time.
102790   */
102791   if( db->lookaside.bMalloced ){
102792     sqlite3_free(db->lookaside.pStart);
102793   }
102794   /* The size of a lookaside slot needs to be larger than a pointer
102795   ** to be useful.
102796   */
102797   if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
102798   if( cnt<0 ) cnt = 0;
102799   if( sz==0 || cnt==0 ){
102800     sz = 0;
102801     pStart = 0;
102802   }else if( pBuf==0 ){
102803     sz = ROUND8(sz);
102804     sqlite3BeginBenignMalloc();
102805     pStart = sqlite3Malloc( sz*cnt );
102806     sqlite3EndBenignMalloc();
102807   }else{
102808     sz = ROUNDDOWN8(sz);
102809     pStart = pBuf;
102810   }
102811   db->lookaside.pStart = pStart;
102812   db->lookaside.pFree = 0;
102813   db->lookaside.sz = (u16)sz;
102814   if( pStart ){
102815     int i;
102816     LookasideSlot *p;
102817     assert( sz > (int)sizeof(LookasideSlot*) );
102818     p = (LookasideSlot*)pStart;
102819     for(i=cnt-1; i>=0; i--){
102820       p->pNext = db->lookaside.pFree;
102821       db->lookaside.pFree = p;
102822       p = (LookasideSlot*)&((u8*)p)[sz];
102823     }
102824     db->lookaside.pEnd = p;
102825     db->lookaside.bEnabled = 1;
102826     db->lookaside.bMalloced = pBuf==0 ?1:0;
102827   }else{
102828     db->lookaside.pEnd = 0;
102829     db->lookaside.bEnabled = 0;
102830     db->lookaside.bMalloced = 0;
102831   }
102832   return SQLITE_OK;
102833 }
102834
102835 /*
102836 ** Return the mutex associated with a database connection.
102837 */
102838 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
102839   return db->mutex;
102840 }
102841
102842 /*
102843 ** Configuration settings for an individual database connection
102844 */
102845 SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
102846   va_list ap;
102847   int rc;
102848   va_start(ap, op);
102849   switch( op ){
102850     case SQLITE_DBCONFIG_LOOKASIDE: {
102851       void *pBuf = va_arg(ap, void*);
102852       int sz = va_arg(ap, int);
102853       int cnt = va_arg(ap, int);
102854       rc = setupLookaside(db, pBuf, sz, cnt);
102855       break;
102856     }
102857     default: {
102858       rc = SQLITE_ERROR;
102859       break;
102860     }
102861   }
102862   va_end(ap);
102863   return rc;
102864 }
102865
102866
102867 /*
102868 ** Return true if the buffer z[0..n-1] contains all spaces.
102869 */
102870 static int allSpaces(const char *z, int n){
102871   while( n>0 && z[n-1]==' ' ){ n--; }
102872   return n==0;
102873 }
102874
102875 /*
102876 ** This is the default collating function named "BINARY" which is always
102877 ** available.
102878 **
102879 ** If the padFlag argument is not NULL then space padding at the end
102880 ** of strings is ignored.  This implements the RTRIM collation.
102881 */
102882 static int binCollFunc(
102883   void *padFlag,
102884   int nKey1, const void *pKey1,
102885   int nKey2, const void *pKey2
102886 ){
102887   int rc, n;
102888   n = nKey1<nKey2 ? nKey1 : nKey2;
102889   rc = memcmp(pKey1, pKey2, n);
102890   if( rc==0 ){
102891     if( padFlag
102892      && allSpaces(((char*)pKey1)+n, nKey1-n)
102893      && allSpaces(((char*)pKey2)+n, nKey2-n)
102894     ){
102895       /* Leave rc unchanged at 0 */
102896     }else{
102897       rc = nKey1 - nKey2;
102898     }
102899   }
102900   return rc;
102901 }
102902
102903 /*
102904 ** Another built-in collating sequence: NOCASE. 
102905 **
102906 ** This collating sequence is intended to be used for "case independant
102907 ** comparison". SQLite's knowledge of upper and lower case equivalents
102908 ** extends only to the 26 characters used in the English language.
102909 **
102910 ** At the moment there is only a UTF-8 implementation.
102911 */
102912 static int nocaseCollatingFunc(
102913   void *NotUsed,
102914   int nKey1, const void *pKey1,
102915   int nKey2, const void *pKey2
102916 ){
102917   int r = sqlite3StrNICmp(
102918       (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
102919   UNUSED_PARAMETER(NotUsed);
102920   if( 0==r ){
102921     r = nKey1-nKey2;
102922   }
102923   return r;
102924 }
102925
102926 /*
102927 ** Return the ROWID of the most recent insert
102928 */
102929 SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
102930   return db->lastRowid;
102931 }
102932
102933 /*
102934 ** Return the number of changes in the most recent call to sqlite3_exec().
102935 */
102936 SQLITE_API int sqlite3_changes(sqlite3 *db){
102937   return db->nChange;
102938 }
102939
102940 /*
102941 ** Return the number of changes since the database handle was opened.
102942 */
102943 SQLITE_API int sqlite3_total_changes(sqlite3 *db){
102944   return db->nTotalChange;
102945 }
102946
102947 /*
102948 ** Close all open savepoints. This function only manipulates fields of the
102949 ** database handle object, it does not close any savepoints that may be open
102950 ** at the b-tree/pager level.
102951 */
102952 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
102953   while( db->pSavepoint ){
102954     Savepoint *pTmp = db->pSavepoint;
102955     db->pSavepoint = pTmp->pNext;
102956     sqlite3DbFree(db, pTmp);
102957   }
102958   db->nSavepoint = 0;
102959   db->nStatement = 0;
102960   db->isTransactionSavepoint = 0;
102961 }
102962
102963 /*
102964 ** Close an existing SQLite database
102965 */
102966 SQLITE_API int sqlite3_close(sqlite3 *db){
102967   HashElem *i;
102968   int j;
102969
102970   if( !db ){
102971     return SQLITE_OK;
102972   }
102973   if( !sqlite3SafetyCheckSickOrOk(db) ){
102974     return SQLITE_MISUSE_BKPT;
102975   }
102976   sqlite3_mutex_enter(db->mutex);
102977
102978   sqlite3ResetInternalSchema(db, 0);
102979
102980   /* If a transaction is open, the ResetInternalSchema() call above
102981   ** will not have called the xDisconnect() method on any virtual
102982   ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
102983   ** call will do so. We need to do this before the check for active
102984   ** SQL statements below, as the v-table implementation may be storing
102985   ** some prepared statements internally.
102986   */
102987   sqlite3VtabRollback(db);
102988
102989   /* If there are any outstanding VMs, return SQLITE_BUSY. */
102990   if( db->pVdbe ){
102991     sqlite3Error(db, SQLITE_BUSY, 
102992         "unable to close due to unfinalised statements");
102993     sqlite3_mutex_leave(db->mutex);
102994     return SQLITE_BUSY;
102995   }
102996   assert( sqlite3SafetyCheckSickOrOk(db) );
102997
102998   for(j=0; j<db->nDb; j++){
102999     Btree *pBt = db->aDb[j].pBt;
103000     if( pBt && sqlite3BtreeIsInBackup(pBt) ){
103001       sqlite3Error(db, SQLITE_BUSY, 
103002           "unable to close due to unfinished backup operation");
103003       sqlite3_mutex_leave(db->mutex);
103004       return SQLITE_BUSY;
103005     }
103006   }
103007
103008   /* Free any outstanding Savepoint structures. */
103009   sqlite3CloseSavepoints(db);
103010
103011   for(j=0; j<db->nDb; j++){
103012     struct Db *pDb = &db->aDb[j];
103013     if( pDb->pBt ){
103014       sqlite3BtreeClose(pDb->pBt);
103015       pDb->pBt = 0;
103016       if( j!=1 ){
103017         pDb->pSchema = 0;
103018       }
103019     }
103020   }
103021   sqlite3ResetInternalSchema(db, 0);
103022
103023   /* Tell the code in notify.c that the connection no longer holds any
103024   ** locks and does not require any further unlock-notify callbacks.
103025   */
103026   sqlite3ConnectionClosed(db);
103027
103028   assert( db->nDb<=2 );
103029   assert( db->aDb==db->aDbStatic );
103030   for(j=0; j<ArraySize(db->aFunc.a); j++){
103031     FuncDef *pNext, *pHash, *p;
103032     for(p=db->aFunc.a[j]; p; p=pHash){
103033       pHash = p->pHash;
103034       while( p ){
103035         pNext = p->pNext;
103036         sqlite3DbFree(db, p);
103037         p = pNext;
103038       }
103039     }
103040   }
103041   for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
103042     CollSeq *pColl = (CollSeq *)sqliteHashData(i);
103043     /* Invoke any destructors registered for collation sequence user data. */
103044     for(j=0; j<3; j++){
103045       if( pColl[j].xDel ){
103046         pColl[j].xDel(pColl[j].pUser);
103047       }
103048     }
103049     sqlite3DbFree(db, pColl);
103050   }
103051   sqlite3HashClear(&db->aCollSeq);
103052 #ifndef SQLITE_OMIT_VIRTUALTABLE
103053   for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
103054     Module *pMod = (Module *)sqliteHashData(i);
103055     if( pMod->xDestroy ){
103056       pMod->xDestroy(pMod->pAux);
103057     }
103058     sqlite3DbFree(db, pMod);
103059   }
103060   sqlite3HashClear(&db->aModule);
103061 #endif
103062
103063   sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
103064   if( db->pErr ){
103065     sqlite3ValueFree(db->pErr);
103066   }
103067   sqlite3CloseExtensions(db);
103068
103069   db->magic = SQLITE_MAGIC_ERROR;
103070
103071   /* The temp-database schema is allocated differently from the other schema
103072   ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
103073   ** So it needs to be freed here. Todo: Why not roll the temp schema into
103074   ** the same sqliteMalloc() as the one that allocates the database 
103075   ** structure?
103076   */
103077   sqlite3DbFree(db, db->aDb[1].pSchema);
103078   sqlite3_mutex_leave(db->mutex);
103079   db->magic = SQLITE_MAGIC_CLOSED;
103080   sqlite3_mutex_free(db->mutex);
103081   assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
103082   if( db->lookaside.bMalloced ){
103083     sqlite3_free(db->lookaside.pStart);
103084   }
103085   sqlite3_free(db);
103086   return SQLITE_OK;
103087 }
103088
103089 /*
103090 ** Rollback all database files.
103091 */
103092 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db){
103093   int i;
103094   int inTrans = 0;
103095   assert( sqlite3_mutex_held(db->mutex) );
103096   sqlite3BeginBenignMalloc();
103097   for(i=0; i<db->nDb; i++){
103098     if( db->aDb[i].pBt ){
103099       if( sqlite3BtreeIsInTrans(db->aDb[i].pBt) ){
103100         inTrans = 1;
103101       }
103102       sqlite3BtreeRollback(db->aDb[i].pBt);
103103       db->aDb[i].inTrans = 0;
103104     }
103105   }
103106   sqlite3VtabRollback(db);
103107   sqlite3EndBenignMalloc();
103108
103109   if( db->flags&SQLITE_InternChanges ){
103110     sqlite3ExpirePreparedStatements(db);
103111     sqlite3ResetInternalSchema(db, 0);
103112   }
103113
103114   /* Any deferred constraint violations have now been resolved. */
103115   db->nDeferredCons = 0;
103116
103117   /* If one has been configured, invoke the rollback-hook callback */
103118   if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
103119     db->xRollbackCallback(db->pRollbackArg);
103120   }
103121 }
103122
103123 /*
103124 ** Return a static string that describes the kind of error specified in the
103125 ** argument.
103126 */
103127 SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
103128   static const char* const aMsg[] = {
103129     /* SQLITE_OK          */ "not an error",
103130     /* SQLITE_ERROR       */ "SQL logic error or missing database",
103131     /* SQLITE_INTERNAL    */ 0,
103132     /* SQLITE_PERM        */ "access permission denied",
103133     /* SQLITE_ABORT       */ "callback requested query abort",
103134     /* SQLITE_BUSY        */ "database is locked",
103135     /* SQLITE_LOCKED      */ "database table is locked",
103136     /* SQLITE_NOMEM       */ "out of memory",
103137     /* SQLITE_READONLY    */ "attempt to write a readonly database",
103138     /* SQLITE_INTERRUPT   */ "interrupted",
103139     /* SQLITE_IOERR       */ "disk I/O error",
103140     /* SQLITE_CORRUPT     */ "database disk image is malformed",
103141     /* SQLITE_NOTFOUND    */ 0,
103142     /* SQLITE_FULL        */ "database or disk is full",
103143     /* SQLITE_CANTOPEN    */ "unable to open database file",
103144     /* SQLITE_PROTOCOL    */ "locking protocol",
103145     /* SQLITE_EMPTY       */ "table contains no data",
103146     /* SQLITE_SCHEMA      */ "database schema has changed",
103147     /* SQLITE_TOOBIG      */ "string or blob too big",
103148     /* SQLITE_CONSTRAINT  */ "constraint failed",
103149     /* SQLITE_MISMATCH    */ "datatype mismatch",
103150     /* SQLITE_MISUSE      */ "library routine called out of sequence",
103151     /* SQLITE_NOLFS       */ "large file support is disabled",
103152     /* SQLITE_AUTH        */ "authorization denied",
103153     /* SQLITE_FORMAT      */ "auxiliary database format error",
103154     /* SQLITE_RANGE       */ "bind or column index out of range",
103155     /* SQLITE_NOTADB      */ "file is encrypted or is not a database",
103156   };
103157   rc &= 0xff;
103158   if( ALWAYS(rc>=0) && rc<(int)(sizeof(aMsg)/sizeof(aMsg[0])) && aMsg[rc]!=0 ){
103159     return aMsg[rc];
103160   }else{
103161     return "unknown error";
103162   }
103163 }
103164
103165 /*
103166 ** This routine implements a busy callback that sleeps and tries
103167 ** again until a timeout value is reached.  The timeout value is
103168 ** an integer number of milliseconds passed in as the first
103169 ** argument.
103170 */
103171 static int sqliteDefaultBusyCallback(
103172  void *ptr,               /* Database connection */
103173  int count                /* Number of times table has been busy */
103174 ){
103175 #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
103176   static const u8 delays[] =
103177      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
103178   static const u8 totals[] =
103179      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
103180 # define NDELAY (sizeof(delays)/sizeof(delays[0]))
103181   sqlite3 *db = (sqlite3 *)ptr;
103182   int timeout = db->busyTimeout;
103183   int delay, prior;
103184
103185   assert( count>=0 );
103186   if( count < NDELAY ){
103187     delay = delays[count];
103188     prior = totals[count];
103189   }else{
103190     delay = delays[NDELAY-1];
103191     prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
103192   }
103193   if( prior + delay > timeout ){
103194     delay = timeout - prior;
103195     if( delay<=0 ) return 0;
103196   }
103197   sqlite3OsSleep(db->pVfs, delay*1000);
103198   return 1;
103199 #else
103200   sqlite3 *db = (sqlite3 *)ptr;
103201   int timeout = ((sqlite3 *)ptr)->busyTimeout;
103202   if( (count+1)*1000 > timeout ){
103203     return 0;
103204   }
103205   sqlite3OsSleep(db->pVfs, 1000000);
103206   return 1;
103207 #endif
103208 }
103209
103210 /*
103211 ** Invoke the given busy handler.
103212 **
103213 ** This routine is called when an operation failed with a lock.
103214 ** If this routine returns non-zero, the lock is retried.  If it
103215 ** returns 0, the operation aborts with an SQLITE_BUSY error.
103216 */
103217 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
103218   int rc;
103219   if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
103220   rc = p->xFunc(p->pArg, p->nBusy);
103221   if( rc==0 ){
103222     p->nBusy = -1;
103223   }else{
103224     p->nBusy++;
103225   }
103226   return rc; 
103227 }
103228
103229 /*
103230 ** This routine sets the busy callback for an Sqlite database to the
103231 ** given callback function with the given argument.
103232 */
103233 SQLITE_API int sqlite3_busy_handler(
103234   sqlite3 *db,
103235   int (*xBusy)(void*,int),
103236   void *pArg
103237 ){
103238   sqlite3_mutex_enter(db->mutex);
103239   db->busyHandler.xFunc = xBusy;
103240   db->busyHandler.pArg = pArg;
103241   db->busyHandler.nBusy = 0;
103242   sqlite3_mutex_leave(db->mutex);
103243   return SQLITE_OK;
103244 }
103245
103246 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
103247 /*
103248 ** This routine sets the progress callback for an Sqlite database to the
103249 ** given callback function with the given argument. The progress callback will
103250 ** be invoked every nOps opcodes.
103251 */
103252 SQLITE_API void sqlite3_progress_handler(
103253   sqlite3 *db, 
103254   int nOps,
103255   int (*xProgress)(void*), 
103256   void *pArg
103257 ){
103258   sqlite3_mutex_enter(db->mutex);
103259   if( nOps>0 ){
103260     db->xProgress = xProgress;
103261     db->nProgressOps = nOps;
103262     db->pProgressArg = pArg;
103263   }else{
103264     db->xProgress = 0;
103265     db->nProgressOps = 0;
103266     db->pProgressArg = 0;
103267   }
103268   sqlite3_mutex_leave(db->mutex);
103269 }
103270 #endif
103271
103272
103273 /*
103274 ** This routine installs a default busy handler that waits for the
103275 ** specified number of milliseconds before returning 0.
103276 */
103277 SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
103278   if( ms>0 ){
103279     db->busyTimeout = ms;
103280     sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
103281   }else{
103282     sqlite3_busy_handler(db, 0, 0);
103283   }
103284   return SQLITE_OK;
103285 }
103286
103287 /*
103288 ** Cause any pending operation to stop at its earliest opportunity.
103289 */
103290 SQLITE_API void sqlite3_interrupt(sqlite3 *db){
103291   db->u1.isInterrupted = 1;
103292 }
103293
103294
103295 /*
103296 ** This function is exactly the same as sqlite3_create_function(), except
103297 ** that it is designed to be called by internal code. The difference is
103298 ** that if a malloc() fails in sqlite3_create_function(), an error code
103299 ** is returned and the mallocFailed flag cleared. 
103300 */
103301 SQLITE_PRIVATE int sqlite3CreateFunc(
103302   sqlite3 *db,
103303   const char *zFunctionName,
103304   int nArg,
103305   int enc,
103306   void *pUserData,
103307   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
103308   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
103309   void (*xFinal)(sqlite3_context*)
103310 ){
103311   FuncDef *p;
103312   int nName;
103313
103314   assert( sqlite3_mutex_held(db->mutex) );
103315   if( zFunctionName==0 ||
103316       (xFunc && (xFinal || xStep)) || 
103317       (!xFunc && (xFinal && !xStep)) ||
103318       (!xFunc && (!xFinal && xStep)) ||
103319       (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
103320       (255<(nName = sqlite3Strlen30( zFunctionName))) ){
103321     return SQLITE_MISUSE_BKPT;
103322   }
103323   
103324 #ifndef SQLITE_OMIT_UTF16
103325   /* If SQLITE_UTF16 is specified as the encoding type, transform this
103326   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
103327   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
103328   **
103329   ** If SQLITE_ANY is specified, add three versions of the function
103330   ** to the hash table.
103331   */
103332   if( enc==SQLITE_UTF16 ){
103333     enc = SQLITE_UTF16NATIVE;
103334   }else if( enc==SQLITE_ANY ){
103335     int rc;
103336     rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
103337          pUserData, xFunc, xStep, xFinal);
103338     if( rc==SQLITE_OK ){
103339       rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
103340           pUserData, xFunc, xStep, xFinal);
103341     }
103342     if( rc!=SQLITE_OK ){
103343       return rc;
103344     }
103345     enc = SQLITE_UTF16BE;
103346   }
103347 #else
103348   enc = SQLITE_UTF8;
103349 #endif
103350   
103351   /* Check if an existing function is being overridden or deleted. If so,
103352   ** and there are active VMs, then return SQLITE_BUSY. If a function
103353   ** is being overridden/deleted but there are no active VMs, allow the
103354   ** operation to continue but invalidate all precompiled statements.
103355   */
103356   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
103357   if( p && p->iPrefEnc==enc && p->nArg==nArg ){
103358     if( db->activeVdbeCnt ){
103359       sqlite3Error(db, SQLITE_BUSY, 
103360         "unable to delete/modify user-function due to active statements");
103361       assert( !db->mallocFailed );
103362       return SQLITE_BUSY;
103363     }else{
103364       sqlite3ExpirePreparedStatements(db);
103365     }
103366   }
103367
103368   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
103369   assert(p || db->mallocFailed);
103370   if( !p ){
103371     return SQLITE_NOMEM;
103372   }
103373   p->flags = 0;
103374   p->xFunc = xFunc;
103375   p->xStep = xStep;
103376   p->xFinalize = xFinal;
103377   p->pUserData = pUserData;
103378   p->nArg = (u16)nArg;
103379   return SQLITE_OK;
103380 }
103381
103382 /*
103383 ** Create new user functions.
103384 */
103385 SQLITE_API int sqlite3_create_function(
103386   sqlite3 *db,
103387   const char *zFunctionName,
103388   int nArg,
103389   int enc,
103390   void *p,
103391   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
103392   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
103393   void (*xFinal)(sqlite3_context*)
103394 ){
103395   int rc;
103396   sqlite3_mutex_enter(db->mutex);
103397   rc = sqlite3CreateFunc(db, zFunctionName, nArg, enc, p, xFunc, xStep, xFinal);
103398   rc = sqlite3ApiExit(db, rc);
103399   sqlite3_mutex_leave(db->mutex);
103400   return rc;
103401 }
103402
103403 #ifndef SQLITE_OMIT_UTF16
103404 SQLITE_API int sqlite3_create_function16(
103405   sqlite3 *db,
103406   const void *zFunctionName,
103407   int nArg,
103408   int eTextRep,
103409   void *p,
103410   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
103411   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
103412   void (*xFinal)(sqlite3_context*)
103413 ){
103414   int rc;
103415   char *zFunc8;
103416   sqlite3_mutex_enter(db->mutex);
103417   assert( !db->mallocFailed );
103418   zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
103419   rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal);
103420   sqlite3DbFree(db, zFunc8);
103421   rc = sqlite3ApiExit(db, rc);
103422   sqlite3_mutex_leave(db->mutex);
103423   return rc;
103424 }
103425 #endif
103426
103427
103428 /*
103429 ** Declare that a function has been overloaded by a virtual table.
103430 **
103431 ** If the function already exists as a regular global function, then
103432 ** this routine is a no-op.  If the function does not exist, then create
103433 ** a new one that always throws a run-time error.  
103434 **
103435 ** When virtual tables intend to provide an overloaded function, they
103436 ** should call this routine to make sure the global function exists.
103437 ** A global function must exist in order for name resolution to work
103438 ** properly.
103439 */
103440 SQLITE_API int sqlite3_overload_function(
103441   sqlite3 *db,
103442   const char *zName,
103443   int nArg
103444 ){
103445   int nName = sqlite3Strlen30(zName);
103446   int rc;
103447   sqlite3_mutex_enter(db->mutex);
103448   if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
103449     sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
103450                       0, sqlite3InvalidFunction, 0, 0);
103451   }
103452   rc = sqlite3ApiExit(db, SQLITE_OK);
103453   sqlite3_mutex_leave(db->mutex);
103454   return rc;
103455 }
103456
103457 #ifndef SQLITE_OMIT_TRACE
103458 /*
103459 ** Register a trace function.  The pArg from the previously registered trace
103460 ** is returned.  
103461 **
103462 ** A NULL trace function means that no tracing is executes.  A non-NULL
103463 ** trace is a pointer to a function that is invoked at the start of each
103464 ** SQL statement.
103465 */
103466 SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
103467   void *pOld;
103468   sqlite3_mutex_enter(db->mutex);
103469   pOld = db->pTraceArg;
103470   db->xTrace = xTrace;
103471   db->pTraceArg = pArg;
103472   sqlite3_mutex_leave(db->mutex);
103473   return pOld;
103474 }
103475 /*
103476 ** Register a profile function.  The pArg from the previously registered 
103477 ** profile function is returned.  
103478 **
103479 ** A NULL profile function means that no profiling is executes.  A non-NULL
103480 ** profile is a pointer to a function that is invoked at the conclusion of
103481 ** each SQL statement that is run.
103482 */
103483 SQLITE_API void *sqlite3_profile(
103484   sqlite3 *db,
103485   void (*xProfile)(void*,const char*,sqlite_uint64),
103486   void *pArg
103487 ){
103488   void *pOld;
103489   sqlite3_mutex_enter(db->mutex);
103490   pOld = db->pProfileArg;
103491   db->xProfile = xProfile;
103492   db->pProfileArg = pArg;
103493   sqlite3_mutex_leave(db->mutex);
103494   return pOld;
103495 }
103496 #endif /* SQLITE_OMIT_TRACE */
103497
103498 /*** EXPERIMENTAL ***
103499 **
103500 ** Register a function to be invoked when a transaction comments.
103501 ** If the invoked function returns non-zero, then the commit becomes a
103502 ** rollback.
103503 */
103504 SQLITE_API void *sqlite3_commit_hook(
103505   sqlite3 *db,              /* Attach the hook to this database */
103506   int (*xCallback)(void*),  /* Function to invoke on each commit */
103507   void *pArg                /* Argument to the function */
103508 ){
103509   void *pOld;
103510   sqlite3_mutex_enter(db->mutex);
103511   pOld = db->pCommitArg;
103512   db->xCommitCallback = xCallback;
103513   db->pCommitArg = pArg;
103514   sqlite3_mutex_leave(db->mutex);
103515   return pOld;
103516 }
103517
103518 /*
103519 ** Register a callback to be invoked each time a row is updated,
103520 ** inserted or deleted using this database connection.
103521 */
103522 SQLITE_API void *sqlite3_update_hook(
103523   sqlite3 *db,              /* Attach the hook to this database */
103524   void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
103525   void *pArg                /* Argument to the function */
103526 ){
103527   void *pRet;
103528   sqlite3_mutex_enter(db->mutex);
103529   pRet = db->pUpdateArg;
103530   db->xUpdateCallback = xCallback;
103531   db->pUpdateArg = pArg;
103532   sqlite3_mutex_leave(db->mutex);
103533   return pRet;
103534 }
103535
103536 /*
103537 ** Register a callback to be invoked each time a transaction is rolled
103538 ** back by this database connection.
103539 */
103540 SQLITE_API void *sqlite3_rollback_hook(
103541   sqlite3 *db,              /* Attach the hook to this database */
103542   void (*xCallback)(void*), /* Callback function */
103543   void *pArg                /* Argument to the function */
103544 ){
103545   void *pRet;
103546   sqlite3_mutex_enter(db->mutex);
103547   pRet = db->pRollbackArg;
103548   db->xRollbackCallback = xCallback;
103549   db->pRollbackArg = pArg;
103550   sqlite3_mutex_leave(db->mutex);
103551   return pRet;
103552 }
103553
103554 #ifndef SQLITE_OMIT_WAL
103555 /*
103556 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
103557 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
103558 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
103559 ** wal_autocheckpoint()).
103560 */ 
103561 SQLITE_PRIVATE int sqlite3WalDefaultHook(
103562   void *pClientData,     /* Argument */
103563   sqlite3 *db,           /* Connection */
103564   const char *zDb,       /* Database */
103565   int nFrame             /* Size of WAL */
103566 ){
103567   if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
103568     sqlite3BeginBenignMalloc();
103569     sqlite3_wal_checkpoint(db, zDb);
103570     sqlite3EndBenignMalloc();
103571   }
103572   return SQLITE_OK;
103573 }
103574 #endif /* SQLITE_OMIT_WAL */
103575
103576 /*
103577 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
103578 ** a database after committing a transaction if there are nFrame or
103579 ** more frames in the log file. Passing zero or a negative value as the
103580 ** nFrame parameter disables automatic checkpoints entirely.
103581 **
103582 ** The callback registered by this function replaces any existing callback
103583 ** registered using sqlite3_wal_hook(). Likewise, registering a callback
103584 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
103585 ** configured by this function.
103586 */
103587 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
103588 #ifndef SQLITE_OMIT_WAL
103589   if( nFrame>0 ){
103590     sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
103591   }else{
103592     sqlite3_wal_hook(db, 0, 0);
103593   }
103594 #endif
103595   return SQLITE_OK;
103596 }
103597
103598 /*
103599 ** Register a callback to be invoked each time a transaction is written
103600 ** into the write-ahead-log by this database connection.
103601 */
103602 SQLITE_API void *sqlite3_wal_hook(
103603   sqlite3 *db,                    /* Attach the hook to this db handle */
103604   int(*xCallback)(void *, sqlite3*, const char*, int),
103605   void *pArg                      /* First argument passed to xCallback() */
103606 ){
103607 #ifndef SQLITE_OMIT_WAL
103608   void *pRet;
103609   sqlite3_mutex_enter(db->mutex);
103610   pRet = db->pWalArg;
103611   db->xWalCallback = xCallback;
103612   db->pWalArg = pArg;
103613   sqlite3_mutex_leave(db->mutex);
103614   return pRet;
103615 #else
103616   return 0;
103617 #endif
103618 }
103619
103620
103621 /*
103622 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
103623 ** to contains a zero-length string, all attached databases are 
103624 ** checkpointed.
103625 */
103626 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
103627 #ifdef SQLITE_OMIT_WAL
103628   return SQLITE_OK;
103629 #else
103630   int rc;                         /* Return code */
103631   int iDb = SQLITE_MAX_ATTACHED;  /* sqlite3.aDb[] index of db to checkpoint */
103632
103633   sqlite3_mutex_enter(db->mutex);
103634   if( zDb && zDb[0] ){
103635     iDb = sqlite3FindDbName(db, zDb);
103636   }
103637   if( iDb<0 ){
103638     rc = SQLITE_ERROR;
103639     sqlite3Error(db, SQLITE_ERROR, "unknown database: %s", zDb);
103640   }else{
103641     rc = sqlite3Checkpoint(db, iDb);
103642     sqlite3Error(db, rc, 0);
103643   }
103644   rc = sqlite3ApiExit(db, rc);
103645   sqlite3_mutex_leave(db->mutex);
103646   return rc;
103647 #endif
103648 }
103649
103650 #ifndef SQLITE_OMIT_WAL
103651 /*
103652 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
103653 ** not currently open in WAL mode.
103654 **
103655 ** If a transaction is open on the database being checkpointed, this 
103656 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If 
103657 ** an error occurs while running the checkpoint, an SQLite error code is 
103658 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
103659 **
103660 ** The mutex on database handle db should be held by the caller. The mutex
103661 ** associated with the specific b-tree being checkpointed is taken by
103662 ** this function while the checkpoint is running.
103663 **
103664 ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
103665 ** checkpointed. If an error is encountered it is returned immediately -
103666 ** no attempt is made to checkpoint any remaining databases.
103667 */
103668 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb){
103669   int rc = SQLITE_OK;             /* Return code */
103670   int i;                          /* Used to iterate through attached dbs */
103671
103672   assert( sqlite3_mutex_held(db->mutex) );
103673
103674   for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
103675     if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
103676       Btree *pBt = db->aDb[i].pBt;
103677       if( pBt ){
103678         if( sqlite3BtreeIsInReadTrans(pBt) ){
103679           rc = SQLITE_LOCKED;
103680         }else{
103681           sqlite3BtreeEnter(pBt);
103682           rc = sqlite3PagerCheckpoint(sqlite3BtreePager(pBt));
103683           sqlite3BtreeLeave(pBt);
103684         }
103685       }
103686     }
103687   }
103688
103689   return rc;
103690 }
103691 #endif /* SQLITE_OMIT_WAL */
103692
103693 /*
103694 ** This function returns true if main-memory should be used instead of
103695 ** a temporary file for transient pager files and statement journals.
103696 ** The value returned depends on the value of db->temp_store (runtime
103697 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
103698 ** following table describes the relationship between these two values
103699 ** and this functions return value.
103700 **
103701 **   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
103702 **   -----------------     --------------     ------------------------------
103703 **   0                     any                file      (return 0)
103704 **   1                     1                  file      (return 0)
103705 **   1                     2                  memory    (return 1)
103706 **   1                     0                  file      (return 0)
103707 **   2                     1                  file      (return 0)
103708 **   2                     2                  memory    (return 1)
103709 **   2                     0                  memory    (return 1)
103710 **   3                     any                memory    (return 1)
103711 */
103712 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
103713 #if SQLITE_TEMP_STORE==1
103714   return ( db->temp_store==2 );
103715 #endif
103716 #if SQLITE_TEMP_STORE==2
103717   return ( db->temp_store!=1 );
103718 #endif
103719 #if SQLITE_TEMP_STORE==3
103720   return 1;
103721 #endif
103722 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
103723   return 0;
103724 #endif
103725 }
103726
103727 /*
103728 ** This routine is called to create a connection to a database BTree
103729 ** driver.  If zFilename is the name of a file, then that file is
103730 ** opened and used.  If zFilename is the magic name ":memory:" then
103731 ** the database is stored in memory (and is thus forgotten as soon as
103732 ** the connection is closed.)  If zFilename is NULL then the database
103733 ** is a "virtual" database for transient use only and is deleted as
103734 ** soon as the connection is closed.
103735 **
103736 ** A virtual database can be either a disk file (that is automatically
103737 ** deleted when the file is closed) or it an be held entirely in memory.
103738 ** The sqlite3TempInMemory() function is used to determine which.
103739 */
103740 SQLITE_PRIVATE int sqlite3BtreeFactory(
103741   sqlite3 *db,              /* Main database when opening aux otherwise 0 */
103742   const char *zFilename,    /* Name of the file containing the BTree database */
103743   int omitJournal,          /* if TRUE then do not journal this file */
103744   int nCache,               /* How many pages in the page cache */
103745   int vfsFlags,             /* Flags passed through to vfsOpen */
103746   Btree **ppBtree           /* Pointer to new Btree object written here */
103747 ){
103748   int btFlags = 0;
103749   int rc;
103750   
103751   assert( sqlite3_mutex_held(db->mutex) );
103752   assert( ppBtree != 0);
103753   if( omitJournal ){
103754     btFlags |= BTREE_OMIT_JOURNAL;
103755   }
103756   if( db->flags & SQLITE_NoReadlock ){
103757     btFlags |= BTREE_NO_READLOCK;
103758   }
103759 #ifndef SQLITE_OMIT_MEMORYDB
103760   if( zFilename==0 && sqlite3TempInMemory(db) ){
103761     zFilename = ":memory:";
103762   }
103763 #endif
103764
103765   if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (zFilename==0 || *zFilename==0) ){
103766     vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
103767   }
103768   rc = sqlite3BtreeOpen(zFilename, (sqlite3 *)db, ppBtree, btFlags, vfsFlags);
103769
103770   /* If the B-Tree was successfully opened, set the pager-cache size to the
103771   ** default value. Except, if the call to BtreeOpen() returned a handle
103772   ** open on an existing shared pager-cache, do not change the pager-cache 
103773   ** size.
103774   */
103775   if( rc==SQLITE_OK && 0==sqlite3BtreeSchema(*ppBtree, 0, 0) ){
103776     sqlite3BtreeSetCacheSize(*ppBtree, nCache);
103777   }
103778   return rc;
103779 }
103780
103781 /*
103782 ** Return UTF-8 encoded English language explanation of the most recent
103783 ** error.
103784 */
103785 SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
103786   const char *z;
103787   if( !db ){
103788     return sqlite3ErrStr(SQLITE_NOMEM);
103789   }
103790   if( !sqlite3SafetyCheckSickOrOk(db) ){
103791     return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
103792   }
103793   sqlite3_mutex_enter(db->mutex);
103794   if( db->mallocFailed ){
103795     z = sqlite3ErrStr(SQLITE_NOMEM);
103796   }else{
103797     z = (char*)sqlite3_value_text(db->pErr);
103798     assert( !db->mallocFailed );
103799     if( z==0 ){
103800       z = sqlite3ErrStr(db->errCode);
103801     }
103802   }
103803   sqlite3_mutex_leave(db->mutex);
103804   return z;
103805 }
103806
103807 #ifndef SQLITE_OMIT_UTF16
103808 /*
103809 ** Return UTF-16 encoded English language explanation of the most recent
103810 ** error.
103811 */
103812 SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
103813   static const u16 outOfMem[] = {
103814     'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
103815   };
103816   static const u16 misuse[] = {
103817     'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ', 
103818     'r', 'o', 'u', 't', 'i', 'n', 'e', ' ', 
103819     'c', 'a', 'l', 'l', 'e', 'd', ' ', 
103820     'o', 'u', 't', ' ', 
103821     'o', 'f', ' ', 
103822     's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
103823   };
103824
103825   const void *z;
103826   if( !db ){
103827     return (void *)outOfMem;
103828   }
103829   if( !sqlite3SafetyCheckSickOrOk(db) ){
103830     return (void *)misuse;
103831   }
103832   sqlite3_mutex_enter(db->mutex);
103833   if( db->mallocFailed ){
103834     z = (void *)outOfMem;
103835   }else{
103836     z = sqlite3_value_text16(db->pErr);
103837     if( z==0 ){
103838       sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
103839            SQLITE_UTF8, SQLITE_STATIC);
103840       z = sqlite3_value_text16(db->pErr);
103841     }
103842     /* A malloc() may have failed within the call to sqlite3_value_text16()
103843     ** above. If this is the case, then the db->mallocFailed flag needs to
103844     ** be cleared before returning. Do this directly, instead of via
103845     ** sqlite3ApiExit(), to avoid setting the database handle error message.
103846     */
103847     db->mallocFailed = 0;
103848   }
103849   sqlite3_mutex_leave(db->mutex);
103850   return z;
103851 }
103852 #endif /* SQLITE_OMIT_UTF16 */
103853
103854 /*
103855 ** Return the most recent error code generated by an SQLite routine. If NULL is
103856 ** passed to this function, we assume a malloc() failed during sqlite3_open().
103857 */
103858 SQLITE_API int sqlite3_errcode(sqlite3 *db){
103859   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
103860     return SQLITE_MISUSE_BKPT;
103861   }
103862   if( !db || db->mallocFailed ){
103863     return SQLITE_NOMEM;
103864   }
103865   return db->errCode & db->errMask;
103866 }
103867 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
103868   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
103869     return SQLITE_MISUSE_BKPT;
103870   }
103871   if( !db || db->mallocFailed ){
103872     return SQLITE_NOMEM;
103873   }
103874   return db->errCode;
103875 }
103876
103877 /*
103878 ** Create a new collating function for database "db".  The name is zName
103879 ** and the encoding is enc.
103880 */
103881 static int createCollation(
103882   sqlite3* db,
103883   const char *zName, 
103884   u8 enc,
103885   u8 collType,
103886   void* pCtx,
103887   int(*xCompare)(void*,int,const void*,int,const void*),
103888   void(*xDel)(void*)
103889 ){
103890   CollSeq *pColl;
103891   int enc2;
103892   int nName = sqlite3Strlen30(zName);
103893   
103894   assert( sqlite3_mutex_held(db->mutex) );
103895
103896   /* If SQLITE_UTF16 is specified as the encoding type, transform this
103897   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
103898   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
103899   */
103900   enc2 = enc;
103901   testcase( enc2==SQLITE_UTF16 );
103902   testcase( enc2==SQLITE_UTF16_ALIGNED );
103903   if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
103904     enc2 = SQLITE_UTF16NATIVE;
103905   }
103906   if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
103907     return SQLITE_MISUSE_BKPT;
103908   }
103909
103910   /* Check if this call is removing or replacing an existing collation 
103911   ** sequence. If so, and there are active VMs, return busy. If there
103912   ** are no active VMs, invalidate any pre-compiled statements.
103913   */
103914   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
103915   if( pColl && pColl->xCmp ){
103916     if( db->activeVdbeCnt ){
103917       sqlite3Error(db, SQLITE_BUSY, 
103918         "unable to delete/modify collation sequence due to active statements");
103919       return SQLITE_BUSY;
103920     }
103921     sqlite3ExpirePreparedStatements(db);
103922
103923     /* If collation sequence pColl was created directly by a call to
103924     ** sqlite3_create_collation, and not generated by synthCollSeq(),
103925     ** then any copies made by synthCollSeq() need to be invalidated.
103926     ** Also, collation destructor - CollSeq.xDel() - function may need
103927     ** to be called.
103928     */ 
103929     if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
103930       CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
103931       int j;
103932       for(j=0; j<3; j++){
103933         CollSeq *p = &aColl[j];
103934         if( p->enc==pColl->enc ){
103935           if( p->xDel ){
103936             p->xDel(p->pUser);
103937           }
103938           p->xCmp = 0;
103939         }
103940       }
103941     }
103942   }
103943
103944   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
103945   if( pColl ){
103946     pColl->xCmp = xCompare;
103947     pColl->pUser = pCtx;
103948     pColl->xDel = xDel;
103949     pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
103950     pColl->type = collType;
103951   }
103952   sqlite3Error(db, SQLITE_OK, 0);
103953   return SQLITE_OK;
103954 }
103955
103956
103957 /*
103958 ** This array defines hard upper bounds on limit values.  The
103959 ** initializer must be kept in sync with the SQLITE_LIMIT_*
103960 ** #defines in sqlite3.h.
103961 */
103962 static const int aHardLimit[] = {
103963   SQLITE_MAX_LENGTH,
103964   SQLITE_MAX_SQL_LENGTH,
103965   SQLITE_MAX_COLUMN,
103966   SQLITE_MAX_EXPR_DEPTH,
103967   SQLITE_MAX_COMPOUND_SELECT,
103968   SQLITE_MAX_VDBE_OP,
103969   SQLITE_MAX_FUNCTION_ARG,
103970   SQLITE_MAX_ATTACHED,
103971   SQLITE_MAX_LIKE_PATTERN_LENGTH,
103972   SQLITE_MAX_VARIABLE_NUMBER,
103973   SQLITE_MAX_TRIGGER_DEPTH,
103974 };
103975
103976 /*
103977 ** Make sure the hard limits are set to reasonable values
103978 */
103979 #if SQLITE_MAX_LENGTH<100
103980 # error SQLITE_MAX_LENGTH must be at least 100
103981 #endif
103982 #if SQLITE_MAX_SQL_LENGTH<100
103983 # error SQLITE_MAX_SQL_LENGTH must be at least 100
103984 #endif
103985 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
103986 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
103987 #endif
103988 #if SQLITE_MAX_COMPOUND_SELECT<2
103989 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
103990 #endif
103991 #if SQLITE_MAX_VDBE_OP<40
103992 # error SQLITE_MAX_VDBE_OP must be at least 40
103993 #endif
103994 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
103995 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
103996 #endif
103997 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>30
103998 # error SQLITE_MAX_ATTACHED must be between 0 and 30
103999 #endif
104000 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
104001 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
104002 #endif
104003 #if SQLITE_MAX_COLUMN>32767
104004 # error SQLITE_MAX_COLUMN must not exceed 32767
104005 #endif
104006 #if SQLITE_MAX_TRIGGER_DEPTH<1
104007 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
104008 #endif
104009
104010
104011 /*
104012 ** Change the value of a limit.  Report the old value.
104013 ** If an invalid limit index is supplied, report -1.
104014 ** Make no changes but still report the old value if the
104015 ** new limit is negative.
104016 **
104017 ** A new lower limit does not shrink existing constructs.
104018 ** It merely prevents new constructs that exceed the limit
104019 ** from forming.
104020 */
104021 SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
104022   int oldLimit;
104023   if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
104024     return -1;
104025   }
104026   oldLimit = db->aLimit[limitId];
104027   if( newLimit>=0 ){
104028     if( newLimit>aHardLimit[limitId] ){
104029       newLimit = aHardLimit[limitId];
104030     }
104031     db->aLimit[limitId] = newLimit;
104032   }
104033   return oldLimit;
104034 }
104035
104036 /*
104037 ** This routine does the work of opening a database on behalf of
104038 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"  
104039 ** is UTF-8 encoded.
104040 */
104041 static int openDatabase(
104042   const char *zFilename, /* Database filename UTF-8 encoded */
104043   sqlite3 **ppDb,        /* OUT: Returned database handle */
104044   unsigned flags,        /* Operational flags */
104045   const char *zVfs       /* Name of the VFS to use */
104046 ){
104047   sqlite3 *db;
104048   int rc;
104049   int isThreadsafe;
104050
104051   *ppDb = 0;
104052 #ifndef SQLITE_OMIT_AUTOINIT
104053   rc = sqlite3_initialize();
104054   if( rc ) return rc;
104055 #endif
104056
104057   if( sqlite3GlobalConfig.bCoreMutex==0 ){
104058     isThreadsafe = 0;
104059   }else if( flags & SQLITE_OPEN_NOMUTEX ){
104060     isThreadsafe = 0;
104061   }else if( flags & SQLITE_OPEN_FULLMUTEX ){
104062     isThreadsafe = 1;
104063   }else{
104064     isThreadsafe = sqlite3GlobalConfig.bFullMutex;
104065   }
104066   if( flags & SQLITE_OPEN_PRIVATECACHE ){
104067     flags &= ~SQLITE_OPEN_SHAREDCACHE;
104068   }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
104069     flags |= SQLITE_OPEN_SHAREDCACHE;
104070   }
104071
104072   /* Remove harmful bits from the flags parameter
104073   **
104074   ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
104075   ** dealt with in the previous code block.  Besides these, the only
104076   ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
104077   ** SQLITE_OPEN_READWRITE, and SQLITE_OPEN_CREATE.  Silently mask
104078   ** off all other flags.
104079   */
104080   flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
104081                SQLITE_OPEN_EXCLUSIVE |
104082                SQLITE_OPEN_MAIN_DB |
104083                SQLITE_OPEN_TEMP_DB | 
104084                SQLITE_OPEN_TRANSIENT_DB | 
104085                SQLITE_OPEN_MAIN_JOURNAL | 
104086                SQLITE_OPEN_TEMP_JOURNAL | 
104087                SQLITE_OPEN_SUBJOURNAL | 
104088                SQLITE_OPEN_MASTER_JOURNAL |
104089                SQLITE_OPEN_NOMUTEX |
104090                SQLITE_OPEN_FULLMUTEX
104091              );
104092
104093   /* Allocate the sqlite data structure */
104094   db = sqlite3MallocZero( sizeof(sqlite3) );
104095   if( db==0 ) goto opendb_out;
104096   if( isThreadsafe ){
104097     db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
104098     if( db->mutex==0 ){
104099       sqlite3_free(db);
104100       db = 0;
104101       goto opendb_out;
104102     }
104103   }
104104   sqlite3_mutex_enter(db->mutex);
104105   db->errMask = 0xff;
104106   db->nDb = 2;
104107   db->magic = SQLITE_MAGIC_BUSY;
104108   db->aDb = db->aDbStatic;
104109
104110   assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
104111   memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
104112   db->autoCommit = 1;
104113   db->nextAutovac = -1;
104114   db->nextPagesize = 0;
104115   db->flags |= SQLITE_ShortColNames | SQLITE_AutoIndex
104116 #if SQLITE_DEFAULT_FILE_FORMAT<4
104117                  | SQLITE_LegacyFileFmt
104118 #endif
104119 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
104120                  | SQLITE_LoadExtension
104121 #endif
104122 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
104123                  | SQLITE_RecTriggers
104124 #endif
104125       ;
104126   sqlite3HashInit(&db->aCollSeq);
104127 #ifndef SQLITE_OMIT_VIRTUALTABLE
104128   sqlite3HashInit(&db->aModule);
104129 #endif
104130
104131   db->pVfs = sqlite3_vfs_find(zVfs);
104132   if( !db->pVfs ){
104133     rc = SQLITE_ERROR;
104134     sqlite3Error(db, rc, "no such vfs: %s", zVfs);
104135     goto opendb_out;
104136   }
104137
104138   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
104139   ** and UTF-16, so add a version for each to avoid any unnecessary
104140   ** conversions. The only error that can occur here is a malloc() failure.
104141   */
104142   createCollation(db, "BINARY", SQLITE_UTF8, SQLITE_COLL_BINARY, 0,
104143                   binCollFunc, 0);
104144   createCollation(db, "BINARY", SQLITE_UTF16BE, SQLITE_COLL_BINARY, 0,
104145                   binCollFunc, 0);
104146   createCollation(db, "BINARY", SQLITE_UTF16LE, SQLITE_COLL_BINARY, 0,
104147                   binCollFunc, 0);
104148   createCollation(db, "RTRIM", SQLITE_UTF8, SQLITE_COLL_USER, (void*)1,
104149                   binCollFunc, 0);
104150   if( db->mallocFailed ){
104151     goto opendb_out;
104152   }
104153   db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
104154   assert( db->pDfltColl!=0 );
104155
104156   /* Also add a UTF-8 case-insensitive collation sequence. */
104157   createCollation(db, "NOCASE", SQLITE_UTF8, SQLITE_COLL_NOCASE, 0,
104158                   nocaseCollatingFunc, 0);
104159
104160   /* Open the backend database driver */
104161   db->openFlags = flags;
104162   rc = sqlite3BtreeFactory(db, zFilename, 0, SQLITE_DEFAULT_CACHE_SIZE, 
104163                            flags | SQLITE_OPEN_MAIN_DB,
104164                            &db->aDb[0].pBt);
104165   if( rc!=SQLITE_OK ){
104166     if( rc==SQLITE_IOERR_NOMEM ){
104167       rc = SQLITE_NOMEM;
104168     }
104169     sqlite3Error(db, rc, 0);
104170     goto opendb_out;
104171   }
104172   db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
104173   db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
104174
104175
104176   /* The default safety_level for the main database is 'full'; for the temp
104177   ** database it is 'NONE'. This matches the pager layer defaults.  
104178   */
104179   db->aDb[0].zName = "main";
104180   db->aDb[0].safety_level = 3;
104181   db->aDb[1].zName = "temp";
104182   db->aDb[1].safety_level = 1;
104183
104184   db->magic = SQLITE_MAGIC_OPEN;
104185   if( db->mallocFailed ){
104186     goto opendb_out;
104187   }
104188
104189   /* Register all built-in functions, but do not attempt to read the
104190   ** database schema yet. This is delayed until the first time the database
104191   ** is accessed.
104192   */
104193   sqlite3Error(db, SQLITE_OK, 0);
104194   sqlite3RegisterBuiltinFunctions(db);
104195
104196   /* Load automatic extensions - extensions that have been registered
104197   ** using the sqlite3_automatic_extension() API.
104198   */
104199   sqlite3AutoLoadExtensions(db);
104200   rc = sqlite3_errcode(db);
104201   if( rc!=SQLITE_OK ){
104202     goto opendb_out;
104203   }
104204
104205 #ifdef SQLITE_ENABLE_FTS1
104206   if( !db->mallocFailed ){
104207     extern int sqlite3Fts1Init(sqlite3*);
104208     rc = sqlite3Fts1Init(db);
104209   }
104210 #endif
104211
104212 #ifdef SQLITE_ENABLE_FTS2
104213   if( !db->mallocFailed && rc==SQLITE_OK ){
104214     extern int sqlite3Fts2Init(sqlite3*);
104215     rc = sqlite3Fts2Init(db);
104216   }
104217 #endif
104218
104219 #ifdef SQLITE_ENABLE_FTS3
104220   if( !db->mallocFailed && rc==SQLITE_OK ){
104221     rc = sqlite3Fts3Init(db);
104222   }
104223 #endif
104224
104225 #ifdef SQLITE_ENABLE_ICU
104226   if( !db->mallocFailed && rc==SQLITE_OK ){
104227     rc = sqlite3IcuInit(db);
104228   }
104229 #endif
104230
104231 #ifdef SQLITE_ENABLE_RTREE
104232   if( !db->mallocFailed && rc==SQLITE_OK){
104233     rc = sqlite3RtreeInit(db);
104234   }
104235 #endif
104236
104237   sqlite3Error(db, rc, 0);
104238
104239   /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
104240   ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
104241   ** mode.  Doing nothing at all also makes NORMAL the default.
104242   */
104243 #ifdef SQLITE_DEFAULT_LOCKING_MODE
104244   db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
104245   sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
104246                           SQLITE_DEFAULT_LOCKING_MODE);
104247 #endif
104248
104249   /* Enable the lookaside-malloc subsystem */
104250   setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
104251                         sqlite3GlobalConfig.nLookaside);
104252
104253   sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
104254
104255 opendb_out:
104256   if( db ){
104257     assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
104258     sqlite3_mutex_leave(db->mutex);
104259   }
104260   rc = sqlite3_errcode(db);
104261   if( rc==SQLITE_NOMEM ){
104262     sqlite3_close(db);
104263     db = 0;
104264   }else if( rc!=SQLITE_OK ){
104265     db->magic = SQLITE_MAGIC_SICK;
104266   }
104267   *ppDb = db;
104268   return sqlite3ApiExit(0, rc);
104269 }
104270
104271 /*
104272 ** Open a new database handle.
104273 */
104274 SQLITE_API int sqlite3_open(
104275   const char *zFilename, 
104276   sqlite3 **ppDb 
104277 ){
104278   return openDatabase(zFilename, ppDb,
104279                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
104280 }
104281 SQLITE_API int sqlite3_open_v2(
104282   const char *filename,   /* Database filename (UTF-8) */
104283   sqlite3 **ppDb,         /* OUT: SQLite db handle */
104284   int flags,              /* Flags */
104285   const char *zVfs        /* Name of VFS module to use */
104286 ){
104287   return openDatabase(filename, ppDb, flags, zVfs);
104288 }
104289
104290 #ifndef SQLITE_OMIT_UTF16
104291 /*
104292 ** Open a new database handle.
104293 */
104294 SQLITE_API int sqlite3_open16(
104295   const void *zFilename, 
104296   sqlite3 **ppDb
104297 ){
104298   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
104299   sqlite3_value *pVal;
104300   int rc;
104301
104302   assert( zFilename );
104303   assert( ppDb );
104304   *ppDb = 0;
104305 #ifndef SQLITE_OMIT_AUTOINIT
104306   rc = sqlite3_initialize();
104307   if( rc ) return rc;
104308 #endif
104309   pVal = sqlite3ValueNew(0);
104310   sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
104311   zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
104312   if( zFilename8 ){
104313     rc = openDatabase(zFilename8, ppDb,
104314                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
104315     assert( *ppDb || rc==SQLITE_NOMEM );
104316     if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
104317       ENC(*ppDb) = SQLITE_UTF16NATIVE;
104318     }
104319   }else{
104320     rc = SQLITE_NOMEM;
104321   }
104322   sqlite3ValueFree(pVal);
104323
104324   return sqlite3ApiExit(0, rc);
104325 }
104326 #endif /* SQLITE_OMIT_UTF16 */
104327
104328 /*
104329 ** Register a new collation sequence with the database handle db.
104330 */
104331 SQLITE_API int sqlite3_create_collation(
104332   sqlite3* db, 
104333   const char *zName, 
104334   int enc, 
104335   void* pCtx,
104336   int(*xCompare)(void*,int,const void*,int,const void*)
104337 ){
104338   int rc;
104339   sqlite3_mutex_enter(db->mutex);
104340   assert( !db->mallocFailed );
104341   rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
104342   rc = sqlite3ApiExit(db, rc);
104343   sqlite3_mutex_leave(db->mutex);
104344   return rc;
104345 }
104346
104347 /*
104348 ** Register a new collation sequence with the database handle db.
104349 */
104350 SQLITE_API int sqlite3_create_collation_v2(
104351   sqlite3* db, 
104352   const char *zName, 
104353   int enc, 
104354   void* pCtx,
104355   int(*xCompare)(void*,int,const void*,int,const void*),
104356   void(*xDel)(void*)
104357 ){
104358   int rc;
104359   sqlite3_mutex_enter(db->mutex);
104360   assert( !db->mallocFailed );
104361   rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, xDel);
104362   rc = sqlite3ApiExit(db, rc);
104363   sqlite3_mutex_leave(db->mutex);
104364   return rc;
104365 }
104366
104367 #ifndef SQLITE_OMIT_UTF16
104368 /*
104369 ** Register a new collation sequence with the database handle db.
104370 */
104371 SQLITE_API int sqlite3_create_collation16(
104372   sqlite3* db, 
104373   const void *zName,
104374   int enc, 
104375   void* pCtx,
104376   int(*xCompare)(void*,int,const void*,int,const void*)
104377 ){
104378   int rc = SQLITE_OK;
104379   char *zName8;
104380   sqlite3_mutex_enter(db->mutex);
104381   assert( !db->mallocFailed );
104382   zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
104383   if( zName8 ){
104384     rc = createCollation(db, zName8, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
104385     sqlite3DbFree(db, zName8);
104386   }
104387   rc = sqlite3ApiExit(db, rc);
104388   sqlite3_mutex_leave(db->mutex);
104389   return rc;
104390 }
104391 #endif /* SQLITE_OMIT_UTF16 */
104392
104393 /*
104394 ** Register a collation sequence factory callback with the database handle
104395 ** db. Replace any previously installed collation sequence factory.
104396 */
104397 SQLITE_API int sqlite3_collation_needed(
104398   sqlite3 *db, 
104399   void *pCollNeededArg, 
104400   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
104401 ){
104402   sqlite3_mutex_enter(db->mutex);
104403   db->xCollNeeded = xCollNeeded;
104404   db->xCollNeeded16 = 0;
104405   db->pCollNeededArg = pCollNeededArg;
104406   sqlite3_mutex_leave(db->mutex);
104407   return SQLITE_OK;
104408 }
104409
104410 #ifndef SQLITE_OMIT_UTF16
104411 /*
104412 ** Register a collation sequence factory callback with the database handle
104413 ** db. Replace any previously installed collation sequence factory.
104414 */
104415 SQLITE_API int sqlite3_collation_needed16(
104416   sqlite3 *db, 
104417   void *pCollNeededArg, 
104418   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
104419 ){
104420   sqlite3_mutex_enter(db->mutex);
104421   db->xCollNeeded = 0;
104422   db->xCollNeeded16 = xCollNeeded16;
104423   db->pCollNeededArg = pCollNeededArg;
104424   sqlite3_mutex_leave(db->mutex);
104425   return SQLITE_OK;
104426 }
104427 #endif /* SQLITE_OMIT_UTF16 */
104428
104429 #ifndef SQLITE_OMIT_DEPRECATED
104430 /*
104431 ** This function is now an anachronism. It used to be used to recover from a
104432 ** malloc() failure, but SQLite now does this automatically.
104433 */
104434 SQLITE_API int sqlite3_global_recover(void){
104435   return SQLITE_OK;
104436 }
104437 #endif
104438
104439 /*
104440 ** Test to see whether or not the database connection is in autocommit
104441 ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
104442 ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
104443 ** by the next COMMIT or ROLLBACK.
104444 **
104445 ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
104446 */
104447 SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
104448   return db->autoCommit;
104449 }
104450
104451 /*
104452 ** The following routines are subtitutes for constants SQLITE_CORRUPT,
104453 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
104454 ** constants.  They server two purposes:
104455 **
104456 **   1.  Serve as a convenient place to set a breakpoint in a debugger
104457 **       to detect when version error conditions occurs.
104458 **
104459 **   2.  Invoke sqlite3_log() to provide the source code location where
104460 **       a low-level error is first detected.
104461 */
104462 SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
104463   testcase( sqlite3GlobalConfig.xLog!=0 );
104464   sqlite3_log(SQLITE_CORRUPT,
104465               "database corruption at line %d of [%.10s]",
104466               lineno, 20+sqlite3_sourceid());
104467   return SQLITE_CORRUPT;
104468 }
104469 SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
104470   testcase( sqlite3GlobalConfig.xLog!=0 );
104471   sqlite3_log(SQLITE_MISUSE, 
104472               "misuse at line %d of [%.10s]",
104473               lineno, 20+sqlite3_sourceid());
104474   return SQLITE_MISUSE;
104475 }
104476 SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
104477   testcase( sqlite3GlobalConfig.xLog!=0 );
104478   sqlite3_log(SQLITE_CANTOPEN, 
104479               "cannot open file at line %d of [%.10s]",
104480               lineno, 20+sqlite3_sourceid());
104481   return SQLITE_CANTOPEN;
104482 }
104483
104484
104485 #ifndef SQLITE_OMIT_DEPRECATED
104486 /*
104487 ** This is a convenience routine that makes sure that all thread-specific
104488 ** data for this thread has been deallocated.
104489 **
104490 ** SQLite no longer uses thread-specific data so this routine is now a
104491 ** no-op.  It is retained for historical compatibility.
104492 */
104493 SQLITE_API void sqlite3_thread_cleanup(void){
104494 }
104495 #endif
104496
104497 /*
104498 ** Return meta information about a specific column of a database table.
104499 ** See comment in sqlite3.h (sqlite.h.in) for details.
104500 */
104501 #ifdef SQLITE_ENABLE_COLUMN_METADATA
104502 SQLITE_API int sqlite3_table_column_metadata(
104503   sqlite3 *db,                /* Connection handle */
104504   const char *zDbName,        /* Database name or NULL */
104505   const char *zTableName,     /* Table name */
104506   const char *zColumnName,    /* Column name */
104507   char const **pzDataType,    /* OUTPUT: Declared data type */
104508   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
104509   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
104510   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
104511   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
104512 ){
104513   int rc;
104514   char *zErrMsg = 0;
104515   Table *pTab = 0;
104516   Column *pCol = 0;
104517   int iCol;
104518
104519   char const *zDataType = 0;
104520   char const *zCollSeq = 0;
104521   int notnull = 0;
104522   int primarykey = 0;
104523   int autoinc = 0;
104524
104525   /* Ensure the database schema has been loaded */
104526   sqlite3_mutex_enter(db->mutex);
104527   sqlite3BtreeEnterAll(db);
104528   rc = sqlite3Init(db, &zErrMsg);
104529   if( SQLITE_OK!=rc ){
104530     goto error_out;
104531   }
104532
104533   /* Locate the table in question */
104534   pTab = sqlite3FindTable(db, zTableName, zDbName);
104535   if( !pTab || pTab->pSelect ){
104536     pTab = 0;
104537     goto error_out;
104538   }
104539
104540   /* Find the column for which info is requested */
104541   if( sqlite3IsRowid(zColumnName) ){
104542     iCol = pTab->iPKey;
104543     if( iCol>=0 ){
104544       pCol = &pTab->aCol[iCol];
104545     }
104546   }else{
104547     for(iCol=0; iCol<pTab->nCol; iCol++){
104548       pCol = &pTab->aCol[iCol];
104549       if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
104550         break;
104551       }
104552     }
104553     if( iCol==pTab->nCol ){
104554       pTab = 0;
104555       goto error_out;
104556     }
104557   }
104558
104559   /* The following block stores the meta information that will be returned
104560   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
104561   ** and autoinc. At this point there are two possibilities:
104562   ** 
104563   **     1. The specified column name was rowid", "oid" or "_rowid_" 
104564   **        and there is no explicitly declared IPK column. 
104565   **
104566   **     2. The table is not a view and the column name identified an 
104567   **        explicitly declared column. Copy meta information from *pCol.
104568   */ 
104569   if( pCol ){
104570     zDataType = pCol->zType;
104571     zCollSeq = pCol->zColl;
104572     notnull = pCol->notNull!=0;
104573     primarykey  = pCol->isPrimKey!=0;
104574     autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
104575   }else{
104576     zDataType = "INTEGER";
104577     primarykey = 1;
104578   }
104579   if( !zCollSeq ){
104580     zCollSeq = "BINARY";
104581   }
104582
104583 error_out:
104584   sqlite3BtreeLeaveAll(db);
104585
104586   /* Whether the function call succeeded or failed, set the output parameters
104587   ** to whatever their local counterparts contain. If an error did occur,
104588   ** this has the effect of zeroing all output parameters.
104589   */
104590   if( pzDataType ) *pzDataType = zDataType;
104591   if( pzCollSeq ) *pzCollSeq = zCollSeq;
104592   if( pNotNull ) *pNotNull = notnull;
104593   if( pPrimaryKey ) *pPrimaryKey = primarykey;
104594   if( pAutoinc ) *pAutoinc = autoinc;
104595
104596   if( SQLITE_OK==rc && !pTab ){
104597     sqlite3DbFree(db, zErrMsg);
104598     zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
104599         zColumnName);
104600     rc = SQLITE_ERROR;
104601   }
104602   sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
104603   sqlite3DbFree(db, zErrMsg);
104604   rc = sqlite3ApiExit(db, rc);
104605   sqlite3_mutex_leave(db->mutex);
104606   return rc;
104607 }
104608 #endif
104609
104610 /*
104611 ** Sleep for a little while.  Return the amount of time slept.
104612 */
104613 SQLITE_API int sqlite3_sleep(int ms){
104614   sqlite3_vfs *pVfs;
104615   int rc;
104616   pVfs = sqlite3_vfs_find(0);
104617   if( pVfs==0 ) return 0;
104618
104619   /* This function works in milliseconds, but the underlying OsSleep() 
104620   ** API uses microseconds. Hence the 1000's.
104621   */
104622   rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
104623   return rc;
104624 }
104625
104626 /*
104627 ** Enable or disable the extended result codes.
104628 */
104629 SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
104630   sqlite3_mutex_enter(db->mutex);
104631   db->errMask = onoff ? 0xffffffff : 0xff;
104632   sqlite3_mutex_leave(db->mutex);
104633   return SQLITE_OK;
104634 }
104635
104636 /*
104637 ** Invoke the xFileControl method on a particular database.
104638 */
104639 SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
104640   int rc = SQLITE_ERROR;
104641   int iDb;
104642   sqlite3_mutex_enter(db->mutex);
104643   if( zDbName==0 ){
104644     iDb = 0;
104645   }else{
104646     for(iDb=0; iDb<db->nDb; iDb++){
104647       if( strcmp(db->aDb[iDb].zName, zDbName)==0 ) break;
104648     }
104649   }
104650   if( iDb<db->nDb ){
104651     Btree *pBtree = db->aDb[iDb].pBt;
104652     if( pBtree ){
104653       Pager *pPager;
104654       sqlite3_file *fd;
104655       sqlite3BtreeEnter(pBtree);
104656       pPager = sqlite3BtreePager(pBtree);
104657       assert( pPager!=0 );
104658       fd = sqlite3PagerFile(pPager);
104659       assert( fd!=0 );
104660       if( fd->pMethods ){
104661         rc = sqlite3OsFileControl(fd, op, pArg);
104662       }
104663       sqlite3BtreeLeave(pBtree);
104664     }
104665   }
104666   sqlite3_mutex_leave(db->mutex);
104667   return rc;   
104668 }
104669
104670 /*
104671 ** Interface to the testing logic.
104672 */
104673 SQLITE_API int sqlite3_test_control(int op, ...){
104674   int rc = 0;
104675 #ifndef SQLITE_OMIT_BUILTIN_TEST
104676   va_list ap;
104677   va_start(ap, op);
104678   switch( op ){
104679
104680     /*
104681     ** Save the current state of the PRNG.
104682     */
104683     case SQLITE_TESTCTRL_PRNG_SAVE: {
104684       sqlite3PrngSaveState();
104685       break;
104686     }
104687
104688     /*
104689     ** Restore the state of the PRNG to the last state saved using
104690     ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
104691     ** this verb acts like PRNG_RESET.
104692     */
104693     case SQLITE_TESTCTRL_PRNG_RESTORE: {
104694       sqlite3PrngRestoreState();
104695       break;
104696     }
104697
104698     /*
104699     ** Reset the PRNG back to its uninitialized state.  The next call
104700     ** to sqlite3_randomness() will reseed the PRNG using a single call
104701     ** to the xRandomness method of the default VFS.
104702     */
104703     case SQLITE_TESTCTRL_PRNG_RESET: {
104704       sqlite3PrngResetState();
104705       break;
104706     }
104707
104708     /*
104709     **  sqlite3_test_control(BITVEC_TEST, size, program)
104710     **
104711     ** Run a test against a Bitvec object of size.  The program argument
104712     ** is an array of integers that defines the test.  Return -1 on a
104713     ** memory allocation error, 0 on success, or non-zero for an error.
104714     ** See the sqlite3BitvecBuiltinTest() for additional information.
104715     */
104716     case SQLITE_TESTCTRL_BITVEC_TEST: {
104717       int sz = va_arg(ap, int);
104718       int *aProg = va_arg(ap, int*);
104719       rc = sqlite3BitvecBuiltinTest(sz, aProg);
104720       break;
104721     }
104722
104723     /*
104724     **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
104725     **
104726     ** Register hooks to call to indicate which malloc() failures 
104727     ** are benign.
104728     */
104729     case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
104730       typedef void (*void_function)(void);
104731       void_function xBenignBegin;
104732       void_function xBenignEnd;
104733       xBenignBegin = va_arg(ap, void_function);
104734       xBenignEnd = va_arg(ap, void_function);
104735       sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
104736       break;
104737     }
104738
104739     /*
104740     **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
104741     **
104742     ** Set the PENDING byte to the value in the argument, if X>0.
104743     ** Make no changes if X==0.  Return the value of the pending byte
104744     ** as it existing before this routine was called.
104745     **
104746     ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
104747     ** an incompatible database file format.  Changing the PENDING byte
104748     ** while any database connection is open results in undefined and
104749     ** dileterious behavior.
104750     */
104751     case SQLITE_TESTCTRL_PENDING_BYTE: {
104752       rc = PENDING_BYTE;
104753 #ifndef SQLITE_OMIT_WSD
104754       {
104755         unsigned int newVal = va_arg(ap, unsigned int);
104756         if( newVal ) sqlite3PendingByte = newVal;
104757       }
104758 #endif
104759       break;
104760     }
104761
104762     /*
104763     **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
104764     **
104765     ** This action provides a run-time test to see whether or not
104766     ** assert() was enabled at compile-time.  If X is true and assert()
104767     ** is enabled, then the return value is true.  If X is true and
104768     ** assert() is disabled, then the return value is zero.  If X is
104769     ** false and assert() is enabled, then the assertion fires and the
104770     ** process aborts.  If X is false and assert() is disabled, then the
104771     ** return value is zero.
104772     */
104773     case SQLITE_TESTCTRL_ASSERT: {
104774       volatile int x = 0;
104775       assert( (x = va_arg(ap,int))!=0 );
104776       rc = x;
104777       break;
104778     }
104779
104780
104781     /*
104782     **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
104783     **
104784     ** This action provides a run-time test to see how the ALWAYS and
104785     ** NEVER macros were defined at compile-time.
104786     **
104787     ** The return value is ALWAYS(X).  
104788     **
104789     ** The recommended test is X==2.  If the return value is 2, that means
104790     ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
104791     ** default setting.  If the return value is 1, then ALWAYS() is either
104792     ** hard-coded to true or else it asserts if its argument is false.
104793     ** The first behavior (hard-coded to true) is the case if
104794     ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
104795     ** behavior (assert if the argument to ALWAYS() is false) is the case if
104796     ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
104797     **
104798     ** The run-time test procedure might look something like this:
104799     **
104800     **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
104801     **      // ALWAYS() and NEVER() are no-op pass-through macros
104802     **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
104803     **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
104804     **    }else{
104805     **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
104806     **    }
104807     */
104808     case SQLITE_TESTCTRL_ALWAYS: {
104809       int x = va_arg(ap,int);
104810       rc = ALWAYS(x);
104811       break;
104812     }
104813
104814     /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
104815     **
104816     ** Set the nReserve size to N for the main database on the database
104817     ** connection db.
104818     */
104819     case SQLITE_TESTCTRL_RESERVE: {
104820       sqlite3 *db = va_arg(ap, sqlite3*);
104821       int x = va_arg(ap,int);
104822       sqlite3_mutex_enter(db->mutex);
104823       sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
104824       sqlite3_mutex_leave(db->mutex);
104825       break;
104826     }
104827
104828     /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
104829     **
104830     ** Enable or disable various optimizations for testing purposes.  The 
104831     ** argument N is a bitmask of optimizations to be disabled.  For normal
104832     ** operation N should be 0.  The idea is that a test program (like the
104833     ** SQL Logic Test or SLT test module) can run the same SQL multiple times
104834     ** with various optimizations disabled to verify that the same answer
104835     ** is obtained in every case.
104836     */
104837     case SQLITE_TESTCTRL_OPTIMIZATIONS: {
104838       sqlite3 *db = va_arg(ap, sqlite3*);
104839       int x = va_arg(ap,int);
104840       db->flags = (x & SQLITE_OptMask) | (db->flags & ~SQLITE_OptMask);
104841       break;
104842     }
104843
104844 #ifdef SQLITE_N_KEYWORD
104845     /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
104846     **
104847     ** If zWord is a keyword recognized by the parser, then return the
104848     ** number of keywords.  Or if zWord is not a keyword, return 0.
104849     ** 
104850     ** This test feature is only available in the amalgamation since
104851     ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
104852     ** is built using separate source files.
104853     */
104854     case SQLITE_TESTCTRL_ISKEYWORD: {
104855       const char *zWord = va_arg(ap, const char*);
104856       int n = sqlite3Strlen30(zWord);
104857       rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
104858       break;
104859     }
104860 #endif 
104861
104862     /* sqlite3_test_control(SQLITE_TESTCTRL_PGHDRSZ)
104863     **
104864     ** Return the size of a pcache header in bytes.
104865     */
104866     case SQLITE_TESTCTRL_PGHDRSZ: {
104867       rc = sizeof(PgHdr);
104868       break;
104869     }
104870
104871   }
104872   va_end(ap);
104873 #endif /* SQLITE_OMIT_BUILTIN_TEST */
104874   return rc;
104875 }
104876
104877 /************** End of main.c ************************************************/
104878 /************** Begin file notify.c ******************************************/
104879 /*
104880 ** 2009 March 3
104881 **
104882 ** The author disclaims copyright to this source code.  In place of
104883 ** a legal notice, here is a blessing:
104884 **
104885 **    May you do good and not evil.
104886 **    May you find forgiveness for yourself and forgive others.
104887 **    May you share freely, never taking more than you give.
104888 **
104889 *************************************************************************
104890 **
104891 ** This file contains the implementation of the sqlite3_unlock_notify()
104892 ** API method and its associated functionality.
104893 */
104894
104895 /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
104896 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
104897
104898 /*
104899 ** Public interfaces:
104900 **
104901 **   sqlite3ConnectionBlocked()
104902 **   sqlite3ConnectionUnlocked()
104903 **   sqlite3ConnectionClosed()
104904 **   sqlite3_unlock_notify()
104905 */
104906
104907 #define assertMutexHeld() \
104908   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
104909
104910 /*
104911 ** Head of a linked list of all sqlite3 objects created by this process
104912 ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
104913 ** is not NULL. This variable may only accessed while the STATIC_MASTER
104914 ** mutex is held.
104915 */
104916 static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
104917
104918 #ifndef NDEBUG
104919 /*
104920 ** This function is a complex assert() that verifies the following 
104921 ** properties of the blocked connections list:
104922 **
104923 **   1) Each entry in the list has a non-NULL value for either 
104924 **      pUnlockConnection or pBlockingConnection, or both.
104925 **
104926 **   2) All entries in the list that share a common value for 
104927 **      xUnlockNotify are grouped together.
104928 **
104929 **   3) If the argument db is not NULL, then none of the entries in the
104930 **      blocked connections list have pUnlockConnection or pBlockingConnection
104931 **      set to db. This is used when closing connection db.
104932 */
104933 static void checkListProperties(sqlite3 *db){
104934   sqlite3 *p;
104935   for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
104936     int seen = 0;
104937     sqlite3 *p2;
104938
104939     /* Verify property (1) */
104940     assert( p->pUnlockConnection || p->pBlockingConnection );
104941
104942     /* Verify property (2) */
104943     for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
104944       if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
104945       assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
104946       assert( db==0 || p->pUnlockConnection!=db );
104947       assert( db==0 || p->pBlockingConnection!=db );
104948     }
104949   }
104950 }
104951 #else
104952 # define checkListProperties(x)
104953 #endif
104954
104955 /*
104956 ** Remove connection db from the blocked connections list. If connection
104957 ** db is not currently a part of the list, this function is a no-op.
104958 */
104959 static void removeFromBlockedList(sqlite3 *db){
104960   sqlite3 **pp;
104961   assertMutexHeld();
104962   for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
104963     if( *pp==db ){
104964       *pp = (*pp)->pNextBlocked;
104965       break;
104966     }
104967   }
104968 }
104969
104970 /*
104971 ** Add connection db to the blocked connections list. It is assumed
104972 ** that it is not already a part of the list.
104973 */
104974 static void addToBlockedList(sqlite3 *db){
104975   sqlite3 **pp;
104976   assertMutexHeld();
104977   for(
104978     pp=&sqlite3BlockedList; 
104979     *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify; 
104980     pp=&(*pp)->pNextBlocked
104981   );
104982   db->pNextBlocked = *pp;
104983   *pp = db;
104984 }
104985
104986 /*
104987 ** Obtain the STATIC_MASTER mutex.
104988 */
104989 static void enterMutex(void){
104990   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
104991   checkListProperties(0);
104992 }
104993
104994 /*
104995 ** Release the STATIC_MASTER mutex.
104996 */
104997 static void leaveMutex(void){
104998   assertMutexHeld();
104999   checkListProperties(0);
105000   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
105001 }
105002
105003 /*
105004 ** Register an unlock-notify callback.
105005 **
105006 ** This is called after connection "db" has attempted some operation
105007 ** but has received an SQLITE_LOCKED error because another connection
105008 ** (call it pOther) in the same process was busy using the same shared
105009 ** cache.  pOther is found by looking at db->pBlockingConnection.
105010 **
105011 ** If there is no blocking connection, the callback is invoked immediately,
105012 ** before this routine returns.
105013 **
105014 ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
105015 ** a deadlock.
105016 **
105017 ** Otherwise, make arrangements to invoke xNotify when pOther drops
105018 ** its locks.
105019 **
105020 ** Each call to this routine overrides any prior callbacks registered
105021 ** on the same "db".  If xNotify==0 then any prior callbacks are immediately
105022 ** cancelled.
105023 */
105024 SQLITE_API int sqlite3_unlock_notify(
105025   sqlite3 *db,
105026   void (*xNotify)(void **, int),
105027   void *pArg
105028 ){
105029   int rc = SQLITE_OK;
105030
105031   sqlite3_mutex_enter(db->mutex);
105032   enterMutex();
105033
105034   if( xNotify==0 ){
105035     removeFromBlockedList(db);
105036     db->pBlockingConnection = 0;
105037     db->pUnlockConnection = 0;
105038     db->xUnlockNotify = 0;
105039     db->pUnlockArg = 0;
105040   }else if( 0==db->pBlockingConnection ){
105041     /* The blocking transaction has been concluded. Or there never was a 
105042     ** blocking transaction. In either case, invoke the notify callback
105043     ** immediately. 
105044     */
105045     xNotify(&pArg, 1);
105046   }else{
105047     sqlite3 *p;
105048
105049     for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
105050     if( p ){
105051       rc = SQLITE_LOCKED;              /* Deadlock detected. */
105052     }else{
105053       db->pUnlockConnection = db->pBlockingConnection;
105054       db->xUnlockNotify = xNotify;
105055       db->pUnlockArg = pArg;
105056       removeFromBlockedList(db);
105057       addToBlockedList(db);
105058     }
105059   }
105060
105061   leaveMutex();
105062   assert( !db->mallocFailed );
105063   sqlite3Error(db, rc, (rc?"database is deadlocked":0));
105064   sqlite3_mutex_leave(db->mutex);
105065   return rc;
105066 }
105067
105068 /*
105069 ** This function is called while stepping or preparing a statement 
105070 ** associated with connection db. The operation will return SQLITE_LOCKED
105071 ** to the user because it requires a lock that will not be available
105072 ** until connection pBlocker concludes its current transaction.
105073 */
105074 SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
105075   enterMutex();
105076   if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
105077     addToBlockedList(db);
105078   }
105079   db->pBlockingConnection = pBlocker;
105080   leaveMutex();
105081 }
105082
105083 /*
105084 ** This function is called when
105085 ** the transaction opened by database db has just finished. Locks held 
105086 ** by database connection db have been released.
105087 **
105088 ** This function loops through each entry in the blocked connections
105089 ** list and does the following:
105090 **
105091 **   1) If the sqlite3.pBlockingConnection member of a list entry is
105092 **      set to db, then set pBlockingConnection=0.
105093 **
105094 **   2) If the sqlite3.pUnlockConnection member of a list entry is
105095 **      set to db, then invoke the configured unlock-notify callback and
105096 **      set pUnlockConnection=0.
105097 **
105098 **   3) If the two steps above mean that pBlockingConnection==0 and
105099 **      pUnlockConnection==0, remove the entry from the blocked connections
105100 **      list.
105101 */
105102 SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
105103   void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
105104   int nArg = 0;                            /* Number of entries in aArg[] */
105105   sqlite3 **pp;                            /* Iterator variable */
105106   void **aArg;               /* Arguments to the unlock callback */
105107   void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
105108   void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
105109
105110   aArg = aStatic;
105111   enterMutex();         /* Enter STATIC_MASTER mutex */
105112
105113   /* This loop runs once for each entry in the blocked-connections list. */
105114   for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
105115     sqlite3 *p = *pp;
105116
105117     /* Step 1. */
105118     if( p->pBlockingConnection==db ){
105119       p->pBlockingConnection = 0;
105120     }
105121
105122     /* Step 2. */
105123     if( p->pUnlockConnection==db ){
105124       assert( p->xUnlockNotify );
105125       if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
105126         xUnlockNotify(aArg, nArg);
105127         nArg = 0;
105128       }
105129
105130       sqlite3BeginBenignMalloc();
105131       assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
105132       assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
105133       if( (!aDyn && nArg==(int)ArraySize(aStatic))
105134        || (aDyn && nArg==(int)(sqlite3DbMallocSize(db, aDyn)/sizeof(void*)))
105135       ){
105136         /* The aArg[] array needs to grow. */
105137         void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
105138         if( pNew ){
105139           memcpy(pNew, aArg, nArg*sizeof(void *));
105140           sqlite3_free(aDyn);
105141           aDyn = aArg = pNew;
105142         }else{
105143           /* This occurs when the array of context pointers that need to
105144           ** be passed to the unlock-notify callback is larger than the
105145           ** aStatic[] array allocated on the stack and the attempt to 
105146           ** allocate a larger array from the heap has failed.
105147           **
105148           ** This is a difficult situation to handle. Returning an error
105149           ** code to the caller is insufficient, as even if an error code
105150           ** is returned the transaction on connection db will still be
105151           ** closed and the unlock-notify callbacks on blocked connections
105152           ** will go unissued. This might cause the application to wait
105153           ** indefinitely for an unlock-notify callback that will never 
105154           ** arrive.
105155           **
105156           ** Instead, invoke the unlock-notify callback with the context
105157           ** array already accumulated. We can then clear the array and
105158           ** begin accumulating any further context pointers without 
105159           ** requiring any dynamic allocation. This is sub-optimal because
105160           ** it means that instead of one callback with a large array of
105161           ** context pointers the application will receive two or more
105162           ** callbacks with smaller arrays of context pointers, which will
105163           ** reduce the applications ability to prioritize multiple 
105164           ** connections. But it is the best that can be done under the
105165           ** circumstances.
105166           */
105167           xUnlockNotify(aArg, nArg);
105168           nArg = 0;
105169         }
105170       }
105171       sqlite3EndBenignMalloc();
105172
105173       aArg[nArg++] = p->pUnlockArg;
105174       xUnlockNotify = p->xUnlockNotify;
105175       p->pUnlockConnection = 0;
105176       p->xUnlockNotify = 0;
105177       p->pUnlockArg = 0;
105178     }
105179
105180     /* Step 3. */
105181     if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
105182       /* Remove connection p from the blocked connections list. */
105183       *pp = p->pNextBlocked;
105184       p->pNextBlocked = 0;
105185     }else{
105186       pp = &p->pNextBlocked;
105187     }
105188   }
105189
105190   if( nArg!=0 ){
105191     xUnlockNotify(aArg, nArg);
105192   }
105193   sqlite3_free(aDyn);
105194   leaveMutex();         /* Leave STATIC_MASTER mutex */
105195 }
105196
105197 /*
105198 ** This is called when the database connection passed as an argument is 
105199 ** being closed. The connection is removed from the blocked list.
105200 */
105201 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
105202   sqlite3ConnectionUnlocked(db);
105203   enterMutex();
105204   removeFromBlockedList(db);
105205   checkListProperties(db);
105206   leaveMutex();
105207 }
105208 #endif
105209
105210 /************** End of notify.c **********************************************/
105211 /************** Begin file fts3.c ********************************************/
105212 /*
105213 ** 2006 Oct 10
105214 **
105215 ** The author disclaims copyright to this source code.  In place of
105216 ** a legal notice, here is a blessing:
105217 **
105218 **    May you do good and not evil.
105219 **    May you find forgiveness for yourself and forgive others.
105220 **    May you share freely, never taking more than you give.
105221 **
105222 ******************************************************************************
105223 **
105224 ** This is an SQLite module implementing full-text search.
105225 */
105226
105227 /*
105228 ** The code in this file is only compiled if:
105229 **
105230 **     * The FTS3 module is being built as an extension
105231 **       (in which case SQLITE_CORE is not defined), or
105232 **
105233 **     * The FTS3 module is being built into the core of
105234 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
105235 */
105236
105237 /* The full-text index is stored in a series of b+tree (-like)
105238 ** structures called segments which map terms to doclists.  The
105239 ** structures are like b+trees in layout, but are constructed from the
105240 ** bottom up in optimal fashion and are not updatable.  Since trees
105241 ** are built from the bottom up, things will be described from the
105242 ** bottom up.
105243 **
105244 **
105245 **** Varints ****
105246 ** The basic unit of encoding is a variable-length integer called a
105247 ** varint.  We encode variable-length integers in little-endian order
105248 ** using seven bits * per byte as follows:
105249 **
105250 ** KEY:
105251 **         A = 0xxxxxxx    7 bits of data and one flag bit
105252 **         B = 1xxxxxxx    7 bits of data and one flag bit
105253 **
105254 **  7 bits - A
105255 ** 14 bits - BA
105256 ** 21 bits - BBA
105257 ** and so on.
105258 **
105259 ** This is similar in concept to how sqlite encodes "varints" but
105260 ** the encoding is not the same.  SQLite varints are big-endian
105261 ** are are limited to 9 bytes in length whereas FTS3 varints are
105262 ** little-endian and can be up to 10 bytes in length (in theory).
105263 **
105264 ** Example encodings:
105265 **
105266 **     1:    0x01
105267 **   127:    0x7f
105268 **   128:    0x81 0x00
105269 **
105270 **
105271 **** Document lists ****
105272 ** A doclist (document list) holds a docid-sorted list of hits for a
105273 ** given term.  Doclists hold docids and associated token positions.
105274 ** A docid is the unique integer identifier for a single document.
105275 ** A position is the index of a word within the document.  The first 
105276 ** word of the document has a position of 0.
105277 **
105278 ** FTS3 used to optionally store character offsets using a compile-time
105279 ** option.  But that functionality is no longer supported.
105280 **
105281 ** A doclist is stored like this:
105282 **
105283 ** array {
105284 **   varint docid;
105285 **   array {                (position list for column 0)
105286 **     varint position;     (2 more than the delta from previous position)
105287 **   }
105288 **   array {
105289 **     varint POS_COLUMN;   (marks start of position list for new column)
105290 **     varint column;       (index of new column)
105291 **     array {
105292 **       varint position;   (2 more than the delta from previous position)
105293 **     }
105294 **   }
105295 **   varint POS_END;        (marks end of positions for this document.
105296 ** }
105297 **
105298 ** Here, array { X } means zero or more occurrences of X, adjacent in
105299 ** memory.  A "position" is an index of a token in the token stream
105300 ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur 
105301 ** in the same logical place as the position element, and act as sentinals
105302 ** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.
105303 ** The positions numbers are not stored literally but rather as two more
105304 ** than the difference from the prior position, or the just the position plus
105305 ** 2 for the first position.  Example:
105306 **
105307 **   label:       A B C D E  F  G H   I  J K
105308 **   value:     123 5 9 1 1 14 35 0 234 72 0
105309 **
105310 ** The 123 value is the first docid.  For column zero in this document
105311 ** there are two matches at positions 3 and 10 (5-2 and 9-2+3).  The 1
105312 ** at D signals the start of a new column; the 1 at E indicates that the
105313 ** new column is column number 1.  There are two positions at 12 and 45
105314 ** (14-2 and 35-2+12).  The 0 at H indicate the end-of-document.  The
105315 ** 234 at I is the next docid.  It has one position 72 (72-2) and then
105316 ** terminates with the 0 at K.
105317 **
105318 ** A "position-list" is the list of positions for multiple columns for
105319 ** a single docid.  A "column-list" is the set of positions for a single
105320 ** column.  Hence, a position-list consists of one or more column-lists,
105321 ** a document record consists of a docid followed by a position-list and
105322 ** a doclist consists of one or more document records.
105323 **
105324 ** A bare doclist omits the position information, becoming an 
105325 ** array of varint-encoded docids.
105326 **
105327 **** Segment leaf nodes ****
105328 ** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
105329 ** nodes are written using LeafWriter, and read using LeafReader (to
105330 ** iterate through a single leaf node's data) and LeavesReader (to
105331 ** iterate through a segment's entire leaf layer).  Leaf nodes have
105332 ** the format:
105333 **
105334 ** varint iHeight;             (height from leaf level, always 0)
105335 ** varint nTerm;               (length of first term)
105336 ** char pTerm[nTerm];          (content of first term)
105337 ** varint nDoclist;            (length of term's associated doclist)
105338 ** char pDoclist[nDoclist];    (content of doclist)
105339 ** array {
105340 **                             (further terms are delta-encoded)
105341 **   varint nPrefix;           (length of prefix shared with previous term)
105342 **   varint nSuffix;           (length of unshared suffix)
105343 **   char pTermSuffix[nSuffix];(unshared suffix of next term)
105344 **   varint nDoclist;          (length of term's associated doclist)
105345 **   char pDoclist[nDoclist];  (content of doclist)
105346 ** }
105347 **
105348 ** Here, array { X } means zero or more occurrences of X, adjacent in
105349 ** memory.
105350 **
105351 ** Leaf nodes are broken into blocks which are stored contiguously in
105352 ** the %_segments table in sorted order.  This means that when the end
105353 ** of a node is reached, the next term is in the node with the next
105354 ** greater node id.
105355 **
105356 ** New data is spilled to a new leaf node when the current node
105357 ** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
105358 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
105359 ** node (a leaf node with a single term and doclist).  The goal of
105360 ** these settings is to pack together groups of small doclists while
105361 ** making it efficient to directly access large doclists.  The
105362 ** assumption is that large doclists represent terms which are more
105363 ** likely to be query targets.
105364 **
105365 ** TODO(shess) It may be useful for blocking decisions to be more
105366 ** dynamic.  For instance, it may make more sense to have a 2.5k leaf
105367 ** node rather than splitting into 2k and .5k nodes.  My intuition is
105368 ** that this might extend through 2x or 4x the pagesize.
105369 **
105370 **
105371 **** Segment interior nodes ****
105372 ** Segment interior nodes store blockids for subtree nodes and terms
105373 ** to describe what data is stored by the each subtree.  Interior
105374 ** nodes are written using InteriorWriter, and read using
105375 ** InteriorReader.  InteriorWriters are created as needed when
105376 ** SegmentWriter creates new leaf nodes, or when an interior node
105377 ** itself grows too big and must be split.  The format of interior
105378 ** nodes:
105379 **
105380 ** varint iHeight;           (height from leaf level, always >0)
105381 ** varint iBlockid;          (block id of node's leftmost subtree)
105382 ** optional {
105383 **   varint nTerm;           (length of first term)
105384 **   char pTerm[nTerm];      (content of first term)
105385 **   array {
105386 **                                (further terms are delta-encoded)
105387 **     varint nPrefix;            (length of shared prefix with previous term)
105388 **     varint nSuffix;            (length of unshared suffix)
105389 **     char pTermSuffix[nSuffix]; (unshared suffix of next term)
105390 **   }
105391 ** }
105392 **
105393 ** Here, optional { X } means an optional element, while array { X }
105394 ** means zero or more occurrences of X, adjacent in memory.
105395 **
105396 ** An interior node encodes n terms separating n+1 subtrees.  The
105397 ** subtree blocks are contiguous, so only the first subtree's blockid
105398 ** is encoded.  The subtree at iBlockid will contain all terms less
105399 ** than the first term encoded (or all terms if no term is encoded).
105400 ** Otherwise, for terms greater than or equal to pTerm[i] but less
105401 ** than pTerm[i+1], the subtree for that term will be rooted at
105402 ** iBlockid+i.  Interior nodes only store enough term data to
105403 ** distinguish adjacent children (if the rightmost term of the left
105404 ** child is "something", and the leftmost term of the right child is
105405 ** "wicked", only "w" is stored).
105406 **
105407 ** New data is spilled to a new interior node at the same height when
105408 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
105409 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
105410 ** interior nodes and making the tree too skinny.  The interior nodes
105411 ** at a given height are naturally tracked by interior nodes at
105412 ** height+1, and so on.
105413 **
105414 **
105415 **** Segment directory ****
105416 ** The segment directory in table %_segdir stores meta-information for
105417 ** merging and deleting segments, and also the root node of the
105418 ** segment's tree.
105419 **
105420 ** The root node is the top node of the segment's tree after encoding
105421 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
105422 ** This could be either a leaf node or an interior node.  If the top
105423 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
105424 ** and a new root interior node is generated (which should always fit
105425 ** within ROOT_MAX because it only needs space for 2 varints, the
105426 ** height and the blockid of the previous root).
105427 **
105428 ** The meta-information in the segment directory is:
105429 **   level               - segment level (see below)
105430 **   idx                 - index within level
105431 **                       - (level,idx uniquely identify a segment)
105432 **   start_block         - first leaf node
105433 **   leaves_end_block    - last leaf node
105434 **   end_block           - last block (including interior nodes)
105435 **   root                - contents of root node
105436 **
105437 ** If the root node is a leaf node, then start_block,
105438 ** leaves_end_block, and end_block are all 0.
105439 **
105440 **
105441 **** Segment merging ****
105442 ** To amortize update costs, segments are grouped into levels and
105443 ** merged in batches.  Each increase in level represents exponentially
105444 ** more documents.
105445 **
105446 ** New documents (actually, document updates) are tokenized and
105447 ** written individually (using LeafWriter) to a level 0 segment, with
105448 ** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
105449 ** level 0 segments are merged into a single level 1 segment.  Level 1
105450 ** is populated like level 0, and eventually MERGE_COUNT level 1
105451 ** segments are merged to a single level 2 segment (representing
105452 ** MERGE_COUNT^2 updates), and so on.
105453 **
105454 ** A segment merge traverses all segments at a given level in
105455 ** parallel, performing a straightforward sorted merge.  Since segment
105456 ** leaf nodes are written in to the %_segments table in order, this
105457 ** merge traverses the underlying sqlite disk structures efficiently.
105458 ** After the merge, all segment blocks from the merged level are
105459 ** deleted.
105460 **
105461 ** MERGE_COUNT controls how often we merge segments.  16 seems to be
105462 ** somewhat of a sweet spot for insertion performance.  32 and 64 show
105463 ** very similar performance numbers to 16 on insertion, though they're
105464 ** a tiny bit slower (perhaps due to more overhead in merge-time
105465 ** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
105466 ** 16, 2 about 66% slower than 16.
105467 **
105468 ** At query time, high MERGE_COUNT increases the number of segments
105469 ** which need to be scanned and merged.  For instance, with 100k docs
105470 ** inserted:
105471 **
105472 **    MERGE_COUNT   segments
105473 **       16           25
105474 **        8           12
105475 **        4           10
105476 **        2            6
105477 **
105478 ** This appears to have only a moderate impact on queries for very
105479 ** frequent terms (which are somewhat dominated by segment merge
105480 ** costs), and infrequent and non-existent terms still seem to be fast
105481 ** even with many segments.
105482 **
105483 ** TODO(shess) That said, it would be nice to have a better query-side
105484 ** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
105485 ** optimizations to things like doclist merging will swing the sweet
105486 ** spot around.
105487 **
105488 **
105489 **
105490 **** Handling of deletions and updates ****
105491 ** Since we're using a segmented structure, with no docid-oriented
105492 ** index into the term index, we clearly cannot simply update the term
105493 ** index when a document is deleted or updated.  For deletions, we
105494 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
105495 ** we simply write the new doclist.  Segment merges overwrite older
105496 ** data for a particular docid with newer data, so deletes or updates
105497 ** will eventually overtake the earlier data and knock it out.  The
105498 ** query logic likewise merges doclists so that newer data knocks out
105499 ** older data.
105500 **
105501 ** TODO(shess) Provide a VACUUM type operation to clear out all
105502 ** deletions and duplications.  This would basically be a forced merge
105503 ** into a single segment.
105504 */
105505
105506 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
105507
105508 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
105509 # define SQLITE_CORE 1
105510 #endif
105511
105512 /************** Include fts3Int.h in the middle of fts3.c ********************/
105513 /************** Begin file fts3Int.h *****************************************/
105514 /*
105515 ** 2009 Nov 12
105516 **
105517 ** The author disclaims copyright to this source code.  In place of
105518 ** a legal notice, here is a blessing:
105519 **
105520 **    May you do good and not evil.
105521 **    May you find forgiveness for yourself and forgive others.
105522 **    May you share freely, never taking more than you give.
105523 **
105524 ******************************************************************************
105525 **
105526 */
105527
105528 #ifndef _FTSINT_H
105529 #define _FTSINT_H
105530
105531 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
105532 # define NDEBUG 1
105533 #endif
105534
105535 /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
105536 /************** Begin file fts3_tokenizer.h **********************************/
105537 /*
105538 ** 2006 July 10
105539 **
105540 ** The author disclaims copyright to this source code.
105541 **
105542 *************************************************************************
105543 ** Defines the interface to tokenizers used by fulltext-search.  There
105544 ** are three basic components:
105545 **
105546 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
105547 ** interface functions.  This is essentially the class structure for
105548 ** tokenizers.
105549 **
105550 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
105551 ** including customization information defined at creation time.
105552 **
105553 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
105554 ** tokens from a particular input.
105555 */
105556 #ifndef _FTS3_TOKENIZER_H_
105557 #define _FTS3_TOKENIZER_H_
105558
105559 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
105560 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
105561 ** we will need a way to register the API consistently.
105562 */
105563
105564 /*
105565 ** Structures used by the tokenizer interface. When a new tokenizer
105566 ** implementation is registered, the caller provides a pointer to
105567 ** an sqlite3_tokenizer_module containing pointers to the callback
105568 ** functions that make up an implementation.
105569 **
105570 ** When an fts3 table is created, it passes any arguments passed to
105571 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
105572 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
105573 ** implementation. The xCreate() function in turn returns an 
105574 ** sqlite3_tokenizer structure representing the specific tokenizer to
105575 ** be used for the fts3 table (customized by the tokenizer clause arguments).
105576 **
105577 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
105578 ** method is called. It returns an sqlite3_tokenizer_cursor object
105579 ** that may be used to tokenize a specific input buffer based on
105580 ** the tokenization rules supplied by a specific sqlite3_tokenizer
105581 ** object.
105582 */
105583 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
105584 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
105585 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
105586
105587 struct sqlite3_tokenizer_module {
105588
105589   /*
105590   ** Structure version. Should always be set to 0.
105591   */
105592   int iVersion;
105593
105594   /*
105595   ** Create a new tokenizer. The values in the argv[] array are the
105596   ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
105597   ** TABLE statement that created the fts3 table. For example, if
105598   ** the following SQL is executed:
105599   **
105600   **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
105601   **
105602   ** then argc is set to 2, and the argv[] array contains pointers
105603   ** to the strings "arg1" and "arg2".
105604   **
105605   ** This method should return either SQLITE_OK (0), or an SQLite error 
105606   ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
105607   ** to point at the newly created tokenizer structure. The generic
105608   ** sqlite3_tokenizer.pModule variable should not be initialised by
105609   ** this callback. The caller will do so.
105610   */
105611   int (*xCreate)(
105612     int argc,                           /* Size of argv array */
105613     const char *const*argv,             /* Tokenizer argument strings */
105614     sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
105615   );
105616
105617   /*
105618   ** Destroy an existing tokenizer. The fts3 module calls this method
105619   ** exactly once for each successful call to xCreate().
105620   */
105621   int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
105622
105623   /*
105624   ** Create a tokenizer cursor to tokenize an input buffer. The caller
105625   ** is responsible for ensuring that the input buffer remains valid
105626   ** until the cursor is closed (using the xClose() method). 
105627   */
105628   int (*xOpen)(
105629     sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
105630     const char *pInput, int nBytes,      /* Input buffer */
105631     sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
105632   );
105633
105634   /*
105635   ** Destroy an existing tokenizer cursor. The fts3 module calls this 
105636   ** method exactly once for each successful call to xOpen().
105637   */
105638   int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
105639
105640   /*
105641   ** Retrieve the next token from the tokenizer cursor pCursor. This
105642   ** method should either return SQLITE_OK and set the values of the
105643   ** "OUT" variables identified below, or SQLITE_DONE to indicate that
105644   ** the end of the buffer has been reached, or an SQLite error code.
105645   **
105646   ** *ppToken should be set to point at a buffer containing the 
105647   ** normalized version of the token (i.e. after any case-folding and/or
105648   ** stemming has been performed). *pnBytes should be set to the length
105649   ** of this buffer in bytes. The input text that generated the token is
105650   ** identified by the byte offsets returned in *piStartOffset and
105651   ** *piEndOffset. *piStartOffset should be set to the index of the first
105652   ** byte of the token in the input buffer. *piEndOffset should be set
105653   ** to the index of the first byte just past the end of the token in
105654   ** the input buffer.
105655   **
105656   ** The buffer *ppToken is set to point at is managed by the tokenizer
105657   ** implementation. It is only required to be valid until the next call
105658   ** to xNext() or xClose(). 
105659   */
105660   /* TODO(shess) current implementation requires pInput to be
105661   ** nul-terminated.  This should either be fixed, or pInput/nBytes
105662   ** should be converted to zInput.
105663   */
105664   int (*xNext)(
105665     sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
105666     const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
105667     int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
105668     int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
105669     int *piPosition      /* OUT: Number of tokens returned before this one */
105670   );
105671 };
105672
105673 struct sqlite3_tokenizer {
105674   const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
105675   /* Tokenizer implementations will typically add additional fields */
105676 };
105677
105678 struct sqlite3_tokenizer_cursor {
105679   sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
105680   /* Tokenizer implementations will typically add additional fields */
105681 };
105682
105683 int fts3_global_term_cnt(int iTerm, int iCol);
105684 int fts3_term_cnt(int iTerm, int iCol);
105685
105686
105687 #endif /* _FTS3_TOKENIZER_H_ */
105688
105689 /************** End of fts3_tokenizer.h **************************************/
105690 /************** Continuing where we left off in fts3Int.h ********************/
105691 /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
105692 /************** Begin file fts3_hash.h ***************************************/
105693 /*
105694 ** 2001 September 22
105695 **
105696 ** The author disclaims copyright to this source code.  In place of
105697 ** a legal notice, here is a blessing:
105698 **
105699 **    May you do good and not evil.
105700 **    May you find forgiveness for yourself and forgive others.
105701 **    May you share freely, never taking more than you give.
105702 **
105703 *************************************************************************
105704 ** This is the header file for the generic hash-table implemenation
105705 ** used in SQLite.  We've modified it slightly to serve as a standalone
105706 ** hash table implementation for the full-text indexing module.
105707 **
105708 */
105709 #ifndef _FTS3_HASH_H_
105710 #define _FTS3_HASH_H_
105711
105712 /* Forward declarations of structures. */
105713 typedef struct Fts3Hash Fts3Hash;
105714 typedef struct Fts3HashElem Fts3HashElem;
105715
105716 /* A complete hash table is an instance of the following structure.
105717 ** The internals of this structure are intended to be opaque -- client
105718 ** code should not attempt to access or modify the fields of this structure
105719 ** directly.  Change this structure only by using the routines below.
105720 ** However, many of the "procedures" and "functions" for modifying and
105721 ** accessing this structure are really macros, so we can't really make
105722 ** this structure opaque.
105723 */
105724 struct Fts3Hash {
105725   char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
105726   char copyKey;           /* True if copy of key made on insert */
105727   int count;              /* Number of entries in this table */
105728   Fts3HashElem *first;    /* The first element of the array */
105729   int htsize;             /* Number of buckets in the hash table */
105730   struct _fts3ht {        /* the hash table */
105731     int count;               /* Number of entries with this hash */
105732     Fts3HashElem *chain;     /* Pointer to first entry with this hash */
105733   } *ht;
105734 };
105735
105736 /* Each element in the hash table is an instance of the following 
105737 ** structure.  All elements are stored on a single doubly-linked list.
105738 **
105739 ** Again, this structure is intended to be opaque, but it can't really
105740 ** be opaque because it is used by macros.
105741 */
105742 struct Fts3HashElem {
105743   Fts3HashElem *next, *prev; /* Next and previous elements in the table */
105744   void *data;                /* Data associated with this element */
105745   void *pKey; int nKey;      /* Key associated with this element */
105746 };
105747
105748 /*
105749 ** There are 2 different modes of operation for a hash table:
105750 **
105751 **   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
105752 **                           (including the null-terminator, if any).  Case
105753 **                           is respected in comparisons.
105754 **
105755 **   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long. 
105756 **                           memcmp() is used to compare keys.
105757 **
105758 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.  
105759 */
105760 #define FTS3_HASH_STRING    1
105761 #define FTS3_HASH_BINARY    2
105762
105763 /*
105764 ** Access routines.  To delete, insert a NULL pointer.
105765 */
105766 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
105767 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
105768 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
105769 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
105770 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
105771
105772 /*
105773 ** Shorthand for the functions above
105774 */
105775 #define fts3HashInit     sqlite3Fts3HashInit
105776 #define fts3HashInsert   sqlite3Fts3HashInsert
105777 #define fts3HashFind     sqlite3Fts3HashFind
105778 #define fts3HashClear    sqlite3Fts3HashClear
105779 #define fts3HashFindElem sqlite3Fts3HashFindElem
105780
105781 /*
105782 ** Macros for looping over all elements of a hash table.  The idiom is
105783 ** like this:
105784 **
105785 **   Fts3Hash h;
105786 **   Fts3HashElem *p;
105787 **   ...
105788 **   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
105789 **     SomeStructure *pData = fts3HashData(p);
105790 **     // do something with pData
105791 **   }
105792 */
105793 #define fts3HashFirst(H)  ((H)->first)
105794 #define fts3HashNext(E)   ((E)->next)
105795 #define fts3HashData(E)   ((E)->data)
105796 #define fts3HashKey(E)    ((E)->pKey)
105797 #define fts3HashKeysize(E) ((E)->nKey)
105798
105799 /*
105800 ** Number of entries in a hash table
105801 */
105802 #define fts3HashCount(H)  ((H)->count)
105803
105804 #endif /* _FTS3_HASH_H_ */
105805
105806 /************** End of fts3_hash.h *******************************************/
105807 /************** Continuing where we left off in fts3Int.h ********************/
105808
105809 /*
105810 ** This constant controls how often segments are merged. Once there are
105811 ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
105812 ** segment of level N+1.
105813 */
105814 #define FTS3_MERGE_COUNT 16
105815
105816 /*
105817 ** This is the maximum amount of data (in bytes) to store in the 
105818 ** Fts3Table.pendingTerms hash table. Normally, the hash table is
105819 ** populated as documents are inserted/updated/deleted in a transaction
105820 ** and used to create a new segment when the transaction is committed.
105821 ** However if this limit is reached midway through a transaction, a new 
105822 ** segment is created and the hash table cleared immediately.
105823 */
105824 #define FTS3_MAX_PENDING_DATA (1*1024*1024)
105825
105826 /*
105827 ** Macro to return the number of elements in an array. SQLite has a
105828 ** similar macro called ArraySize(). Use a different name to avoid
105829 ** a collision when building an amalgamation with built-in FTS3.
105830 */
105831 #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
105832
105833 /*
105834 ** Maximum length of a varint encoded integer. The varint format is different
105835 ** from that used by SQLite, so the maximum length is 10, not 9.
105836 */
105837 #define FTS3_VARINT_MAX 10
105838
105839 /*
105840 ** The testcase() macro is only used by the amalgamation.  If undefined,
105841 ** make it a no-op.
105842 */
105843 #ifndef testcase
105844 # define testcase(X)
105845 #endif
105846
105847 /*
105848 ** Terminator values for position-lists and column-lists.
105849 */
105850 #define POS_COLUMN  (1)     /* Column-list terminator */
105851 #define POS_END     (0)     /* Position-list terminator */ 
105852
105853 /*
105854 ** This section provides definitions to allow the
105855 ** FTS3 extension to be compiled outside of the 
105856 ** amalgamation.
105857 */
105858 #ifndef SQLITE_AMALGAMATION
105859 /*
105860 ** Macros indicating that conditional expressions are always true or
105861 ** false.
105862 */
105863 # define ALWAYS(x) (x)
105864 # define NEVER(X)  (x)
105865 /*
105866 ** Internal types used by SQLite.
105867 */
105868 typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
105869 typedef short int i16;            /* 2-byte (or larger) signed integer */
105870 typedef unsigned int u32;         /* 4-byte unsigned integer */
105871 typedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */
105872 /*
105873 ** Macro used to suppress compiler warnings for unused parameters.
105874 */
105875 #define UNUSED_PARAMETER(x) (void)(x)
105876 #endif
105877
105878 typedef struct Fts3Table Fts3Table;
105879 typedef struct Fts3Cursor Fts3Cursor;
105880 typedef struct Fts3Expr Fts3Expr;
105881 typedef struct Fts3Phrase Fts3Phrase;
105882 typedef struct Fts3SegReader Fts3SegReader;
105883 typedef struct Fts3SegFilter Fts3SegFilter;
105884
105885 /*
105886 ** A connection to a fulltext index is an instance of the following
105887 ** structure. The xCreate and xConnect methods create an instance
105888 ** of this structure and xDestroy and xDisconnect free that instance.
105889 ** All other methods receive a pointer to the structure as one of their
105890 ** arguments.
105891 */
105892 struct Fts3Table {
105893   sqlite3_vtab base;              /* Base class used by SQLite core */
105894   sqlite3 *db;                    /* The database connection */
105895   const char *zDb;                /* logical database name */
105896   const char *zName;              /* virtual table name */
105897   int nColumn;                    /* number of named columns in virtual table */
105898   char **azColumn;                /* column names.  malloced */
105899   sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
105900
105901   /* Precompiled statements used by the implementation. Each of these 
105902   ** statements is run and reset within a single virtual table API call. 
105903   */
105904   sqlite3_stmt *aStmt[25];
105905
105906   /* Pointer to string containing the SQL:
105907   **
105908   ** "SELECT block FROM %_segments WHERE blockid BETWEEN ? AND ? 
105909   **    ORDER BY blockid"
105910   */
105911   char *zSelectLeaves;
105912   int nLeavesStmt;                /* Valid statements in aLeavesStmt */
105913   int nLeavesTotal;               /* Total number of prepared leaves stmts */
105914   int nLeavesAlloc;               /* Allocated size of aLeavesStmt */
105915   sqlite3_stmt **aLeavesStmt;     /* Array of prepared zSelectLeaves stmts */
105916
105917   int nNodeSize;                  /* Soft limit for node size */
105918   u8 bHasContent;                 /* True if %_content table exists */
105919   u8 bHasDocsize;                 /* True if %_docsize table exists */
105920
105921   /* The following hash table is used to buffer pending index updates during
105922   ** transactions. Variable nPendingData estimates the memory size of the 
105923   ** pending data, including hash table overhead, but not malloc overhead. 
105924   ** When nPendingData exceeds nMaxPendingData, the buffer is flushed 
105925   ** automatically. Variable iPrevDocid is the docid of the most recently
105926   ** inserted record.
105927   */
105928   int nMaxPendingData;
105929   int nPendingData;
105930   sqlite_int64 iPrevDocid;
105931   Fts3Hash pendingTerms;
105932 };
105933
105934 /*
105935 ** When the core wants to read from the virtual table, it creates a
105936 ** virtual table cursor (an instance of the following structure) using
105937 ** the xOpen method. Cursors are destroyed using the xClose method.
105938 */
105939 struct Fts3Cursor {
105940   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
105941   i16 eSearch;                    /* Search strategy (see below) */
105942   u8 isEof;                       /* True if at End Of Results */
105943   u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
105944   sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */
105945   Fts3Expr *pExpr;                /* Parsed MATCH query string */
105946   sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */
105947   char *pNextId;                  /* Pointer into the body of aDoclist */
105948   char *aDoclist;                 /* List of docids for full-text queries */
105949   int nDoclist;                   /* Size of buffer at aDoclist */
105950   int isMatchinfoNeeded;          /* True when aMatchinfo[] needs filling in */
105951   u32 *aMatchinfo;                /* Information about most recent match */
105952 };
105953
105954 /*
105955 ** The Fts3Cursor.eSearch member is always set to one of the following.
105956 ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
105957 ** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
105958 ** of the column to be searched.  For example, in
105959 **
105960 **     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
105961 **     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
105962 ** 
105963 ** Because the LHS of the MATCH operator is 2nd column "b",
105964 ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
105965 ** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1" 
105966 ** indicating that all columns should be searched,
105967 ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
105968 */
105969 #define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
105970 #define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
105971 #define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
105972
105973 /*
105974 ** A "phrase" is a sequence of one or more tokens that must match in
105975 ** sequence.  A single token is the base case and the most common case.
105976 ** For a sequence of tokens contained in "...", nToken will be the number
105977 ** of tokens in the string.
105978 */
105979 struct Fts3Phrase {
105980   int nToken;                /* Number of tokens in the phrase */
105981   int iColumn;               /* Index of column this phrase must match */
105982   int isNot;                 /* Phrase prefixed by unary not (-) operator */
105983   struct PhraseToken {
105984     char *z;                 /* Text of the token */
105985     int n;                   /* Number of bytes in buffer pointed to by z */
105986     int isPrefix;            /* True if token ends in with a "*" character */
105987   } aToken[1];               /* One entry for each token in the phrase */
105988 };
105989
105990 /*
105991 ** A tree of these objects forms the RHS of a MATCH operator.
105992 **
105993 ** If Fts3Expr.eType is either FTSQUERY_NEAR or FTSQUERY_PHRASE and isLoaded
105994 ** is true, then aDoclist points to a malloced buffer, size nDoclist bytes, 
105995 ** containing the results of the NEAR or phrase query in FTS3 doclist
105996 ** format. As usual, the initial "Length" field found in doclists stored
105997 ** on disk is omitted from this buffer.
105998 **
105999 ** Variable pCurrent always points to the start of a docid field within
106000 ** aDoclist. Since the doclist is usually scanned in docid order, this can
106001 ** be used to accelerate seeking to the required docid within the doclist.
106002 */
106003 struct Fts3Expr {
106004   int eType;                 /* One of the FTSQUERY_XXX values defined below */
106005   int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
106006   Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
106007   Fts3Expr *pLeft;           /* Left operand */
106008   Fts3Expr *pRight;          /* Right operand */
106009   Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
106010
106011   int isLoaded;              /* True if aDoclist/nDoclist are initialized. */
106012   char *aDoclist;            /* Buffer containing doclist */
106013   int nDoclist;              /* Size of aDoclist in bytes */
106014
106015   sqlite3_int64 iCurrent;
106016   char *pCurrent;
106017 };
106018
106019 /*
106020 ** Candidate values for Fts3Query.eType. Note that the order of the first
106021 ** four values is in order of precedence when parsing expressions. For 
106022 ** example, the following:
106023 **
106024 **   "a OR b AND c NOT d NEAR e"
106025 **
106026 ** is equivalent to:
106027 **
106028 **   "a OR (b AND (c NOT (d NEAR e)))"
106029 */
106030 #define FTSQUERY_NEAR   1
106031 #define FTSQUERY_NOT    2
106032 #define FTSQUERY_AND    3
106033 #define FTSQUERY_OR     4
106034 #define FTSQUERY_PHRASE 5
106035
106036
106037 /* fts3_init.c */
106038 SQLITE_PRIVATE int sqlite3Fts3DeleteVtab(int, sqlite3_vtab *);
106039 SQLITE_PRIVATE int sqlite3Fts3InitVtab(int, sqlite3*, void*, int, const char*const*, 
106040                         sqlite3_vtab **, char **);
106041
106042 /* fts3_write.c */
106043 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
106044 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
106045 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
106046 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
106047 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(Fts3Table *,int, sqlite3_int64,
106048   sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
106049 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(Fts3Table*,const char*,int,int,Fts3SegReader**);
106050 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3Table *, Fts3SegReader *);
106051 SQLITE_PRIVATE int sqlite3Fts3SegReaderIterate(
106052   Fts3Table *, Fts3SegReader **, int, Fts3SegFilter *,
106053   int (*)(Fts3Table *, void *, char *, int, char *, int),  void *
106054 );
106055 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char const**, int*);
106056 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, sqlite3_stmt **);
106057 SQLITE_PRIVATE int sqlite3Fts3MatchinfoDocsizeLocal(Fts3Cursor*, u32*);
106058 SQLITE_PRIVATE int sqlite3Fts3MatchinfoDocsizeGlobal(Fts3Cursor*, u32*);
106059
106060 /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
106061 #define FTS3_SEGMENT_REQUIRE_POS   0x00000001
106062 #define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
106063 #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
106064 #define FTS3_SEGMENT_PREFIX        0x00000008
106065
106066 /* Type passed as 4th argument to SegmentReaderIterate() */
106067 struct Fts3SegFilter {
106068   const char *zTerm;
106069   int nTerm;
106070   int iCol;
106071   int flags;
106072 };
106073
106074 /* fts3.c */
106075 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
106076 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
106077 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
106078 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
106079 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
106080
106081 SQLITE_PRIVATE char *sqlite3Fts3FindPositions(Fts3Expr *, sqlite3_int64, int);
106082 SQLITE_PRIVATE int sqlite3Fts3ExprLoadDoclist(Fts3Table *, Fts3Expr *);
106083 SQLITE_PRIVATE int sqlite3Fts3ExprNearTrim(Fts3Expr *, Fts3Expr *, int);
106084
106085 /* fts3_tokenizer.c */
106086 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
106087 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
106088 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, 
106089   const char *, sqlite3_tokenizer **, const char **, char **
106090 );
106091
106092 /* fts3_snippet.c */
106093 SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
106094 SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
106095   const char *, const char *, int, int
106096 );
106097 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *);
106098
106099 /* fts3_expr.c */
106100 SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, 
106101   char **, int, int, const char *, int, Fts3Expr **
106102 );
106103 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
106104 #ifdef SQLITE_TEST
106105 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
106106 #endif
106107
106108 #endif /* _FTSINT_H */
106109
106110 /************** End of fts3Int.h *********************************************/
106111 /************** Continuing where we left off in fts3.c ***********************/
106112
106113
106114 #ifndef SQLITE_CORE 
106115   SQLITE_EXTENSION_INIT1
106116 #endif
106117
106118 /* 
106119 ** Write a 64-bit variable-length integer to memory starting at p[0].
106120 ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
106121 ** The number of bytes written is returned.
106122 */
106123 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
106124   unsigned char *q = (unsigned char *) p;
106125   sqlite_uint64 vu = v;
106126   do{
106127     *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
106128     vu >>= 7;
106129   }while( vu!=0 );
106130   q[-1] &= 0x7f;  /* turn off high bit in final byte */
106131   assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
106132   return (int) (q - (unsigned char *)p);
106133 }
106134
106135 /* 
106136 ** Read a 64-bit variable-length integer from memory starting at p[0].
106137 ** Return the number of bytes read, or 0 on error.
106138 ** The value is stored in *v.
106139 */
106140 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
106141   const unsigned char *q = (const unsigned char *) p;
106142   sqlite_uint64 x = 0, y = 1;
106143   while( (*q&0x80)==0x80 && q-(unsigned char *)p<FTS3_VARINT_MAX ){
106144     x += y * (*q++ & 0x7f);
106145     y <<= 7;
106146   }
106147   x += y * (*q++);
106148   *v = (sqlite_int64) x;
106149   return (int) (q - (unsigned char *)p);
106150 }
106151
106152 /*
106153 ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
106154 ** 32-bit integer before it is returned.
106155 */
106156 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
106157  sqlite_int64 i;
106158  int ret = sqlite3Fts3GetVarint(p, &i);
106159  *pi = (int) i;
106160  return ret;
106161 }
106162
106163 /*
106164 ** Return the number of bytes required to encode v as a varint
106165 */
106166 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
106167   int i = 0;
106168   do{
106169     i++;
106170     v >>= 7;
106171   }while( v!=0 );
106172   return i;
106173 }
106174
106175 /*
106176 ** Convert an SQL-style quoted string into a normal string by removing
106177 ** the quote characters.  The conversion is done in-place.  If the
106178 ** input does not begin with a quote character, then this routine
106179 ** is a no-op.
106180 **
106181 ** Examples:
106182 **
106183 **     "abc"   becomes   abc
106184 **     'xyz'   becomes   xyz
106185 **     [pqr]   becomes   pqr
106186 **     `mno`   becomes   mno
106187 **
106188 */
106189 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
106190   char quote;                     /* Quote character (if any ) */
106191
106192   quote = z[0];
106193   if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
106194     int iIn = 1;                  /* Index of next byte to read from input */
106195     int iOut = 0;                 /* Index of next byte to write to output */
106196
106197     /* If the first byte was a '[', then the close-quote character is a ']' */
106198     if( quote=='[' ) quote = ']';  
106199
106200     while( ALWAYS(z[iIn]) ){
106201       if( z[iIn]==quote ){
106202         if( z[iIn+1]!=quote ) break;
106203         z[iOut++] = quote;
106204         iIn += 2;
106205       }else{
106206         z[iOut++] = z[iIn++];
106207       }
106208     }
106209     z[iOut] = '\0';
106210   }
106211 }
106212
106213 /*
106214 ** Read a single varint from the doclist at *pp and advance *pp to point
106215 ** to the first byte past the end of the varint.  Add the value of the varint
106216 ** to *pVal.
106217 */
106218 static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
106219   sqlite3_int64 iVal;
106220   *pp += sqlite3Fts3GetVarint(*pp, &iVal);
106221   *pVal += iVal;
106222 }
106223
106224 /*
106225 ** As long as *pp has not reached its end (pEnd), then do the same
106226 ** as fts3GetDeltaVarint(): read a single varint and add it to *pVal.
106227 ** But if we have reached the end of the varint, just set *pp=0 and
106228 ** leave *pVal unchanged.
106229 */
106230 static void fts3GetDeltaVarint2(char **pp, char *pEnd, sqlite3_int64 *pVal){
106231   if( *pp>=pEnd ){
106232     *pp = 0;
106233   }else{
106234     fts3GetDeltaVarint(pp, pVal);
106235   }
106236 }
106237
106238 /*
106239 ** The xDisconnect() virtual table method.
106240 */
106241 static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
106242   Fts3Table *p = (Fts3Table *)pVtab;
106243   int i;
106244
106245   assert( p->nPendingData==0 );
106246
106247   /* Free any prepared statements held */
106248   for(i=0; i<SizeofArray(p->aStmt); i++){
106249     sqlite3_finalize(p->aStmt[i]);
106250   }
106251   for(i=0; i<p->nLeavesStmt; i++){
106252     sqlite3_finalize(p->aLeavesStmt[i]);
106253   }
106254   sqlite3_free(p->zSelectLeaves);
106255   sqlite3_free(p->aLeavesStmt);
106256
106257   /* Invoke the tokenizer destructor to free the tokenizer. */
106258   p->pTokenizer->pModule->xDestroy(p->pTokenizer);
106259
106260   sqlite3_free(p);
106261   return SQLITE_OK;
106262 }
106263
106264 /*
106265 ** Construct one or more SQL statements from the format string given
106266 ** and then evaluate those statements.  The success code is writting
106267 ** into *pRc.
106268 **
106269 ** If *pRc is initially non-zero then this routine is a no-op.
106270 */
106271 static void fts3DbExec(
106272   int *pRc,              /* Success code */
106273   sqlite3 *db,           /* Database in which to run SQL */
106274   const char *zFormat,   /* Format string for SQL */
106275   ...                    /* Arguments to the format string */
106276 ){
106277   va_list ap;
106278   char *zSql;
106279   if( *pRc ) return;
106280   va_start(ap, zFormat);
106281   zSql = sqlite3_vmprintf(zFormat, ap);
106282   va_end(ap);
106283   if( zSql==0 ){
106284     *pRc = SQLITE_NOMEM;
106285   }else{
106286     *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
106287     sqlite3_free(zSql);
106288   }
106289 }
106290
106291 /*
106292 ** The xDestroy() virtual table method.
106293 */
106294 static int fts3DestroyMethod(sqlite3_vtab *pVtab){
106295   int rc = SQLITE_OK;              /* Return code */
106296   Fts3Table *p = (Fts3Table *)pVtab;
106297   sqlite3 *db = p->db;
106298
106299   /* Drop the shadow tables */
106300   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", p->zDb, p->zName);
106301   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", p->zDb,p->zName);
106302   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", p->zDb, p->zName);
106303   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", p->zDb, p->zName);
106304   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", p->zDb, p->zName);
106305
106306   /* If everything has worked, invoke fts3DisconnectMethod() to free the
106307   ** memory associated with the Fts3Table structure and return SQLITE_OK.
106308   ** Otherwise, return an SQLite error code.
106309   */
106310   return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
106311 }
106312
106313
106314 /*
106315 ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
106316 ** passed as the first argument. This is done as part of the xConnect()
106317 ** and xCreate() methods.
106318 */
106319 static int fts3DeclareVtab(Fts3Table *p){
106320   int i;                          /* Iterator variable */
106321   int rc;                         /* Return code */
106322   char *zSql;                     /* SQL statement passed to declare_vtab() */
106323   char *zCols;                    /* List of user defined columns */
106324
106325   /* Create a list of user columns for the virtual table */
106326   zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
106327   for(i=1; zCols && i<p->nColumn; i++){
106328     zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
106329   }
106330
106331   /* Create the whole "CREATE TABLE" statement to pass to SQLite */
106332   zSql = sqlite3_mprintf(
106333       "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN)", zCols, p->zName
106334   );
106335
106336   if( !zCols || !zSql ){
106337     rc = SQLITE_NOMEM;
106338   }else{
106339     rc = sqlite3_declare_vtab(p->db, zSql);
106340   }
106341
106342   sqlite3_free(zSql);
106343   sqlite3_free(zCols);
106344   return rc;
106345 }
106346
106347 /*
106348 ** Create the backing store tables (%_content, %_segments and %_segdir)
106349 ** required by the FTS3 table passed as the only argument. This is done
106350 ** as part of the vtab xCreate() method.
106351 **
106352 ** If the p->bHasDocsize boolean is true (indicating that this is an
106353 ** FTS4 table, not an FTS3 table) then also create the %_docsize and
106354 ** %_stat tables required by FTS4.
106355 */
106356 static int fts3CreateTables(Fts3Table *p){
106357   int rc = SQLITE_OK;             /* Return code */
106358   int i;                          /* Iterator variable */
106359   char *zContentCols;             /* Columns of %_content table */
106360   sqlite3 *db = p->db;            /* The database connection */
106361
106362   /* Create a list of user columns for the content table */
106363   if( p->bHasContent ){
106364     zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
106365     for(i=0; zContentCols && i<p->nColumn; i++){
106366       char *z = p->azColumn[i];
106367       zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
106368     }
106369     if( zContentCols==0 ) rc = SQLITE_NOMEM;
106370
106371     /* Create the content table */
106372     fts3DbExec(&rc, db, 
106373        "CREATE TABLE %Q.'%q_content'(%s)",
106374        p->zDb, p->zName, zContentCols
106375     );
106376     sqlite3_free(zContentCols);
106377   }
106378   /* Create other tables */
106379   fts3DbExec(&rc, db, 
106380       "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
106381       p->zDb, p->zName
106382   );
106383   fts3DbExec(&rc, db, 
106384       "CREATE TABLE %Q.'%q_segdir'("
106385         "level INTEGER,"
106386         "idx INTEGER,"
106387         "start_block INTEGER,"
106388         "leaves_end_block INTEGER,"
106389         "end_block INTEGER,"
106390         "root BLOB,"
106391         "PRIMARY KEY(level, idx)"
106392       ");",
106393       p->zDb, p->zName
106394   );
106395   if( p->bHasDocsize ){
106396     fts3DbExec(&rc, db, 
106397         "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
106398         p->zDb, p->zName
106399     );
106400     fts3DbExec(&rc, db, 
106401         "CREATE TABLE %Q.'%q_stat'(id INTEGER PRIMARY KEY, value BLOB);",
106402         p->zDb, p->zName
106403     );
106404   }
106405   return rc;
106406 }
106407
106408 /*
106409 ** An sqlite3_exec() callback for fts3TableExists.
106410 */
106411 static int fts3TableExistsCallback(void *pArg, int n, char **pp1, char **pp2){
106412   UNUSED_PARAMETER(n);
106413   UNUSED_PARAMETER(pp1);
106414   UNUSED_PARAMETER(pp2);
106415   *(int*)pArg = 1;
106416   return 1;
106417 }
106418
106419 /*
106420 ** Determine if a table currently exists in the database.
106421 */
106422 static void fts3TableExists(
106423   int *pRc,             /* Success code */
106424   sqlite3 *db,          /* The database connection to test */
106425   const char *zDb,      /* ATTACHed database within the connection */
106426   const char *zName,    /* Name of the FTS3 table */
106427   const char *zSuffix,  /* Shadow table extension */
106428   u8 *pResult           /* Write results here */
106429 ){
106430   int rc = SQLITE_OK;
106431   int res = 0;
106432   char *zSql;
106433   if( *pRc ) return;
106434   zSql = sqlite3_mprintf(
106435     "SELECT 1 FROM %Q.sqlite_master WHERE name='%q%s'",
106436     zDb, zName, zSuffix
106437   );    
106438   rc = sqlite3_exec(db, zSql, fts3TableExistsCallback, &res, 0);
106439   sqlite3_free(zSql);
106440   *pResult = (u8)(res & 0xff);
106441   if( rc!=SQLITE_ABORT ) *pRc = rc;
106442 }
106443
106444 /*
106445 ** This function is the implementation of both the xConnect and xCreate
106446 ** methods of the FTS3 virtual table.
106447 **
106448 ** The argv[] array contains the following:
106449 **
106450 **   argv[0]   -> module name  ("fts3" or "fts4")
106451 **   argv[1]   -> database name
106452 **   argv[2]   -> table name
106453 **   argv[...] -> "column name" and other module argument fields.
106454 */
106455 static int fts3InitVtab(
106456   int isCreate,                   /* True for xCreate, false for xConnect */
106457   sqlite3 *db,                    /* The SQLite database connection */
106458   void *pAux,                     /* Hash table containing tokenizers */
106459   int argc,                       /* Number of elements in argv array */
106460   const char * const *argv,       /* xCreate/xConnect argument array */
106461   sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
106462   char **pzErr                    /* Write any error message here */
106463 ){
106464   Fts3Hash *pHash = (Fts3Hash *)pAux;
106465   Fts3Table *p;                   /* Pointer to allocated vtab */
106466   int rc;                         /* Return code */
106467   int i;                          /* Iterator variable */
106468   int nByte;                      /* Size of allocation used for *p */
106469   int iCol;                       /* Column index */
106470   int nString = 0;                /* Bytes required to hold all column names */
106471   int nCol = 0;                   /* Number of columns in the FTS table */
106472   char *zCsr;                     /* Space for holding column names */
106473   int nDb;                        /* Bytes required to hold database name */
106474   int nName;                      /* Bytes required to hold table name */
106475
106476   const char *zTokenizer = 0;               /* Name of tokenizer to use */
106477   sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
106478
106479   nDb = (int)strlen(argv[1]) + 1;
106480   nName = (int)strlen(argv[2]) + 1;
106481   for(i=3; i<argc; i++){
106482     char const *z = argv[i];
106483     rc = sqlite3Fts3InitTokenizer(pHash, z, &pTokenizer, &zTokenizer, pzErr);
106484     if( rc!=SQLITE_OK ){
106485       return rc;
106486     }
106487     if( z!=zTokenizer ){
106488       nString += (int)(strlen(z) + 1);
106489     }
106490   }
106491   nCol = argc - 3 - (zTokenizer!=0);
106492   if( zTokenizer==0 ){
106493     rc = sqlite3Fts3InitTokenizer(pHash, 0, &pTokenizer, 0, pzErr);
106494     if( rc!=SQLITE_OK ){
106495       return rc;
106496     }
106497     assert( pTokenizer );
106498   }
106499
106500   if( nCol==0 ){
106501     nCol = 1;
106502   }
106503
106504   /* Allocate and populate the Fts3Table structure. */
106505   nByte = sizeof(Fts3Table) +              /* Fts3Table */
106506           nCol * sizeof(char *) +              /* azColumn */
106507           nName +                              /* zName */
106508           nDb +                                /* zDb */
106509           nString;                             /* Space for azColumn strings */
106510   p = (Fts3Table*)sqlite3_malloc(nByte);
106511   if( p==0 ){
106512     rc = SQLITE_NOMEM;
106513     goto fts3_init_out;
106514   }
106515   memset(p, 0, nByte);
106516
106517   p->db = db;
106518   p->nColumn = nCol;
106519   p->nPendingData = 0;
106520   p->azColumn = (char **)&p[1];
106521   p->pTokenizer = pTokenizer;
106522   p->nNodeSize = 1000;
106523   p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
106524   zCsr = (char *)&p->azColumn[nCol];
106525
106526   fts3HashInit(&p->pendingTerms, FTS3_HASH_STRING, 1);
106527
106528   /* Fill in the zName and zDb fields of the vtab structure. */
106529   p->zName = zCsr;
106530   memcpy(zCsr, argv[2], nName);
106531   zCsr += nName;
106532   p->zDb = zCsr;
106533   memcpy(zCsr, argv[1], nDb);
106534   zCsr += nDb;
106535
106536   /* Fill in the azColumn array */
106537   iCol = 0;
106538   for(i=3; i<argc; i++){
106539     if( argv[i]!=zTokenizer ){
106540       char *z; 
106541       int n;
106542       z = (char *)sqlite3Fts3NextToken(argv[i], &n);
106543       memcpy(zCsr, z, n);
106544       zCsr[n] = '\0';
106545       sqlite3Fts3Dequote(zCsr);
106546       p->azColumn[iCol++] = zCsr;
106547       zCsr += n+1;
106548       assert( zCsr <= &((char *)p)[nByte] );
106549     }
106550   }
106551   if( iCol==0 ){
106552     assert( nCol==1 );
106553     p->azColumn[0] = "content";
106554   }
106555
106556   /* If this is an xCreate call, create the underlying tables in the 
106557   ** database. TODO: For xConnect(), it could verify that said tables exist.
106558   */
106559   if( isCreate ){
106560     p->bHasContent = 1;
106561     p->bHasDocsize = argv[0][3]=='4';
106562     rc = fts3CreateTables(p);
106563   }else{
106564     rc = SQLITE_OK;
106565     fts3TableExists(&rc, db, argv[1], argv[2], "_content", &p->bHasContent);
106566     fts3TableExists(&rc, db, argv[1], argv[2], "_docsize", &p->bHasDocsize);
106567   }
106568   if( rc!=SQLITE_OK ) goto fts3_init_out;
106569
106570   rc = fts3DeclareVtab(p);
106571   if( rc!=SQLITE_OK ) goto fts3_init_out;
106572
106573   *ppVTab = &p->base;
106574
106575 fts3_init_out:
106576   assert( p || (pTokenizer && rc!=SQLITE_OK) );
106577   if( rc!=SQLITE_OK ){
106578     if( p ){
106579       fts3DisconnectMethod((sqlite3_vtab *)p);
106580     }else{
106581       pTokenizer->pModule->xDestroy(pTokenizer);
106582     }
106583   }
106584   return rc;
106585 }
106586
106587 /*
106588 ** The xConnect() and xCreate() methods for the virtual table. All the
106589 ** work is done in function fts3InitVtab().
106590 */
106591 static int fts3ConnectMethod(
106592   sqlite3 *db,                    /* Database connection */
106593   void *pAux,                     /* Pointer to tokenizer hash table */
106594   int argc,                       /* Number of elements in argv array */
106595   const char * const *argv,       /* xCreate/xConnect argument array */
106596   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
106597   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
106598 ){
106599   return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
106600 }
106601 static int fts3CreateMethod(
106602   sqlite3 *db,                    /* Database connection */
106603   void *pAux,                     /* Pointer to tokenizer hash table */
106604   int argc,                       /* Number of elements in argv array */
106605   const char * const *argv,       /* xCreate/xConnect argument array */
106606   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
106607   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
106608 ){
106609   return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
106610 }
106611
106612 /* 
106613 ** Implementation of the xBestIndex method for FTS3 tables. There
106614 ** are three possible strategies, in order of preference:
106615 **
106616 **   1. Direct lookup by rowid or docid. 
106617 **   2. Full-text search using a MATCH operator on a non-docid column.
106618 **   3. Linear scan of %_content table.
106619 */
106620 static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
106621   Fts3Table *p = (Fts3Table *)pVTab;
106622   int i;                          /* Iterator variable */
106623   int iCons = -1;                 /* Index of constraint to use */
106624
106625   /* By default use a full table scan. This is an expensive option,
106626   ** so search through the constraints to see if a more efficient 
106627   ** strategy is possible.
106628   */
106629   pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
106630   pInfo->estimatedCost = 500000;
106631   for(i=0; i<pInfo->nConstraint; i++){
106632     struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
106633     if( pCons->usable==0 ) continue;
106634
106635     /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
106636     if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ 
106637      && (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1 )
106638     ){
106639       pInfo->idxNum = FTS3_DOCID_SEARCH;
106640       pInfo->estimatedCost = 1.0;
106641       iCons = i;
106642     }
106643
106644     /* A MATCH constraint. Use a full-text search.
106645     **
106646     ** If there is more than one MATCH constraint available, use the first
106647     ** one encountered. If there is both a MATCH constraint and a direct
106648     ** rowid/docid lookup, prefer the MATCH strategy. This is done even 
106649     ** though the rowid/docid lookup is faster than a MATCH query, selecting
106650     ** it would lead to an "unable to use function MATCH in the requested 
106651     ** context" error.
106652     */
106653     if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH 
106654      && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
106655     ){
106656       pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
106657       pInfo->estimatedCost = 2.0;
106658       iCons = i;
106659       break;
106660     }
106661   }
106662
106663   if( iCons>=0 ){
106664     pInfo->aConstraintUsage[iCons].argvIndex = 1;
106665     pInfo->aConstraintUsage[iCons].omit = 1;
106666   } 
106667   return SQLITE_OK;
106668 }
106669
106670 /*
106671 ** Implementation of xOpen method.
106672 */
106673 static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
106674   sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
106675
106676   UNUSED_PARAMETER(pVTab);
106677
106678   /* Allocate a buffer large enough for an Fts3Cursor structure. If the
106679   ** allocation succeeds, zero it and return SQLITE_OK. Otherwise, 
106680   ** if the allocation fails, return SQLITE_NOMEM.
106681   */
106682   *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
106683   if( !pCsr ){
106684     return SQLITE_NOMEM;
106685   }
106686   memset(pCsr, 0, sizeof(Fts3Cursor));
106687   return SQLITE_OK;
106688 }
106689
106690 /*
106691 ** Close the cursor.  For additional information see the documentation
106692 ** on the xClose method of the virtual table interface.
106693 */
106694 static int fulltextClose(sqlite3_vtab_cursor *pCursor){
106695   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
106696   sqlite3_finalize(pCsr->pStmt);
106697   sqlite3Fts3ExprFree(pCsr->pExpr);
106698   sqlite3_free(pCsr->aDoclist);
106699   sqlite3_free(pCsr->aMatchinfo);
106700   sqlite3_free(pCsr);
106701   return SQLITE_OK;
106702 }
106703
106704 /*
106705 ** Position the pCsr->pStmt statement so that it is on the row
106706 ** of the %_content table that contains the last match.  Return
106707 ** SQLITE_OK on success.  
106708 */
106709 static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
106710   if( pCsr->isRequireSeek ){
106711     pCsr->isRequireSeek = 0;
106712     sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
106713     if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
106714       return SQLITE_OK;
106715     }else{
106716       int rc = sqlite3_reset(pCsr->pStmt);
106717       if( rc==SQLITE_OK ){
106718         /* If no row was found and no error has occured, then the %_content
106719         ** table is missing a row that is present in the full-text index.
106720         ** The data structures are corrupt.
106721         */
106722         rc = SQLITE_CORRUPT;
106723       }
106724       pCsr->isEof = 1;
106725       if( pContext ){
106726         sqlite3_result_error_code(pContext, rc);
106727       }
106728       return rc;
106729     }
106730   }else{
106731     return SQLITE_OK;
106732   }
106733 }
106734
106735 /*
106736 ** Advance the cursor to the next row in the %_content table that
106737 ** matches the search criteria.  For a MATCH search, this will be
106738 ** the next row that matches.  For a full-table scan, this will be
106739 ** simply the next row in the %_content table.  For a docid lookup,
106740 ** this routine simply sets the EOF flag.
106741 **
106742 ** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
106743 ** even if we reach end-of-file.  The fts3EofMethod() will be called
106744 ** subsequently to determine whether or not an EOF was hit.
106745 */
106746 static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
106747   int rc = SQLITE_OK;             /* Return code */
106748   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
106749
106750   if( pCsr->aDoclist==0 ){
106751     if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
106752       pCsr->isEof = 1;
106753       rc = sqlite3_reset(pCsr->pStmt);
106754     }
106755   }else if( pCsr->pNextId>=&pCsr->aDoclist[pCsr->nDoclist] ){
106756     pCsr->isEof = 1;
106757   }else{
106758     sqlite3_reset(pCsr->pStmt);
106759     fts3GetDeltaVarint(&pCsr->pNextId, &pCsr->iPrevId);
106760     pCsr->isRequireSeek = 1;
106761     pCsr->isMatchinfoNeeded = 1;
106762   }
106763   return rc;
106764 }
106765
106766
106767 /*
106768 ** The buffer pointed to by argument zNode (size nNode bytes) contains the
106769 ** root node of a b-tree segment. The segment is guaranteed to be at least
106770 ** one level high (i.e. the root node is not also a leaf). If successful,
106771 ** this function locates the leaf node of the segment that may contain the 
106772 ** term specified by arguments zTerm and nTerm and writes its block number 
106773 ** to *piLeaf.
106774 **
106775 ** It is possible that the returned leaf node does not contain the specified
106776 ** term. However, if the segment does contain said term, it is stored on
106777 ** the identified leaf node. Because this function only inspects interior
106778 ** segment nodes (and never loads leaf nodes into memory), it is not possible
106779 ** to be sure.
106780 **
106781 ** If an error occurs, an error code other than SQLITE_OK is returned.
106782 */ 
106783 static int fts3SelectLeaf(
106784   Fts3Table *p,                   /* Virtual table handle */
106785   const char *zTerm,              /* Term to select leaves for */
106786   int nTerm,                      /* Size of term zTerm in bytes */
106787   const char *zNode,              /* Buffer containing segment interior node */
106788   int nNode,                      /* Size of buffer at zNode */
106789   sqlite3_int64 *piLeaf           /* Selected leaf node */
106790 ){
106791   int rc = SQLITE_OK;             /* Return code */
106792   const char *zCsr = zNode;       /* Cursor to iterate through node */
106793   const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
106794   char *zBuffer = 0;              /* Buffer to load terms into */
106795   int nAlloc = 0;                 /* Size of allocated buffer */
106796
106797   while( 1 ){
106798     int isFirstTerm = 1;          /* True when processing first term on page */
106799     int iHeight;                  /* Height of this node in tree */
106800     sqlite3_int64 iChild;         /* Block id of child node to descend to */
106801     int nBlock;                   /* Size of child node in bytes */
106802
106803     zCsr += sqlite3Fts3GetVarint32(zCsr, &iHeight);
106804     zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
106805   
106806     while( zCsr<zEnd ){
106807       int cmp;                    /* memcmp() result */
106808       int nSuffix;                /* Size of term suffix */
106809       int nPrefix = 0;            /* Size of term prefix */
106810       int nBuffer;                /* Total term size */
106811   
106812       /* Load the next term on the node into zBuffer */
106813       if( !isFirstTerm ){
106814         zCsr += sqlite3Fts3GetVarint32(zCsr, &nPrefix);
106815       }
106816       isFirstTerm = 0;
106817       zCsr += sqlite3Fts3GetVarint32(zCsr, &nSuffix);
106818       if( nPrefix+nSuffix>nAlloc ){
106819         char *zNew;
106820         nAlloc = (nPrefix+nSuffix) * 2;
106821         zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
106822         if( !zNew ){
106823           sqlite3_free(zBuffer);
106824           return SQLITE_NOMEM;
106825         }
106826         zBuffer = zNew;
106827       }
106828       memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
106829       nBuffer = nPrefix + nSuffix;
106830       zCsr += nSuffix;
106831   
106832       /* Compare the term we are searching for with the term just loaded from
106833       ** the interior node. If the specified term is greater than or equal
106834       ** to the term from the interior node, then all terms on the sub-tree 
106835       ** headed by node iChild are smaller than zTerm. No need to search 
106836       ** iChild.
106837       **
106838       ** If the interior node term is larger than the specified term, then
106839       ** the tree headed by iChild may contain the specified term.
106840       */
106841       cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
106842       if( cmp<0 || (cmp==0 && nBuffer>nTerm) ) break;
106843       iChild++;
106844     };
106845
106846     /* If (iHeight==1), the children of this interior node are leaves. The
106847     ** specified term may be present on leaf node iChild.
106848     */
106849     if( iHeight==1 ){
106850       *piLeaf = iChild;
106851       break;
106852     }
106853
106854     /* Descend to interior node iChild. */
106855     rc = sqlite3Fts3ReadBlock(p, iChild, &zCsr, &nBlock);
106856     if( rc!=SQLITE_OK ) break;
106857     zEnd = &zCsr[nBlock];
106858   }
106859   sqlite3_free(zBuffer);
106860   return rc;
106861 }
106862
106863 /*
106864 ** This function is used to create delta-encoded serialized lists of FTS3 
106865 ** varints. Each call to this function appends a single varint to a list.
106866 */
106867 static void fts3PutDeltaVarint(
106868   char **pp,                      /* IN/OUT: Output pointer */
106869   sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
106870   sqlite3_int64 iVal              /* Write this value to the list */
106871 ){
106872   assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
106873   *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
106874   *piPrev = iVal;
106875 }
106876
106877 /*
106878 ** When this function is called, *ppPoslist is assumed to point to the 
106879 ** start of a position-list. After it returns, *ppPoslist points to the
106880 ** first byte after the position-list.
106881 **
106882 ** A position list is list of positions (delta encoded) and columns for 
106883 ** a single document record of a doclist.  So, in other words, this
106884 ** routine advances *ppPoslist so that it points to the next docid in
106885 ** the doclist, or to the first byte past the end of the doclist.
106886 **
106887 ** If pp is not NULL, then the contents of the position list are copied
106888 ** to *pp. *pp is set to point to the first byte past the last byte copied
106889 ** before this function returns.
106890 */
106891 static void fts3PoslistCopy(char **pp, char **ppPoslist){
106892   char *pEnd = *ppPoslist;
106893   char c = 0;
106894
106895   /* The end of a position list is marked by a zero encoded as an FTS3 
106896   ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
106897   ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
106898   ** of some other, multi-byte, value.
106899   **
106900   ** The following while-loop moves pEnd to point to the first byte that is not 
106901   ** immediately preceded by a byte with the 0x80 bit set. Then increments
106902   ** pEnd once more so that it points to the byte immediately following the
106903   ** last byte in the position-list.
106904   */
106905   while( *pEnd | c ){
106906     c = *pEnd++ & 0x80;
106907     testcase( c!=0 && (*pEnd)==0 );
106908   }
106909   pEnd++;  /* Advance past the POS_END terminator byte */
106910
106911   if( pp ){
106912     int n = (int)(pEnd - *ppPoslist);
106913     char *p = *pp;
106914     memcpy(p, *ppPoslist, n);
106915     p += n;
106916     *pp = p;
106917   }
106918   *ppPoslist = pEnd;
106919 }
106920
106921 /*
106922 ** When this function is called, *ppPoslist is assumed to point to the 
106923 ** start of a column-list. After it returns, *ppPoslist points to the
106924 ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
106925 **
106926 ** A column-list is list of delta-encoded positions for a single column
106927 ** within a single document within a doclist.
106928 **
106929 ** The column-list is terminated either by a POS_COLUMN varint (1) or
106930 ** a POS_END varint (0).  This routine leaves *ppPoslist pointing to
106931 ** the POS_COLUMN or POS_END that terminates the column-list.
106932 **
106933 ** If pp is not NULL, then the contents of the column-list are copied
106934 ** to *pp. *pp is set to point to the first byte past the last byte copied
106935 ** before this function returns.  The POS_COLUMN or POS_END terminator
106936 ** is not copied into *pp.
106937 */
106938 static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
106939   char *pEnd = *ppPoslist;
106940   char c = 0;
106941
106942   /* A column-list is terminated by either a 0x01 or 0x00 byte that is
106943   ** not part of a multi-byte varint.
106944   */
106945   while( 0xFE & (*pEnd | c) ){
106946     c = *pEnd++ & 0x80;
106947     testcase( c!=0 && ((*pEnd)&0xfe)==0 );
106948   }
106949   if( pp ){
106950     int n = (int)(pEnd - *ppPoslist);
106951     char *p = *pp;
106952     memcpy(p, *ppPoslist, n);
106953     p += n;
106954     *pp = p;
106955   }
106956   *ppPoslist = pEnd;
106957 }
106958
106959 /*
106960 ** Value used to signify the end of an position-list. This is safe because
106961 ** it is not possible to have a document with 2^31 terms.
106962 */
106963 #define POSITION_LIST_END 0x7fffffff
106964
106965 /*
106966 ** This function is used to help parse position-lists. When this function is
106967 ** called, *pp may point to the start of the next varint in the position-list
106968 ** being parsed, or it may point to 1 byte past the end of the position-list
106969 ** (in which case **pp will be a terminator bytes POS_END (0) or
106970 ** (1)).
106971 **
106972 ** If *pp points past the end of the current position-list, set *pi to 
106973 ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
106974 ** increment the current value of *pi by the value read, and set *pp to
106975 ** point to the next value before returning.
106976 **
106977 ** Before calling this routine *pi must be initialized to the value of
106978 ** the previous position, or zero if we are reading the first position
106979 ** in the position-list.  Because positions are delta-encoded, the value
106980 ** of the previous position is needed in order to compute the value of
106981 ** the next position.
106982 */
106983 static void fts3ReadNextPos(
106984   char **pp,                    /* IN/OUT: Pointer into position-list buffer */
106985   sqlite3_int64 *pi             /* IN/OUT: Value read from position-list */
106986 ){
106987   if( (**pp)&0xFE ){
106988     fts3GetDeltaVarint(pp, pi);
106989     *pi -= 2;
106990   }else{
106991     *pi = POSITION_LIST_END;
106992   }
106993 }
106994
106995 /*
106996 ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
106997 ** the value of iCol encoded as a varint to *pp.   This will start a new
106998 ** column list.
106999 **
107000 ** Set *pp to point to the byte just after the last byte written before 
107001 ** returning (do not modify it if iCol==0). Return the total number of bytes
107002 ** written (0 if iCol==0).
107003 */
107004 static int fts3PutColNumber(char **pp, int iCol){
107005   int n = 0;                      /* Number of bytes written */
107006   if( iCol ){
107007     char *p = *pp;                /* Output pointer */
107008     n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
107009     *p = 0x01;
107010     *pp = &p[n];
107011   }
107012   return n;
107013 }
107014
107015 /*
107016 ** Compute the union of two position lists.  The output written
107017 ** into *pp contains all positions of both *pp1 and *pp2 in sorted
107018 ** order and with any duplicates removed.  All pointers are
107019 ** updated appropriately.   The caller is responsible for insuring
107020 ** that there is enough space in *pp to hold the complete output.
107021 */
107022 static void fts3PoslistMerge(
107023   char **pp,                      /* Output buffer */
107024   char **pp1,                     /* Left input list */
107025   char **pp2                      /* Right input list */
107026 ){
107027   char *p = *pp;
107028   char *p1 = *pp1;
107029   char *p2 = *pp2;
107030
107031   while( *p1 || *p2 ){
107032     int iCol1;         /* The current column index in pp1 */
107033     int iCol2;         /* The current column index in pp2 */
107034
107035     if( *p1==POS_COLUMN ) sqlite3Fts3GetVarint32(&p1[1], &iCol1);
107036     else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
107037     else iCol1 = 0;
107038
107039     if( *p2==POS_COLUMN ) sqlite3Fts3GetVarint32(&p2[1], &iCol2);
107040     else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
107041     else iCol2 = 0;
107042
107043     if( iCol1==iCol2 ){
107044       sqlite3_int64 i1 = 0;       /* Last position from pp1 */
107045       sqlite3_int64 i2 = 0;       /* Last position from pp2 */
107046       sqlite3_int64 iPrev = 0;
107047       int n = fts3PutColNumber(&p, iCol1);
107048       p1 += n;
107049       p2 += n;
107050
107051       /* At this point, both p1 and p2 point to the start of column-lists
107052       ** for the same column (the column with index iCol1 and iCol2).
107053       ** A column-list is a list of non-negative delta-encoded varints, each 
107054       ** incremented by 2 before being stored. Each list is terminated by a
107055       ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
107056       ** and writes the results to buffer p. p is left pointing to the byte
107057       ** after the list written. No terminator (POS_END or POS_COLUMN) is
107058       ** written to the output.
107059       */
107060       fts3GetDeltaVarint(&p1, &i1);
107061       fts3GetDeltaVarint(&p2, &i2);
107062       do {
107063         fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2); 
107064         iPrev -= 2;
107065         if( i1==i2 ){
107066           fts3ReadNextPos(&p1, &i1);
107067           fts3ReadNextPos(&p2, &i2);
107068         }else if( i1<i2 ){
107069           fts3ReadNextPos(&p1, &i1);
107070         }else{
107071           fts3ReadNextPos(&p2, &i2);
107072         }
107073       }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
107074     }else if( iCol1<iCol2 ){
107075       p1 += fts3PutColNumber(&p, iCol1);
107076       fts3ColumnlistCopy(&p, &p1);
107077     }else{
107078       p2 += fts3PutColNumber(&p, iCol2);
107079       fts3ColumnlistCopy(&p, &p2);
107080     }
107081   }
107082
107083   *p++ = POS_END;
107084   *pp = p;
107085   *pp1 = p1 + 1;
107086   *pp2 = p2 + 1;
107087 }
107088
107089 /*
107090 ** nToken==1 searches for adjacent positions.
107091 */
107092 static int fts3PoslistPhraseMerge(
107093   char **pp,                      /* Output buffer */
107094   int nToken,                     /* Maximum difference in token positions */
107095   int isSaveLeft,                 /* Save the left position */
107096   char **pp1,                     /* Left input list */
107097   char **pp2                      /* Right input list */
107098 ){
107099   char *p = (pp ? *pp : 0);
107100   char *p1 = *pp1;
107101   char *p2 = *pp2;
107102
107103   int iCol1 = 0;
107104   int iCol2 = 0;
107105   assert( *p1!=0 && *p2!=0 );
107106   if( *p1==POS_COLUMN ){ 
107107     p1++;
107108     p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
107109   }
107110   if( *p2==POS_COLUMN ){ 
107111     p2++;
107112     p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
107113   }
107114
107115   while( 1 ){
107116     if( iCol1==iCol2 ){
107117       char *pSave = p;
107118       sqlite3_int64 iPrev = 0;
107119       sqlite3_int64 iPos1 = 0;
107120       sqlite3_int64 iPos2 = 0;
107121
107122       if( pp && iCol1 ){
107123         *p++ = POS_COLUMN;
107124         p += sqlite3Fts3PutVarint(p, iCol1);
107125       }
107126
107127       assert( *p1!=POS_END && *p1!=POS_COLUMN );
107128       assert( *p2!=POS_END && *p2!=POS_COLUMN );
107129       fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
107130       fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
107131
107132       while( 1 ){
107133         if( iPos2>iPos1 && iPos2<=iPos1+nToken ){
107134           sqlite3_int64 iSave;
107135           if( !pp ){
107136             fts3PoslistCopy(0, &p2);
107137             fts3PoslistCopy(0, &p1);
107138             *pp1 = p1;
107139             *pp2 = p2;
107140             return 1;
107141           }
107142           iSave = isSaveLeft ? iPos1 : iPos2;
107143           fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
107144           pSave = 0;
107145         }
107146         if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
107147           if( (*p2&0xFE)==0 ) break;
107148           fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
107149         }else{
107150           if( (*p1&0xFE)==0 ) break;
107151           fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
107152         }
107153       }
107154
107155       if( pSave ){
107156         assert( pp && p );
107157         p = pSave;
107158       }
107159
107160       fts3ColumnlistCopy(0, &p1);
107161       fts3ColumnlistCopy(0, &p2);
107162       assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
107163       if( 0==*p1 || 0==*p2 ) break;
107164
107165       p1++;
107166       p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
107167       p2++;
107168       p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
107169     }
107170
107171     /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
107172     ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
107173     ** end of the position list, or the 0x01 that precedes the next 
107174     ** column-number in the position list. 
107175     */
107176     else if( iCol1<iCol2 ){
107177       fts3ColumnlistCopy(0, &p1);
107178       if( 0==*p1 ) break;
107179       p1++;
107180       p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
107181     }else{
107182       fts3ColumnlistCopy(0, &p2);
107183       if( 0==*p2 ) break;
107184       p2++;
107185       p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
107186     }
107187   }
107188
107189   fts3PoslistCopy(0, &p2);
107190   fts3PoslistCopy(0, &p1);
107191   *pp1 = p1;
107192   *pp2 = p2;
107193   if( !pp || *pp==p ){
107194     return 0;
107195   }
107196   *p++ = 0x00;
107197   *pp = p;
107198   return 1;
107199 }
107200
107201 /*
107202 ** Merge two position-lists as required by the NEAR operator.
107203 */
107204 static int fts3PoslistNearMerge(
107205   char **pp,                      /* Output buffer */
107206   char *aTmp,                     /* Temporary buffer space */
107207   int nRight,                     /* Maximum difference in token positions */
107208   int nLeft,                      /* Maximum difference in token positions */
107209   char **pp1,                     /* IN/OUT: Left input list */
107210   char **pp2                      /* IN/OUT: Right input list */
107211 ){
107212   char *p1 = *pp1;
107213   char *p2 = *pp2;
107214
107215   if( !pp ){
107216     if( fts3PoslistPhraseMerge(0, nRight, 0, pp1, pp2) ) return 1;
107217     *pp1 = p1;
107218     *pp2 = p2;
107219     return fts3PoslistPhraseMerge(0, nLeft, 0, pp2, pp1);
107220   }else{
107221     char *pTmp1 = aTmp;
107222     char *pTmp2;
107223     char *aTmp2;
107224     int res = 1;
107225
107226     fts3PoslistPhraseMerge(&pTmp1, nRight, 0, pp1, pp2);
107227     aTmp2 = pTmp2 = pTmp1;
107228     *pp1 = p1;
107229     *pp2 = p2;
107230     fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, pp2, pp1);
107231     if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
107232       fts3PoslistMerge(pp, &aTmp, &aTmp2);
107233     }else if( pTmp1!=aTmp ){
107234       fts3PoslistCopy(pp, &aTmp);
107235     }else if( pTmp2!=aTmp2 ){
107236       fts3PoslistCopy(pp, &aTmp2);
107237     }else{
107238       res = 0;
107239     }
107240
107241     return res;
107242   }
107243 }
107244
107245 /*
107246 ** Values that may be used as the first parameter to fts3DoclistMerge().
107247 */
107248 #define MERGE_NOT        2        /* D + D -> D */
107249 #define MERGE_AND        3        /* D + D -> D */
107250 #define MERGE_OR         4        /* D + D -> D */
107251 #define MERGE_POS_OR     5        /* P + P -> P */
107252 #define MERGE_PHRASE     6        /* P + P -> D */
107253 #define MERGE_POS_PHRASE 7        /* P + P -> P */
107254 #define MERGE_NEAR       8        /* P + P -> D */
107255 #define MERGE_POS_NEAR   9        /* P + P -> P */
107256
107257 /*
107258 ** Merge the two doclists passed in buffer a1 (size n1 bytes) and a2
107259 ** (size n2 bytes). The output is written to pre-allocated buffer aBuffer,
107260 ** which is guaranteed to be large enough to hold the results. The number
107261 ** of bytes written to aBuffer is stored in *pnBuffer before returning.
107262 **
107263 ** If successful, SQLITE_OK is returned. Otherwise, if a malloc error
107264 ** occurs while allocating a temporary buffer as part of the merge operation,
107265 ** SQLITE_NOMEM is returned.
107266 */
107267 static int fts3DoclistMerge(
107268   int mergetype,                  /* One of the MERGE_XXX constants */
107269   int nParam1,                    /* Used by MERGE_NEAR and MERGE_POS_NEAR */
107270   int nParam2,                    /* Used by MERGE_NEAR and MERGE_POS_NEAR */
107271   char *aBuffer,                  /* Pre-allocated output buffer */
107272   int *pnBuffer,                  /* OUT: Bytes written to aBuffer */
107273   char *a1,                       /* Buffer containing first doclist */
107274   int n1,                         /* Size of buffer a1 */
107275   char *a2,                       /* Buffer containing second doclist */
107276   int n2                          /* Size of buffer a2 */
107277 ){
107278   sqlite3_int64 i1 = 0;
107279   sqlite3_int64 i2 = 0;
107280   sqlite3_int64 iPrev = 0;
107281
107282   char *p = aBuffer;
107283   char *p1 = a1;
107284   char *p2 = a2;
107285   char *pEnd1 = &a1[n1];
107286   char *pEnd2 = &a2[n2];
107287
107288   assert( mergetype==MERGE_OR     || mergetype==MERGE_POS_OR 
107289        || mergetype==MERGE_AND    || mergetype==MERGE_NOT
107290        || mergetype==MERGE_PHRASE || mergetype==MERGE_POS_PHRASE
107291        || mergetype==MERGE_NEAR   || mergetype==MERGE_POS_NEAR
107292   );
107293
107294   if( !aBuffer ){
107295     *pnBuffer = 0;
107296     return SQLITE_NOMEM;
107297   }
107298
107299   /* Read the first docid from each doclist */
107300   fts3GetDeltaVarint2(&p1, pEnd1, &i1);
107301   fts3GetDeltaVarint2(&p2, pEnd2, &i2);
107302
107303   switch( mergetype ){
107304     case MERGE_OR:
107305     case MERGE_POS_OR:
107306       while( p1 || p2 ){
107307         if( p2 && p1 && i1==i2 ){
107308           fts3PutDeltaVarint(&p, &iPrev, i1);
107309           if( mergetype==MERGE_POS_OR ) fts3PoslistMerge(&p, &p1, &p2);
107310           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
107311           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
107312         }else if( !p2 || (p1 && i1<i2) ){
107313           fts3PutDeltaVarint(&p, &iPrev, i1);
107314           if( mergetype==MERGE_POS_OR ) fts3PoslistCopy(&p, &p1);
107315           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
107316         }else{
107317           fts3PutDeltaVarint(&p, &iPrev, i2);
107318           if( mergetype==MERGE_POS_OR ) fts3PoslistCopy(&p, &p2);
107319           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
107320         }
107321       }
107322       break;
107323
107324     case MERGE_AND:
107325       while( p1 && p2 ){
107326         if( i1==i2 ){
107327           fts3PutDeltaVarint(&p, &iPrev, i1);
107328           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
107329           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
107330         }else if( i1<i2 ){
107331           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
107332         }else{
107333           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
107334         }
107335       }
107336       break;
107337
107338     case MERGE_NOT:
107339       while( p1 ){
107340         if( p2 && i1==i2 ){
107341           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
107342           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
107343         }else if( !p2 || i1<i2 ){
107344           fts3PutDeltaVarint(&p, &iPrev, i1);
107345           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
107346         }else{
107347           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
107348         }
107349       }
107350       break;
107351
107352     case MERGE_POS_PHRASE:
107353     case MERGE_PHRASE: {
107354       char **ppPos = (mergetype==MERGE_PHRASE ? 0 : &p);
107355       while( p1 && p2 ){
107356         if( i1==i2 ){
107357           char *pSave = p;
107358           sqlite3_int64 iPrevSave = iPrev;
107359           fts3PutDeltaVarint(&p, &iPrev, i1);
107360           if( 0==fts3PoslistPhraseMerge(ppPos, 1, 0, &p1, &p2) ){
107361             p = pSave;
107362             iPrev = iPrevSave;
107363           }
107364           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
107365           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
107366         }else if( i1<i2 ){
107367           fts3PoslistCopy(0, &p1);
107368           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
107369         }else{
107370           fts3PoslistCopy(0, &p2);
107371           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
107372         }
107373       }
107374       break;
107375     }
107376
107377     default: assert( mergetype==MERGE_POS_NEAR || mergetype==MERGE_NEAR ); {
107378       char *aTmp = 0;
107379       char **ppPos = 0;
107380
107381       if( mergetype==MERGE_POS_NEAR ){
107382         ppPos = &p;
107383         aTmp = sqlite3_malloc(2*(n1+n2+1));
107384         if( !aTmp ){
107385           return SQLITE_NOMEM;
107386         }
107387       }
107388
107389       while( p1 && p2 ){
107390         if( i1==i2 ){
107391           char *pSave = p;
107392           sqlite3_int64 iPrevSave = iPrev;
107393           fts3PutDeltaVarint(&p, &iPrev, i1);
107394
107395           if( !fts3PoslistNearMerge(ppPos, aTmp, nParam1, nParam2, &p1, &p2) ){
107396             iPrev = iPrevSave;
107397             p = pSave;
107398           }
107399
107400           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
107401           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
107402         }else if( i1<i2 ){
107403           fts3PoslistCopy(0, &p1);
107404           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
107405         }else{
107406           fts3PoslistCopy(0, &p2);
107407           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
107408         }
107409       }
107410       sqlite3_free(aTmp);
107411       break;
107412     }
107413   }
107414
107415   *pnBuffer = (int)(p-aBuffer);
107416   return SQLITE_OK;
107417 }
107418
107419 /* 
107420 ** A pointer to an instance of this structure is used as the context 
107421 ** argument to sqlite3Fts3SegReaderIterate()
107422 */
107423 typedef struct TermSelect TermSelect;
107424 struct TermSelect {
107425   int isReqPos;
107426   char *aaOutput[16];             /* Malloc'd output buffer */
107427   int anOutput[16];               /* Size of output in bytes */
107428 };
107429
107430 /*
107431 ** Merge all doclists in the TermSelect.aaOutput[] array into a single
107432 ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
107433 ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
107434 **
107435 ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
107436 ** the responsibility of the caller to free any doclists left in the
107437 ** TermSelect.aaOutput[] array.
107438 */
107439 static int fts3TermSelectMerge(TermSelect *pTS){
107440   int mergetype = (pTS->isReqPos ? MERGE_POS_OR : MERGE_OR);
107441   char *aOut = 0;
107442   int nOut = 0;
107443   int i;
107444
107445   /* Loop through the doclists in the aaOutput[] array. Merge them all
107446   ** into a single doclist.
107447   */
107448   for(i=0; i<SizeofArray(pTS->aaOutput); i++){
107449     if( pTS->aaOutput[i] ){
107450       if( !aOut ){
107451         aOut = pTS->aaOutput[i];
107452         nOut = pTS->anOutput[i];
107453         pTS->aaOutput[0] = 0;
107454       }else{
107455         int nNew = nOut + pTS->anOutput[i];
107456         char *aNew = sqlite3_malloc(nNew);
107457         if( !aNew ){
107458           sqlite3_free(aOut);
107459           return SQLITE_NOMEM;
107460         }
107461         fts3DoclistMerge(mergetype, 0, 0,
107462             aNew, &nNew, pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut
107463         );
107464         sqlite3_free(pTS->aaOutput[i]);
107465         sqlite3_free(aOut);
107466         pTS->aaOutput[i] = 0;
107467         aOut = aNew;
107468         nOut = nNew;
107469       }
107470     }
107471   }
107472
107473   pTS->aaOutput[0] = aOut;
107474   pTS->anOutput[0] = nOut;
107475   return SQLITE_OK;
107476 }
107477
107478 /*
107479 ** This function is used as the sqlite3Fts3SegReaderIterate() callback when
107480 ** querying the full-text index for a doclist associated with a term or
107481 ** term-prefix.
107482 */
107483 static int fts3TermSelectCb(
107484   Fts3Table *p,                   /* Virtual table object */
107485   void *pContext,                 /* Pointer to TermSelect structure */
107486   char *zTerm,
107487   int nTerm,
107488   char *aDoclist,
107489   int nDoclist
107490 ){
107491   TermSelect *pTS = (TermSelect *)pContext;
107492
107493   UNUSED_PARAMETER(p);
107494   UNUSED_PARAMETER(zTerm);
107495   UNUSED_PARAMETER(nTerm);
107496
107497   if( pTS->aaOutput[0]==0 ){
107498     /* If this is the first term selected, copy the doclist to the output
107499     ** buffer using memcpy(). TODO: Add a way to transfer control of the
107500     ** aDoclist buffer from the caller so as to avoid the memcpy().
107501     */
107502     pTS->aaOutput[0] = sqlite3_malloc(nDoclist);
107503     pTS->anOutput[0] = nDoclist;
107504     if( pTS->aaOutput[0] ){
107505       memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
107506     }else{
107507       return SQLITE_NOMEM;
107508     }
107509   }else{
107510     int mergetype = (pTS->isReqPos ? MERGE_POS_OR : MERGE_OR);
107511     char *aMerge = aDoclist;
107512     int nMerge = nDoclist;
107513     int iOut;
107514
107515     for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
107516       char *aNew;
107517       int nNew;
107518       if( pTS->aaOutput[iOut]==0 ){
107519         assert( iOut>0 );
107520         pTS->aaOutput[iOut] = aMerge;
107521         pTS->anOutput[iOut] = nMerge;
107522         break;
107523       }
107524
107525       nNew = nMerge + pTS->anOutput[iOut];
107526       aNew = sqlite3_malloc(nNew);
107527       if( !aNew ){
107528         if( aMerge!=aDoclist ){
107529           sqlite3_free(aMerge);
107530         }
107531         return SQLITE_NOMEM;
107532       }
107533       fts3DoclistMerge(mergetype, 0, 0,
107534           aNew, &nNew, pTS->aaOutput[iOut], pTS->anOutput[iOut], aMerge, nMerge
107535       );
107536
107537       if( iOut>0 ) sqlite3_free(aMerge);
107538       sqlite3_free(pTS->aaOutput[iOut]);
107539       pTS->aaOutput[iOut] = 0;
107540
107541       aMerge = aNew;
107542       nMerge = nNew;
107543       if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
107544         pTS->aaOutput[iOut] = aMerge;
107545         pTS->anOutput[iOut] = nMerge;
107546       }
107547     }
107548   }
107549   return SQLITE_OK;
107550 }
107551
107552 /*
107553 ** This function retreives the doclist for the specified term (or term
107554 ** prefix) from the database. 
107555 **
107556 ** The returned doclist may be in one of two formats, depending on the 
107557 ** value of parameter isReqPos. If isReqPos is zero, then the doclist is
107558 ** a sorted list of delta-compressed docids (a bare doclist). If isReqPos
107559 ** is non-zero, then the returned list is in the same format as is stored 
107560 ** in the database without the found length specifier at the start of on-disk
107561 ** doclists.
107562 */
107563 static int fts3TermSelect(
107564   Fts3Table *p,                   /* Virtual table handle */
107565   int iColumn,                    /* Column to query (or -ve for all columns) */
107566   const char *zTerm,              /* Term to query for */
107567   int nTerm,                      /* Size of zTerm in bytes */
107568   int isPrefix,                   /* True for a prefix search */
107569   int isReqPos,                   /* True to include position lists in output */
107570   int *pnOut,                     /* OUT: Size of buffer at *ppOut */
107571   char **ppOut                    /* OUT: Malloced result buffer */
107572 ){
107573   int i;
107574   TermSelect tsc;
107575   Fts3SegFilter filter;           /* Segment term filter configuration */
107576   Fts3SegReader **apSegment;      /* Array of segments to read data from */
107577   int nSegment = 0;               /* Size of apSegment array */
107578   int nAlloc = 16;                /* Allocated size of segment array */
107579   int rc;                         /* Return code */
107580   sqlite3_stmt *pStmt = 0;        /* SQL statement to scan %_segdir table */
107581   int iAge = 0;                   /* Used to assign ages to segments */
107582
107583   apSegment = (Fts3SegReader **)sqlite3_malloc(sizeof(Fts3SegReader*)*nAlloc);
107584   if( !apSegment ) return SQLITE_NOMEM;
107585   rc = sqlite3Fts3SegReaderPending(p, zTerm, nTerm, isPrefix, &apSegment[0]);
107586   if( rc!=SQLITE_OK ) goto finished;
107587   if( apSegment[0] ){
107588     nSegment = 1;
107589   }
107590
107591   /* Loop through the entire %_segdir table. For each segment, create a
107592   ** Fts3SegReader to iterate through the subset of the segment leaves
107593   ** that may contain a term that matches zTerm/nTerm. For non-prefix
107594   ** searches, this is always a single leaf. For prefix searches, this
107595   ** may be a contiguous block of leaves.
107596   **
107597   ** The code in this loop does not actually load any leaves into memory
107598   ** (unless the root node happens to be a leaf). It simply examines the
107599   ** b-tree structure to determine which leaves need to be inspected.
107600   */
107601   rc = sqlite3Fts3AllSegdirs(p, &pStmt);
107602   while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
107603     Fts3SegReader *pNew = 0;
107604     int nRoot = sqlite3_column_bytes(pStmt, 4);
107605     char const *zRoot = sqlite3_column_blob(pStmt, 4);
107606     if( sqlite3_column_int64(pStmt, 1)==0 ){
107607       /* The entire segment is stored on the root node (which must be a
107608       ** leaf). Do not bother inspecting any data in this case, just
107609       ** create a Fts3SegReader to scan the single leaf. 
107610       */
107611       rc = sqlite3Fts3SegReaderNew(p, iAge, 0, 0, 0, zRoot, nRoot, &pNew);
107612     }else{
107613       int rc2;                    /* Return value of sqlite3Fts3ReadBlock() */
107614       sqlite3_int64 i1;           /* Blockid of leaf that may contain zTerm */
107615       rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &i1);
107616       if( rc==SQLITE_OK ){
107617         sqlite3_int64 i2 = sqlite3_column_int64(pStmt, 2);
107618         rc = sqlite3Fts3SegReaderNew(p, iAge, i1, i2, 0, 0, 0, &pNew);
107619       }
107620
107621       /* The following call to ReadBlock() serves to reset the SQL statement
107622       ** used to retrieve blocks of data from the %_segments table. If it is
107623       ** not reset here, then it may remain classified as an active statement 
107624       ** by SQLite, which may lead to "DROP TABLE" or "DETACH" commands 
107625       ** failing.
107626       */ 
107627       rc2 = sqlite3Fts3ReadBlock(p, 0, 0, 0);
107628       if( rc==SQLITE_OK ){
107629         rc = rc2;
107630       }
107631     }
107632     iAge++;
107633
107634     /* If a new Fts3SegReader was allocated, add it to the apSegment array. */
107635     assert( pNew!=0 || rc!=SQLITE_OK );
107636     if( pNew ){
107637       if( nSegment==nAlloc ){
107638         Fts3SegReader **pArray;
107639         nAlloc += 16;
107640         pArray = (Fts3SegReader **)sqlite3_realloc(
107641             apSegment, nAlloc*sizeof(Fts3SegReader *)
107642         );
107643         if( !pArray ){
107644           sqlite3Fts3SegReaderFree(p, pNew);
107645           rc = SQLITE_NOMEM;
107646           goto finished;
107647         }
107648         apSegment = pArray;
107649       }
107650       apSegment[nSegment++] = pNew;
107651     }
107652   }
107653   if( rc!=SQLITE_DONE ){
107654     assert( rc!=SQLITE_OK );
107655     goto finished;
107656   }
107657
107658   memset(&tsc, 0, sizeof(TermSelect));
107659   tsc.isReqPos = isReqPos;
107660
107661   filter.flags = FTS3_SEGMENT_IGNORE_EMPTY 
107662         | (isPrefix ? FTS3_SEGMENT_PREFIX : 0)
107663         | (isReqPos ? FTS3_SEGMENT_REQUIRE_POS : 0)
107664         | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
107665   filter.iCol = iColumn;
107666   filter.zTerm = zTerm;
107667   filter.nTerm = nTerm;
107668
107669   rc = sqlite3Fts3SegReaderIterate(p, apSegment, nSegment, &filter,
107670       fts3TermSelectCb, (void *)&tsc
107671   );
107672   if( rc==SQLITE_OK ){
107673     rc = fts3TermSelectMerge(&tsc);
107674   }
107675
107676   if( rc==SQLITE_OK ){
107677     *ppOut = tsc.aaOutput[0];
107678     *pnOut = tsc.anOutput[0];
107679   }else{
107680     for(i=0; i<SizeofArray(tsc.aaOutput); i++){
107681       sqlite3_free(tsc.aaOutput[i]);
107682     }
107683   }
107684
107685 finished:
107686   sqlite3_reset(pStmt);
107687   for(i=0; i<nSegment; i++){
107688     sqlite3Fts3SegReaderFree(p, apSegment[i]);
107689   }
107690   sqlite3_free(apSegment);
107691   return rc;
107692 }
107693
107694
107695 /* 
107696 ** Return a DocList corresponding to the phrase *pPhrase.
107697 */
107698 static int fts3PhraseSelect(
107699   Fts3Table *p,                   /* Virtual table handle */
107700   Fts3Phrase *pPhrase,            /* Phrase to return a doclist for */
107701   int isReqPos,                   /* True if output should contain positions */
107702   char **paOut,                   /* OUT: Pointer to malloc'd result buffer */
107703   int *pnOut                      /* OUT: Size of buffer at *paOut */
107704 ){
107705   char *pOut = 0;
107706   int nOut = 0;
107707   int rc = SQLITE_OK;
107708   int ii;
107709   int iCol = pPhrase->iColumn;
107710   int isTermPos = (pPhrase->nToken>1 || isReqPos);
107711
107712   for(ii=0; ii<pPhrase->nToken; ii++){
107713     struct PhraseToken *pTok = &pPhrase->aToken[ii];
107714     char *z = pTok->z;            /* Next token of the phrase */
107715     int n = pTok->n;              /* Size of z in bytes */
107716     int isPrefix = pTok->isPrefix;/* True if token is a prefix */
107717     char *pList;                  /* Pointer to token doclist */
107718     int nList;                    /* Size of buffer at pList */
107719
107720     rc = fts3TermSelect(p, iCol, z, n, isPrefix, isTermPos, &nList, &pList);
107721     if( rc!=SQLITE_OK ) break;
107722
107723     if( ii==0 ){
107724       pOut = pList;
107725       nOut = nList;
107726     }else{
107727       /* Merge the new term list and the current output. If this is the
107728       ** last term in the phrase, and positions are not required in the
107729       ** output of this function, the positions can be dropped as part
107730       ** of this merge. Either way, the result of this merge will be
107731       ** smaller than nList bytes. The code in fts3DoclistMerge() is written
107732       ** so that it is safe to use pList as the output as well as an input
107733       ** in this case.
107734       */
107735       int mergetype = MERGE_POS_PHRASE;
107736       if( ii==pPhrase->nToken-1 && !isReqPos ){
107737         mergetype = MERGE_PHRASE;
107738       }
107739       fts3DoclistMerge(mergetype, 0, 0, pList, &nOut, pOut, nOut, pList, nList);
107740       sqlite3_free(pOut);
107741       pOut = pList;
107742     }
107743     assert( nOut==0 || pOut!=0 );
107744   }
107745
107746   if( rc==SQLITE_OK ){
107747     *paOut = pOut;
107748     *pnOut = nOut;
107749   }else{
107750     sqlite3_free(pOut);
107751   }
107752   return rc;
107753 }
107754
107755 static int fts3NearMerge(
107756   int mergetype,                  /* MERGE_POS_NEAR or MERGE_NEAR */
107757   int nNear,                      /* Parameter to NEAR operator */
107758   int nTokenLeft,                 /* Number of tokens in LHS phrase arg */
107759   char *aLeft,                    /* Doclist for LHS (incl. positions) */
107760   int nLeft,                      /* Size of LHS doclist in bytes */
107761   int nTokenRight,                /* As nTokenLeft */
107762   char *aRight,                   /* As aLeft */
107763   int nRight,                     /* As nRight */
107764   char **paOut,                   /* OUT: Results of merge (malloced) */
107765   int *pnOut                      /* OUT: Sized of output buffer */
107766 ){
107767   char *aOut;
107768   int rc;
107769
107770   assert( mergetype==MERGE_POS_NEAR || MERGE_NEAR );
107771
107772   aOut = sqlite3_malloc(nLeft+nRight+1);
107773   if( aOut==0 ){
107774     rc = SQLITE_NOMEM;
107775   }else{
107776     rc = fts3DoclistMerge(mergetype, nNear+nTokenRight, nNear+nTokenLeft, 
107777       aOut, pnOut, aLeft, nLeft, aRight, nRight
107778     );
107779     if( rc!=SQLITE_OK ){
107780       sqlite3_free(aOut);
107781       aOut = 0;
107782     }
107783   }
107784
107785   *paOut = aOut;
107786   return rc;
107787 }
107788
107789 SQLITE_PRIVATE int sqlite3Fts3ExprNearTrim(Fts3Expr *pLeft, Fts3Expr *pRight, int nNear){
107790   int rc;
107791   if( pLeft->aDoclist==0 || pRight->aDoclist==0 ){
107792     sqlite3_free(pLeft->aDoclist);
107793     sqlite3_free(pRight->aDoclist);
107794     pRight->aDoclist = 0;
107795     pLeft->aDoclist = 0;
107796     rc = SQLITE_OK;
107797   }else{
107798     char *aOut;
107799     int nOut;
107800
107801     rc = fts3NearMerge(MERGE_POS_NEAR, nNear, 
107802         pLeft->pPhrase->nToken, pLeft->aDoclist, pLeft->nDoclist,
107803         pRight->pPhrase->nToken, pRight->aDoclist, pRight->nDoclist,
107804         &aOut, &nOut
107805     );
107806     if( rc!=SQLITE_OK ) return rc;
107807     sqlite3_free(pRight->aDoclist);
107808     pRight->aDoclist = aOut;
107809     pRight->nDoclist = nOut;
107810
107811     rc = fts3NearMerge(MERGE_POS_NEAR, nNear, 
107812         pRight->pPhrase->nToken, pRight->aDoclist, pRight->nDoclist,
107813         pLeft->pPhrase->nToken, pLeft->aDoclist, pLeft->nDoclist,
107814         &aOut, &nOut
107815     );
107816     sqlite3_free(pLeft->aDoclist);
107817     pLeft->aDoclist = aOut;
107818     pLeft->nDoclist = nOut;
107819   }
107820   return rc;
107821 }
107822
107823 /*
107824 ** Evaluate the full-text expression pExpr against fts3 table pTab. Store
107825 ** the resulting doclist in *paOut and *pnOut.  This routine mallocs for
107826 ** the space needed to store the output.  The caller is responsible for
107827 ** freeing the space when it has finished.
107828 */
107829 static int evalFts3Expr(
107830   Fts3Table *p,                   /* Virtual table handle */
107831   Fts3Expr *pExpr,                /* Parsed fts3 expression */
107832   char **paOut,                   /* OUT: Pointer to malloc'd result buffer */
107833   int *pnOut,                     /* OUT: Size of buffer at *paOut */
107834   int isReqPos                    /* Require positions in output buffer */
107835 ){
107836   int rc = SQLITE_OK;             /* Return code */
107837
107838   /* Zero the output parameters. */
107839   *paOut = 0;
107840   *pnOut = 0;
107841
107842   if( pExpr ){
107843     assert( pExpr->eType==FTSQUERY_PHRASE 
107844          || pExpr->eType==FTSQUERY_NEAR 
107845          || isReqPos==0
107846     );
107847     if( pExpr->eType==FTSQUERY_PHRASE ){
107848       rc = fts3PhraseSelect(p, pExpr->pPhrase, 
107849           isReqPos || (pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR),
107850           paOut, pnOut
107851       );
107852     }else{
107853       char *aLeft;
107854       char *aRight;
107855       int nLeft;
107856       int nRight;
107857
107858       if( 0==(rc = evalFts3Expr(p, pExpr->pRight, &aRight, &nRight, isReqPos))
107859        && 0==(rc = evalFts3Expr(p, pExpr->pLeft, &aLeft, &nLeft, isReqPos))
107860       ){
107861         assert( pExpr->eType==FTSQUERY_NEAR || pExpr->eType==FTSQUERY_OR     
107862             || pExpr->eType==FTSQUERY_AND  || pExpr->eType==FTSQUERY_NOT
107863         );
107864         switch( pExpr->eType ){
107865           case FTSQUERY_NEAR: {
107866             Fts3Expr *pLeft;
107867             Fts3Expr *pRight;
107868             int mergetype = isReqPos ? MERGE_POS_NEAR : MERGE_NEAR;
107869            
107870             if( pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR ){
107871               mergetype = MERGE_POS_NEAR;
107872             }
107873             pLeft = pExpr->pLeft;
107874             while( pLeft->eType==FTSQUERY_NEAR ){ 
107875               pLeft=pLeft->pRight;
107876             }
107877             pRight = pExpr->pRight;
107878             assert( pRight->eType==FTSQUERY_PHRASE );
107879             assert( pLeft->eType==FTSQUERY_PHRASE );
107880
107881             rc = fts3NearMerge(mergetype, pExpr->nNear, 
107882                 pLeft->pPhrase->nToken, aLeft, nLeft,
107883                 pRight->pPhrase->nToken, aRight, nRight,
107884                 paOut, pnOut
107885             );
107886             sqlite3_free(aLeft);
107887             break;
107888           }
107889
107890           case FTSQUERY_OR: {
107891             /* Allocate a buffer for the output. The maximum size is the
107892             ** sum of the sizes of the two input buffers. The +1 term is
107893             ** so that a buffer of zero bytes is never allocated - this can
107894             ** cause fts3DoclistMerge() to incorrectly return SQLITE_NOMEM.
107895             */
107896             char *aBuffer = sqlite3_malloc(nRight+nLeft+1);
107897             rc = fts3DoclistMerge(MERGE_OR, 0, 0, aBuffer, pnOut,
107898                 aLeft, nLeft, aRight, nRight
107899             );
107900             *paOut = aBuffer;
107901             sqlite3_free(aLeft);
107902             break;
107903           }
107904
107905           default: {
107906             assert( FTSQUERY_NOT==MERGE_NOT && FTSQUERY_AND==MERGE_AND );
107907             fts3DoclistMerge(pExpr->eType, 0, 0, aLeft, pnOut,
107908                 aLeft, nLeft, aRight, nRight
107909             );
107910             *paOut = aLeft;
107911             break;
107912           }
107913         }
107914       }
107915       sqlite3_free(aRight);
107916     }
107917   }
107918
107919   return rc;
107920 }
107921
107922 /*
107923 ** This is the xFilter interface for the virtual table.  See
107924 ** the virtual table xFilter method documentation for additional
107925 ** information.
107926 **
107927 ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
107928 ** the %_content table.
107929 **
107930 ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
107931 ** in the %_content table.
107932 **
107933 ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
107934 ** column on the left-hand side of the MATCH operator is column
107935 ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
107936 ** side of the MATCH operator.
107937 */
107938 /* TODO(shess) Upgrade the cursor initialization and destruction to
107939 ** account for fts3FilterMethod() being called multiple times on the
107940 ** same cursor. The current solution is very fragile. Apply fix to
107941 ** fts3 as appropriate.
107942 */
107943 static int fts3FilterMethod(
107944   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
107945   int idxNum,                     /* Strategy index */
107946   const char *idxStr,             /* Unused */
107947   int nVal,                       /* Number of elements in apVal */
107948   sqlite3_value **apVal           /* Arguments for the indexing scheme */
107949 ){
107950   const char *azSql[] = {
107951     "SELECT * FROM %Q.'%q_content' WHERE docid = ?", /* non-full-table-scan */
107952     "SELECT * FROM %Q.'%q_content'",                 /* full-table-scan */
107953   };
107954   int rc;                         /* Return code */
107955   char *zSql;                     /* SQL statement used to access %_content */
107956   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
107957   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
107958
107959   UNUSED_PARAMETER(idxStr);
107960   UNUSED_PARAMETER(nVal);
107961
107962   assert( idxNum>=0 && idxNum<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
107963   assert( nVal==0 || nVal==1 );
107964   assert( (nVal==0)==(idxNum==FTS3_FULLSCAN_SEARCH) );
107965
107966   /* In case the cursor has been used before, clear it now. */
107967   sqlite3_finalize(pCsr->pStmt);
107968   sqlite3_free(pCsr->aDoclist);
107969   sqlite3Fts3ExprFree(pCsr->pExpr);
107970   memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
107971
107972   /* Compile a SELECT statement for this cursor. For a full-table-scan, the
107973   ** statement loops through all rows of the %_content table. For a
107974   ** full-text query or docid lookup, the statement retrieves a single
107975   ** row by docid.
107976   */
107977   zSql = sqlite3_mprintf(azSql[idxNum==FTS3_FULLSCAN_SEARCH], p->zDb, p->zName);
107978   if( !zSql ){
107979     rc = SQLITE_NOMEM;
107980   }else{
107981     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
107982     sqlite3_free(zSql);
107983   }
107984   if( rc!=SQLITE_OK ) return rc;
107985   pCsr->eSearch = (i16)idxNum;
107986
107987   if( idxNum==FTS3_DOCID_SEARCH ){
107988     rc = sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
107989   }else if( idxNum!=FTS3_FULLSCAN_SEARCH ){
107990     int iCol = idxNum-FTS3_FULLTEXT_SEARCH;
107991     const char *zQuery = (const char *)sqlite3_value_text(apVal[0]);
107992
107993     if( zQuery==0 && sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
107994       return SQLITE_NOMEM;
107995     }
107996
107997     rc = sqlite3Fts3ExprParse(p->pTokenizer, p->azColumn, p->nColumn, 
107998         iCol, zQuery, -1, &pCsr->pExpr
107999     );
108000     if( rc!=SQLITE_OK ){
108001       if( rc==SQLITE_ERROR ){
108002         p->base.zErrMsg = sqlite3_mprintf("malformed MATCH expression: [%s]",
108003                                           zQuery);
108004       }
108005       return rc;
108006     }
108007
108008     rc = evalFts3Expr(p, pCsr->pExpr, &pCsr->aDoclist, &pCsr->nDoclist, 0);
108009     pCsr->pNextId = pCsr->aDoclist;
108010     pCsr->iPrevId = 0;
108011   }
108012
108013   if( rc!=SQLITE_OK ) return rc;
108014   return fts3NextMethod(pCursor);
108015 }
108016
108017 /* 
108018 ** This is the xEof method of the virtual table. SQLite calls this 
108019 ** routine to find out if it has reached the end of a result set.
108020 */
108021 static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
108022   return ((Fts3Cursor *)pCursor)->isEof;
108023 }
108024
108025 /* 
108026 ** This is the xRowid method. The SQLite core calls this routine to
108027 ** retrieve the rowid for the current row of the result set. fts3
108028 ** exposes %_content.docid as the rowid for the virtual table. The
108029 ** rowid should be written to *pRowid.
108030 */
108031 static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
108032   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
108033   if( pCsr->aDoclist ){
108034     *pRowid = pCsr->iPrevId;
108035   }else{
108036     *pRowid = sqlite3_column_int64(pCsr->pStmt, 0);
108037   }
108038   return SQLITE_OK;
108039 }
108040
108041 /* 
108042 ** This is the xColumn method, called by SQLite to request a value from
108043 ** the row that the supplied cursor currently points to.
108044 */
108045 static int fts3ColumnMethod(
108046   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
108047   sqlite3_context *pContext,      /* Context for sqlite3_result_xxx() calls */
108048   int iCol                        /* Index of column to read value from */
108049 ){
108050   int rc;                         /* Return Code */
108051   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
108052   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
108053
108054   /* The column value supplied by SQLite must be in range. */
108055   assert( iCol>=0 && iCol<=p->nColumn+1 );
108056
108057   if( iCol==p->nColumn+1 ){
108058     /* This call is a request for the "docid" column. Since "docid" is an 
108059     ** alias for "rowid", use the xRowid() method to obtain the value.
108060     */
108061     sqlite3_int64 iRowid;
108062     rc = fts3RowidMethod(pCursor, &iRowid);
108063     sqlite3_result_int64(pContext, iRowid);
108064   }else if( iCol==p->nColumn ){
108065     /* The extra column whose name is the same as the table.
108066     ** Return a blob which is a pointer to the cursor.
108067     */
108068     sqlite3_result_blob(pContext, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
108069     rc = SQLITE_OK;
108070   }else{
108071     rc = fts3CursorSeek(0, pCsr);
108072     if( rc==SQLITE_OK ){
108073       sqlite3_result_value(pContext, sqlite3_column_value(pCsr->pStmt, iCol+1));
108074     }
108075   }
108076   return rc;
108077 }
108078
108079 /* 
108080 ** This function is the implementation of the xUpdate callback used by 
108081 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
108082 ** inserted, updated or deleted.
108083 */
108084 static int fts3UpdateMethod(
108085   sqlite3_vtab *pVtab,            /* Virtual table handle */
108086   int nArg,                       /* Size of argument array */
108087   sqlite3_value **apVal,          /* Array of arguments */
108088   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
108089 ){
108090   return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
108091 }
108092
108093 /*
108094 ** Implementation of xSync() method. Flush the contents of the pending-terms
108095 ** hash-table to the database.
108096 */
108097 static int fts3SyncMethod(sqlite3_vtab *pVtab){
108098   return sqlite3Fts3PendingTermsFlush((Fts3Table *)pVtab);
108099 }
108100
108101 /*
108102 ** Implementation of xBegin() method. This is a no-op.
108103 */
108104 static int fts3BeginMethod(sqlite3_vtab *pVtab){
108105   UNUSED_PARAMETER(pVtab);
108106   assert( ((Fts3Table *)pVtab)->nPendingData==0 );
108107   return SQLITE_OK;
108108 }
108109
108110 /*
108111 ** Implementation of xCommit() method. This is a no-op. The contents of
108112 ** the pending-terms hash-table have already been flushed into the database
108113 ** by fts3SyncMethod().
108114 */
108115 static int fts3CommitMethod(sqlite3_vtab *pVtab){
108116   UNUSED_PARAMETER(pVtab);
108117   assert( ((Fts3Table *)pVtab)->nPendingData==0 );
108118   return SQLITE_OK;
108119 }
108120
108121 /*
108122 ** Implementation of xRollback(). Discard the contents of the pending-terms
108123 ** hash-table. Any changes made to the database are reverted by SQLite.
108124 */
108125 static int fts3RollbackMethod(sqlite3_vtab *pVtab){
108126   sqlite3Fts3PendingTermsClear((Fts3Table *)pVtab);
108127   return SQLITE_OK;
108128 }
108129
108130 /*
108131 ** Load the doclist associated with expression pExpr to pExpr->aDoclist.
108132 ** The loaded doclist contains positions as well as the document ids.
108133 ** This is used by the matchinfo(), snippet() and offsets() auxillary
108134 ** functions.
108135 */
108136 SQLITE_PRIVATE int sqlite3Fts3ExprLoadDoclist(Fts3Table *pTab, Fts3Expr *pExpr){
108137   return evalFts3Expr(pTab, pExpr, &pExpr->aDoclist, &pExpr->nDoclist, 1);
108138 }
108139
108140 /*
108141 ** After ExprLoadDoclist() (see above) has been called, this function is
108142 ** used to iterate/search through the position lists that make up the doclist
108143 ** stored in pExpr->aDoclist.
108144 */
108145 SQLITE_PRIVATE char *sqlite3Fts3FindPositions(
108146   Fts3Expr *pExpr,                /* Access this expressions doclist */
108147   sqlite3_int64 iDocid,           /* Docid associated with requested pos-list */
108148   int iCol                        /* Column of requested pos-list */
108149 ){
108150   assert( pExpr->isLoaded );
108151   if( pExpr->aDoclist ){
108152     char *pEnd = &pExpr->aDoclist[pExpr->nDoclist];
108153     char *pCsr = pExpr->pCurrent;
108154
108155     assert( pCsr );
108156     while( pCsr<pEnd ){
108157       if( pExpr->iCurrent<iDocid ){
108158         fts3PoslistCopy(0, &pCsr);
108159         if( pCsr<pEnd ){
108160           fts3GetDeltaVarint(&pCsr, &pExpr->iCurrent);
108161         }
108162         pExpr->pCurrent = pCsr;
108163       }else{
108164         if( pExpr->iCurrent==iDocid ){
108165           int iThis = 0;
108166           if( iCol<0 ){
108167             /* If iCol is negative, return a pointer to the start of the
108168             ** position-list (instead of a pointer to the start of a list
108169             ** of offsets associated with a specific column).
108170             */
108171             return pCsr;
108172           }
108173           while( iThis<iCol ){
108174             fts3ColumnlistCopy(0, &pCsr);
108175             if( *pCsr==0x00 ) return 0;
108176             pCsr++;
108177             pCsr += sqlite3Fts3GetVarint32(pCsr, &iThis);
108178           }
108179           if( iCol==iThis && (*pCsr&0xFE) ) return pCsr;
108180         }
108181         return 0;
108182       }
108183     }
108184   }
108185
108186   return 0;
108187 }
108188
108189 /*
108190 ** Helper function used by the implementation of the overloaded snippet(),
108191 ** offsets() and optimize() SQL functions.
108192 **
108193 ** If the value passed as the third argument is a blob of size
108194 ** sizeof(Fts3Cursor*), then the blob contents are copied to the 
108195 ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
108196 ** message is written to context pContext and SQLITE_ERROR returned. The
108197 ** string passed via zFunc is used as part of the error message.
108198 */
108199 static int fts3FunctionArg(
108200   sqlite3_context *pContext,      /* SQL function call context */
108201   const char *zFunc,              /* Function name */
108202   sqlite3_value *pVal,            /* argv[0] passed to function */
108203   Fts3Cursor **ppCsr         /* OUT: Store cursor handle here */
108204 ){
108205   Fts3Cursor *pRet;
108206   if( sqlite3_value_type(pVal)!=SQLITE_BLOB 
108207    || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
108208   ){
108209     char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
108210     sqlite3_result_error(pContext, zErr, -1);
108211     sqlite3_free(zErr);
108212     return SQLITE_ERROR;
108213   }
108214   memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
108215   *ppCsr = pRet;
108216   return SQLITE_OK;
108217 }
108218
108219 /*
108220 ** Implementation of the snippet() function for FTS3
108221 */
108222 static void fts3SnippetFunc(
108223   sqlite3_context *pContext,      /* SQLite function call context */
108224   int nVal,                       /* Size of apVal[] array */
108225   sqlite3_value **apVal           /* Array of arguments */
108226 ){
108227   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
108228   const char *zStart = "<b>";
108229   const char *zEnd = "</b>";
108230   const char *zEllipsis = "<b>...</b>";
108231   int iCol = -1;
108232   int nToken = 15;                /* Default number of tokens in snippet */
108233
108234   /* There must be at least one argument passed to this function (otherwise
108235   ** the non-overloaded version would have been called instead of this one).
108236   */
108237   assert( nVal>=1 );
108238
108239   if( nVal>6 ){
108240     sqlite3_result_error(pContext, 
108241         "wrong number of arguments to function snippet()", -1);
108242     return;
108243   }
108244   if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
108245
108246   switch( nVal ){
108247     case 6: nToken = sqlite3_value_int(apVal[5]);
108248     case 5: iCol = sqlite3_value_int(apVal[4]);
108249     case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
108250     case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
108251     case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
108252   }
108253   if( !zEllipsis || !zEnd || !zStart ){
108254     sqlite3_result_error_nomem(pContext);
108255   }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
108256     sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
108257   }
108258 }
108259
108260 /*
108261 ** Implementation of the offsets() function for FTS3
108262 */
108263 static void fts3OffsetsFunc(
108264   sqlite3_context *pContext,      /* SQLite function call context */
108265   int nVal,                       /* Size of argument array */
108266   sqlite3_value **apVal           /* Array of arguments */
108267 ){
108268   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
108269
108270   UNUSED_PARAMETER(nVal);
108271
108272   assert( nVal==1 );
108273   if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
108274   assert( pCsr );
108275   if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
108276     sqlite3Fts3Offsets(pContext, pCsr);
108277   }
108278 }
108279
108280 /* 
108281 ** Implementation of the special optimize() function for FTS3. This 
108282 ** function merges all segments in the database to a single segment.
108283 ** Example usage is:
108284 **
108285 **   SELECT optimize(t) FROM t LIMIT 1;
108286 **
108287 ** where 't' is the name of an FTS3 table.
108288 */
108289 static void fts3OptimizeFunc(
108290   sqlite3_context *pContext,      /* SQLite function call context */
108291   int nVal,                       /* Size of argument array */
108292   sqlite3_value **apVal           /* Array of arguments */
108293 ){
108294   int rc;                         /* Return code */
108295   Fts3Table *p;                   /* Virtual table handle */
108296   Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
108297
108298   UNUSED_PARAMETER(nVal);
108299
108300   assert( nVal==1 );
108301   if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
108302   p = (Fts3Table *)pCursor->base.pVtab;
108303   assert( p );
108304
108305   rc = sqlite3Fts3Optimize(p);
108306
108307   switch( rc ){
108308     case SQLITE_OK:
108309       sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
108310       break;
108311     case SQLITE_DONE:
108312       sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
108313       break;
108314     default:
108315       sqlite3_result_error_code(pContext, rc);
108316       break;
108317   }
108318 }
108319
108320 /*
108321 ** Implementation of the matchinfo() function for FTS3
108322 */
108323 static void fts3MatchinfoFunc(
108324   sqlite3_context *pContext,      /* SQLite function call context */
108325   int nVal,                       /* Size of argument array */
108326   sqlite3_value **apVal           /* Array of arguments */
108327 ){
108328   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
108329
108330   if( nVal!=1 ){
108331     sqlite3_result_error(pContext,
108332         "wrong number of arguments to function matchinfo()", -1);
108333     return;
108334   }
108335
108336   if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
108337     sqlite3Fts3Matchinfo(pContext, pCsr);
108338   }
108339 }
108340
108341 /*
108342 ** This routine implements the xFindFunction method for the FTS3
108343 ** virtual table.
108344 */
108345 static int fts3FindFunctionMethod(
108346   sqlite3_vtab *pVtab,            /* Virtual table handle */
108347   int nArg,                       /* Number of SQL function arguments */
108348   const char *zName,              /* Name of SQL function */
108349   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
108350   void **ppArg                    /* Unused */
108351 ){
108352   struct Overloaded {
108353     const char *zName;
108354     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
108355   } aOverload[] = {
108356     { "snippet", fts3SnippetFunc },
108357     { "offsets", fts3OffsetsFunc },
108358     { "optimize", fts3OptimizeFunc },
108359     { "matchinfo", fts3MatchinfoFunc },
108360   };
108361   int i;                          /* Iterator variable */
108362
108363   UNUSED_PARAMETER(pVtab);
108364   UNUSED_PARAMETER(nArg);
108365   UNUSED_PARAMETER(ppArg);
108366
108367   for(i=0; i<SizeofArray(aOverload); i++){
108368     if( strcmp(zName, aOverload[i].zName)==0 ){
108369       *pxFunc = aOverload[i].xFunc;
108370       return 1;
108371     }
108372   }
108373
108374   /* No function of the specified name was found. Return 0. */
108375   return 0;
108376 }
108377
108378 /*
108379 ** Implementation of FTS3 xRename method. Rename an fts3 table.
108380 */
108381 static int fts3RenameMethod(
108382   sqlite3_vtab *pVtab,            /* Virtual table handle */
108383   const char *zName               /* New name of table */
108384 ){
108385   Fts3Table *p = (Fts3Table *)pVtab;
108386   sqlite3 *db;                    /* Database connection */
108387   int rc;                         /* Return Code */
108388  
108389   db = p->db;
108390   rc = SQLITE_OK;
108391   fts3DbExec(&rc, db,
108392     "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';",
108393     p->zDb, p->zName, zName
108394   );
108395   if( rc==SQLITE_ERROR ) rc = SQLITE_OK;
108396   if( p->bHasDocsize ){
108397     fts3DbExec(&rc, db,
108398       "ALTER TABLE %Q.'%q_docsize'  RENAME TO '%q_docsize';",
108399       p->zDb, p->zName, zName
108400     );
108401     fts3DbExec(&rc, db,
108402       "ALTER TABLE %Q.'%q_stat'  RENAME TO '%q_stat';",
108403       p->zDb, p->zName, zName
108404     );
108405   }
108406   fts3DbExec(&rc, db,
108407     "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
108408     p->zDb, p->zName, zName
108409   );
108410   fts3DbExec(&rc, db,
108411     "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';",
108412     p->zDb, p->zName, zName
108413   );
108414   return rc;
108415 }
108416
108417 static const sqlite3_module fts3Module = {
108418   /* iVersion      */ 0,
108419   /* xCreate       */ fts3CreateMethod,
108420   /* xConnect      */ fts3ConnectMethod,
108421   /* xBestIndex    */ fts3BestIndexMethod,
108422   /* xDisconnect   */ fts3DisconnectMethod,
108423   /* xDestroy      */ fts3DestroyMethod,
108424   /* xOpen         */ fts3OpenMethod,
108425   /* xClose        */ fulltextClose,
108426   /* xFilter       */ fts3FilterMethod,
108427   /* xNext         */ fts3NextMethod,
108428   /* xEof          */ fts3EofMethod,
108429   /* xColumn       */ fts3ColumnMethod,
108430   /* xRowid        */ fts3RowidMethod,
108431   /* xUpdate       */ fts3UpdateMethod,
108432   /* xBegin        */ fts3BeginMethod,
108433   /* xSync         */ fts3SyncMethod,
108434   /* xCommit       */ fts3CommitMethod,
108435   /* xRollback     */ fts3RollbackMethod,
108436   /* xFindFunction */ fts3FindFunctionMethod,
108437   /* xRename */       fts3RenameMethod,
108438 };
108439
108440 /*
108441 ** This function is registered as the module destructor (called when an
108442 ** FTS3 enabled database connection is closed). It frees the memory
108443 ** allocated for the tokenizer hash table.
108444 */
108445 static void hashDestroy(void *p){
108446   Fts3Hash *pHash = (Fts3Hash *)p;
108447   sqlite3Fts3HashClear(pHash);
108448   sqlite3_free(pHash);
108449 }
108450
108451 /*
108452 ** The fts3 built-in tokenizers - "simple" and "porter" - are implemented
108453 ** in files fts3_tokenizer1.c and fts3_porter.c respectively. The following
108454 ** two forward declarations are for functions declared in these files
108455 ** used to retrieve the respective implementations.
108456 **
108457 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
108458 ** to by the argument to point a the "simple" tokenizer implementation.
108459 ** Function ...PorterTokenizerModule() sets *pModule to point to the
108460 ** porter tokenizer/stemmer implementation.
108461 */
108462 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
108463 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
108464 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
108465
108466 /*
108467 ** Initialise the fts3 extension. If this extension is built as part
108468 ** of the sqlite library, then this function is called directly by
108469 ** SQLite. If fts3 is built as a dynamically loadable extension, this
108470 ** function is called by the sqlite3_extension_init() entry point.
108471 */
108472 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
108473   int rc = SQLITE_OK;
108474   Fts3Hash *pHash = 0;
108475   const sqlite3_tokenizer_module *pSimple = 0;
108476   const sqlite3_tokenizer_module *pPorter = 0;
108477
108478 #ifdef SQLITE_ENABLE_ICU
108479   const sqlite3_tokenizer_module *pIcu = 0;
108480   sqlite3Fts3IcuTokenizerModule(&pIcu);
108481 #endif
108482
108483   sqlite3Fts3SimpleTokenizerModule(&pSimple);
108484   sqlite3Fts3PorterTokenizerModule(&pPorter);
108485
108486   /* Allocate and initialise the hash-table used to store tokenizers. */
108487   pHash = sqlite3_malloc(sizeof(Fts3Hash));
108488   if( !pHash ){
108489     rc = SQLITE_NOMEM;
108490   }else{
108491     sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
108492   }
108493
108494   /* Load the built-in tokenizers into the hash table */
108495   if( rc==SQLITE_OK ){
108496     if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
108497      || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter) 
108498 #ifdef SQLITE_ENABLE_ICU
108499      || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
108500 #endif
108501     ){
108502       rc = SQLITE_NOMEM;
108503     }
108504   }
108505
108506 #ifdef SQLITE_TEST
108507   if( rc==SQLITE_OK ){
108508     rc = sqlite3Fts3ExprInitTestInterface(db);
108509   }
108510 #endif
108511
108512   /* Create the virtual table wrapper around the hash-table and overload 
108513   ** the two scalar functions. If this is successful, register the
108514   ** module with sqlite.
108515   */
108516   if( SQLITE_OK==rc 
108517    && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
108518    && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
108519    && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
108520    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", -1))
108521    && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
108522   ){
108523     rc = sqlite3_create_module_v2(
108524         db, "fts3", &fts3Module, (void *)pHash, hashDestroy
108525     );
108526     if( rc==SQLITE_OK ){
108527       rc = sqlite3_create_module_v2(
108528           db, "fts4", &fts3Module, (void *)pHash, 0
108529       );
108530     }
108531     return rc;
108532   }
108533
108534   /* An error has occurred. Delete the hash table and return the error code. */
108535   assert( rc!=SQLITE_OK );
108536   if( pHash ){
108537     sqlite3Fts3HashClear(pHash);
108538     sqlite3_free(pHash);
108539   }
108540   return rc;
108541 }
108542
108543 #if !SQLITE_CORE
108544 SQLITE_API int sqlite3_extension_init(
108545   sqlite3 *db, 
108546   char **pzErrMsg,
108547   const sqlite3_api_routines *pApi
108548 ){
108549   SQLITE_EXTENSION_INIT2(pApi)
108550   return sqlite3Fts3Init(db);
108551 }
108552 #endif
108553
108554 #endif
108555
108556 /************** End of fts3.c ************************************************/
108557 /************** Begin file fts3_expr.c ***************************************/
108558 /*
108559 ** 2008 Nov 28
108560 **
108561 ** The author disclaims copyright to this source code.  In place of
108562 ** a legal notice, here is a blessing:
108563 **
108564 **    May you do good and not evil.
108565 **    May you find forgiveness for yourself and forgive others.
108566 **    May you share freely, never taking more than you give.
108567 **
108568 ******************************************************************************
108569 **
108570 ** This module contains code that implements a parser for fts3 query strings
108571 ** (the right-hand argument to the MATCH operator). Because the supported 
108572 ** syntax is relatively simple, the whole tokenizer/parser system is
108573 ** hand-coded. 
108574 */
108575 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
108576
108577 /*
108578 ** By default, this module parses the legacy syntax that has been 
108579 ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
108580 ** is defined, then it uses the new syntax. The differences between
108581 ** the new and the old syntaxes are:
108582 **
108583 **  a) The new syntax supports parenthesis. The old does not.
108584 **
108585 **  b) The new syntax supports the AND and NOT operators. The old does not.
108586 **
108587 **  c) The old syntax supports the "-" token qualifier. This is not 
108588 **     supported by the new syntax (it is replaced by the NOT operator).
108589 **
108590 **  d) When using the old syntax, the OR operator has a greater precedence
108591 **     than an implicit AND. When using the new, both implicity and explicit
108592 **     AND operators have a higher precedence than OR.
108593 **
108594 ** If compiled with SQLITE_TEST defined, then this module exports the
108595 ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
108596 ** to zero causes the module to use the old syntax. If it is set to 
108597 ** non-zero the new syntax is activated. This is so both syntaxes can
108598 ** be tested using a single build of testfixture.
108599 **
108600 ** The following describes the syntax supported by the fts3 MATCH
108601 ** operator in a similar format to that used by the lemon parser
108602 ** generator. This module does not use actually lemon, it uses a
108603 ** custom parser.
108604 **
108605 **   query ::= andexpr (OR andexpr)*.
108606 **
108607 **   andexpr ::= notexpr (AND? notexpr)*.
108608 **
108609 **   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
108610 **   notexpr ::= LP query RP.
108611 **
108612 **   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
108613 **
108614 **   distance_opt ::= .
108615 **   distance_opt ::= / INTEGER.
108616 **
108617 **   phrase ::= TOKEN.
108618 **   phrase ::= COLUMN:TOKEN.
108619 **   phrase ::= "TOKEN TOKEN TOKEN...".
108620 */
108621
108622 #ifdef SQLITE_TEST
108623 SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
108624 #else
108625 # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS 
108626 #  define sqlite3_fts3_enable_parentheses 1
108627 # else
108628 #  define sqlite3_fts3_enable_parentheses 0
108629 # endif
108630 #endif
108631
108632 /*
108633 ** Default span for NEAR operators.
108634 */
108635 #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
108636
108637
108638 typedef struct ParseContext ParseContext;
108639 struct ParseContext {
108640   sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
108641   const char **azCol;                 /* Array of column names for fts3 table */
108642   int nCol;                           /* Number of entries in azCol[] */
108643   int iDefaultCol;                    /* Default column to query */
108644   sqlite3_context *pCtx;              /* Write error message here */
108645   int nNest;                          /* Number of nested brackets */
108646 };
108647
108648 /*
108649 ** This function is equivalent to the standard isspace() function. 
108650 **
108651 ** The standard isspace() can be awkward to use safely, because although it
108652 ** is defined to accept an argument of type int, its behaviour when passed
108653 ** an integer that falls outside of the range of the unsigned char type
108654 ** is undefined (and sometimes, "undefined" means segfault). This wrapper
108655 ** is defined to accept an argument of type char, and always returns 0 for
108656 ** any values that fall outside of the range of the unsigned char type (i.e.
108657 ** negative values).
108658 */
108659 static int fts3isspace(char c){
108660   return (c&0x80)==0 ? isspace(c) : 0;
108661 }
108662
108663 /*
108664 ** Extract the next token from buffer z (length n) using the tokenizer
108665 ** and other information (column names etc.) in pParse. Create an Fts3Expr
108666 ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
108667 ** single token and set *ppExpr to point to it. If the end of the buffer is
108668 ** reached before a token is found, set *ppExpr to zero. It is the
108669 ** responsibility of the caller to eventually deallocate the allocated 
108670 ** Fts3Expr structure (if any) by passing it to sqlite3_free().
108671 **
108672 ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
108673 ** fails.
108674 */
108675 static int getNextToken(
108676   ParseContext *pParse,                   /* fts3 query parse context */
108677   int iCol,                               /* Value for Fts3Phrase.iColumn */
108678   const char *z, int n,                   /* Input string */
108679   Fts3Expr **ppExpr,                      /* OUT: expression */
108680   int *pnConsumed                         /* OUT: Number of bytes consumed */
108681 ){
108682   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
108683   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
108684   int rc;
108685   sqlite3_tokenizer_cursor *pCursor;
108686   Fts3Expr *pRet = 0;
108687   int nConsumed = 0;
108688
108689   rc = pModule->xOpen(pTokenizer, z, n, &pCursor);
108690   if( rc==SQLITE_OK ){
108691     const char *zToken;
108692     int nToken, iStart, iEnd, iPosition;
108693     int nByte;                               /* total space to allocate */
108694
108695     pCursor->pTokenizer = pTokenizer;
108696     rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
108697
108698     if( rc==SQLITE_OK ){
108699       nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
108700       pRet = (Fts3Expr *)sqlite3_malloc(nByte);
108701       if( !pRet ){
108702         rc = SQLITE_NOMEM;
108703       }else{
108704         memset(pRet, 0, nByte);
108705         pRet->eType = FTSQUERY_PHRASE;
108706         pRet->pPhrase = (Fts3Phrase *)&pRet[1];
108707         pRet->pPhrase->nToken = 1;
108708         pRet->pPhrase->iColumn = iCol;
108709         pRet->pPhrase->aToken[0].n = nToken;
108710         pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
108711         memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
108712
108713         if( iEnd<n && z[iEnd]=='*' ){
108714           pRet->pPhrase->aToken[0].isPrefix = 1;
108715           iEnd++;
108716         }
108717         if( !sqlite3_fts3_enable_parentheses && iStart>0 && z[iStart-1]=='-' ){
108718           pRet->pPhrase->isNot = 1;
108719         }
108720       }
108721       nConsumed = iEnd;
108722     }
108723
108724     pModule->xClose(pCursor);
108725   }
108726   
108727   *pnConsumed = nConsumed;
108728   *ppExpr = pRet;
108729   return rc;
108730 }
108731
108732
108733 /*
108734 ** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
108735 ** then free the old allocation.
108736 */
108737 static void *fts3ReallocOrFree(void *pOrig, int nNew){
108738   void *pRet = sqlite3_realloc(pOrig, nNew);
108739   if( !pRet ){
108740     sqlite3_free(pOrig);
108741   }
108742   return pRet;
108743 }
108744
108745 /*
108746 ** Buffer zInput, length nInput, contains the contents of a quoted string
108747 ** that appeared as part of an fts3 query expression. Neither quote character
108748 ** is included in the buffer. This function attempts to tokenize the entire
108749 ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE 
108750 ** containing the results.
108751 **
108752 ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
108753 ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
108754 ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
108755 ** to 0.
108756 */
108757 static int getNextString(
108758   ParseContext *pParse,                   /* fts3 query parse context */
108759   const char *zInput, int nInput,         /* Input string */
108760   Fts3Expr **ppExpr                       /* OUT: expression */
108761 ){
108762   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
108763   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
108764   int rc;
108765   Fts3Expr *p = 0;
108766   sqlite3_tokenizer_cursor *pCursor = 0;
108767   char *zTemp = 0;
108768   int nTemp = 0;
108769
108770   rc = pModule->xOpen(pTokenizer, zInput, nInput, &pCursor);
108771   if( rc==SQLITE_OK ){
108772     int ii;
108773     pCursor->pTokenizer = pTokenizer;
108774     for(ii=0; rc==SQLITE_OK; ii++){
108775       const char *zToken;
108776       int nToken, iBegin, iEnd, iPos;
108777       rc = pModule->xNext(pCursor, &zToken, &nToken, &iBegin, &iEnd, &iPos);
108778       if( rc==SQLITE_OK ){
108779         int nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
108780         p = fts3ReallocOrFree(p, nByte+ii*sizeof(struct PhraseToken));
108781         zTemp = fts3ReallocOrFree(zTemp, nTemp + nToken);
108782         if( !p || !zTemp ){
108783           goto no_mem;
108784         }
108785         if( ii==0 ){
108786           memset(p, 0, nByte);
108787           p->pPhrase = (Fts3Phrase *)&p[1];
108788         }
108789         p->pPhrase = (Fts3Phrase *)&p[1];
108790         p->pPhrase->nToken = ii+1;
108791         p->pPhrase->aToken[ii].n = nToken;
108792         memcpy(&zTemp[nTemp], zToken, nToken);
108793         nTemp += nToken;
108794         if( iEnd<nInput && zInput[iEnd]=='*' ){
108795           p->pPhrase->aToken[ii].isPrefix = 1;
108796         }else{
108797           p->pPhrase->aToken[ii].isPrefix = 0;
108798         }
108799       }
108800     }
108801
108802     pModule->xClose(pCursor);
108803     pCursor = 0;
108804   }
108805
108806   if( rc==SQLITE_DONE ){
108807     int jj;
108808     char *zNew = NULL;
108809     int nNew = 0;
108810     int nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
108811     nByte += (p?(p->pPhrase->nToken-1):0) * sizeof(struct PhraseToken);
108812     p = fts3ReallocOrFree(p, nByte + nTemp);
108813     if( !p ){
108814       goto no_mem;
108815     }
108816     if( zTemp ){
108817       zNew = &(((char *)p)[nByte]);
108818       memcpy(zNew, zTemp, nTemp);
108819     }else{
108820       memset(p, 0, nByte+nTemp);
108821     }
108822     p->pPhrase = (Fts3Phrase *)&p[1];
108823     for(jj=0; jj<p->pPhrase->nToken; jj++){
108824       p->pPhrase->aToken[jj].z = &zNew[nNew];
108825       nNew += p->pPhrase->aToken[jj].n;
108826     }
108827     sqlite3_free(zTemp);
108828     p->eType = FTSQUERY_PHRASE;
108829     p->pPhrase->iColumn = pParse->iDefaultCol;
108830     rc = SQLITE_OK;
108831   }
108832
108833   *ppExpr = p;
108834   return rc;
108835 no_mem:
108836
108837   if( pCursor ){
108838     pModule->xClose(pCursor);
108839   }
108840   sqlite3_free(zTemp);
108841   sqlite3_free(p);
108842   *ppExpr = 0;
108843   return SQLITE_NOMEM;
108844 }
108845
108846 /*
108847 ** Function getNextNode(), which is called by fts3ExprParse(), may itself
108848 ** call fts3ExprParse(). So this forward declaration is required.
108849 */
108850 static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
108851
108852 /*
108853 ** The output variable *ppExpr is populated with an allocated Fts3Expr 
108854 ** structure, or set to 0 if the end of the input buffer is reached.
108855 **
108856 ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
108857 ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
108858 ** If SQLITE_ERROR is returned, pContext is populated with an error message.
108859 */
108860 static int getNextNode(
108861   ParseContext *pParse,                   /* fts3 query parse context */
108862   const char *z, int n,                   /* Input string */
108863   Fts3Expr **ppExpr,                      /* OUT: expression */
108864   int *pnConsumed                         /* OUT: Number of bytes consumed */
108865 ){
108866   static const struct Fts3Keyword {
108867     char *z;                              /* Keyword text */
108868     unsigned char n;                      /* Length of the keyword */
108869     unsigned char parenOnly;              /* Only valid in paren mode */
108870     unsigned char eType;                  /* Keyword code */
108871   } aKeyword[] = {
108872     { "OR" ,  2, 0, FTSQUERY_OR   },
108873     { "AND",  3, 1, FTSQUERY_AND  },
108874     { "NOT",  3, 1, FTSQUERY_NOT  },
108875     { "NEAR", 4, 0, FTSQUERY_NEAR }
108876   };
108877   int ii;
108878   int iCol;
108879   int iColLen;
108880   int rc;
108881   Fts3Expr *pRet = 0;
108882
108883   const char *zInput = z;
108884   int nInput = n;
108885
108886   /* Skip over any whitespace before checking for a keyword, an open or
108887   ** close bracket, or a quoted string. 
108888   */
108889   while( nInput>0 && fts3isspace(*zInput) ){
108890     nInput--;
108891     zInput++;
108892   }
108893   if( nInput==0 ){
108894     return SQLITE_DONE;
108895   }
108896
108897   /* See if we are dealing with a keyword. */
108898   for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
108899     const struct Fts3Keyword *pKey = &aKeyword[ii];
108900
108901     if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
108902       continue;
108903     }
108904
108905     if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
108906       int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
108907       int nKey = pKey->n;
108908       char cNext;
108909
108910       /* If this is a "NEAR" keyword, check for an explicit nearness. */
108911       if( pKey->eType==FTSQUERY_NEAR ){
108912         assert( nKey==4 );
108913         if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
108914           nNear = 0;
108915           for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
108916             nNear = nNear * 10 + (zInput[nKey] - '0');
108917           }
108918         }
108919       }
108920
108921       /* At this point this is probably a keyword. But for that to be true,
108922       ** the next byte must contain either whitespace, an open or close
108923       ** parenthesis, a quote character, or EOF. 
108924       */
108925       cNext = zInput[nKey];
108926       if( fts3isspace(cNext) 
108927        || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
108928       ){
108929         pRet = (Fts3Expr *)sqlite3_malloc(sizeof(Fts3Expr));
108930         if( !pRet ){
108931           return SQLITE_NOMEM;
108932         }
108933         memset(pRet, 0, sizeof(Fts3Expr));
108934         pRet->eType = pKey->eType;
108935         pRet->nNear = nNear;
108936         *ppExpr = pRet;
108937         *pnConsumed = (int)((zInput - z) + nKey);
108938         return SQLITE_OK;
108939       }
108940
108941       /* Turns out that wasn't a keyword after all. This happens if the
108942       ** user has supplied a token such as "ORacle". Continue.
108943       */
108944     }
108945   }
108946
108947   /* Check for an open bracket. */
108948   if( sqlite3_fts3_enable_parentheses ){
108949     if( *zInput=='(' ){
108950       int nConsumed;
108951       int rc;
108952       pParse->nNest++;
108953       rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);
108954       if( rc==SQLITE_OK && !*ppExpr ){
108955         rc = SQLITE_DONE;
108956       }
108957       *pnConsumed = (int)((zInput - z) + 1 + nConsumed);
108958       return rc;
108959     }
108960   
108961     /* Check for a close bracket. */
108962     if( *zInput==')' ){
108963       pParse->nNest--;
108964       *pnConsumed = (int)((zInput - z) + 1);
108965       return SQLITE_DONE;
108966     }
108967   }
108968
108969   /* See if we are dealing with a quoted phrase. If this is the case, then
108970   ** search for the closing quote and pass the whole string to getNextString()
108971   ** for processing. This is easy to do, as fts3 has no syntax for escaping
108972   ** a quote character embedded in a string.
108973   */
108974   if( *zInput=='"' ){
108975     for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
108976     *pnConsumed = (int)((zInput - z) + ii + 1);
108977     if( ii==nInput ){
108978       return SQLITE_ERROR;
108979     }
108980     return getNextString(pParse, &zInput[1], ii-1, ppExpr);
108981   }
108982
108983
108984   /* If control flows to this point, this must be a regular token, or 
108985   ** the end of the input. Read a regular token using the sqlite3_tokenizer
108986   ** interface. Before doing so, figure out if there is an explicit
108987   ** column specifier for the token. 
108988   **
108989   ** TODO: Strangely, it is not possible to associate a column specifier
108990   ** with a quoted phrase, only with a single token. Not sure if this was
108991   ** an implementation artifact or an intentional decision when fts3 was
108992   ** first implemented. Whichever it was, this module duplicates the 
108993   ** limitation.
108994   */
108995   iCol = pParse->iDefaultCol;
108996   iColLen = 0;
108997   for(ii=0; ii<pParse->nCol; ii++){
108998     const char *zStr = pParse->azCol[ii];
108999     int nStr = (int)strlen(zStr);
109000     if( nInput>nStr && zInput[nStr]==':' 
109001      && sqlite3_strnicmp(zStr, zInput, nStr)==0 
109002     ){
109003       iCol = ii;
109004       iColLen = (int)((zInput - z) + nStr + 1);
109005       break;
109006     }
109007   }
109008   rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
109009   *pnConsumed += iColLen;
109010   return rc;
109011 }
109012
109013 /*
109014 ** The argument is an Fts3Expr structure for a binary operator (any type
109015 ** except an FTSQUERY_PHRASE). Return an integer value representing the
109016 ** precedence of the operator. Lower values have a higher precedence (i.e.
109017 ** group more tightly). For example, in the C language, the == operator
109018 ** groups more tightly than ||, and would therefore have a higher precedence.
109019 **
109020 ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
109021 ** is defined), the order of the operators in precedence from highest to
109022 ** lowest is:
109023 **
109024 **   NEAR
109025 **   NOT
109026 **   AND (including implicit ANDs)
109027 **   OR
109028 **
109029 ** Note that when using the old query syntax, the OR operator has a higher
109030 ** precedence than the AND operator.
109031 */
109032 static int opPrecedence(Fts3Expr *p){
109033   assert( p->eType!=FTSQUERY_PHRASE );
109034   if( sqlite3_fts3_enable_parentheses ){
109035     return p->eType;
109036   }else if( p->eType==FTSQUERY_NEAR ){
109037     return 1;
109038   }else if( p->eType==FTSQUERY_OR ){
109039     return 2;
109040   }
109041   assert( p->eType==FTSQUERY_AND );
109042   return 3;
109043 }
109044
109045 /*
109046 ** Argument ppHead contains a pointer to the current head of a query 
109047 ** expression tree being parsed. pPrev is the expression node most recently
109048 ** inserted into the tree. This function adds pNew, which is always a binary
109049 ** operator node, into the expression tree based on the relative precedence
109050 ** of pNew and the existing nodes of the tree. This may result in the head
109051 ** of the tree changing, in which case *ppHead is set to the new root node.
109052 */
109053 static void insertBinaryOperator(
109054   Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
109055   Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
109056   Fts3Expr *pNew           /* New binary node to insert into expression tree */
109057 ){
109058   Fts3Expr *pSplit = pPrev;
109059   while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
109060     pSplit = pSplit->pParent;
109061   }
109062
109063   if( pSplit->pParent ){
109064     assert( pSplit->pParent->pRight==pSplit );
109065     pSplit->pParent->pRight = pNew;
109066     pNew->pParent = pSplit->pParent;
109067   }else{
109068     *ppHead = pNew;
109069   }
109070   pNew->pLeft = pSplit;
109071   pSplit->pParent = pNew;
109072 }
109073
109074 /*
109075 ** Parse the fts3 query expression found in buffer z, length n. This function
109076 ** returns either when the end of the buffer is reached or an unmatched 
109077 ** closing bracket - ')' - is encountered.
109078 **
109079 ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
109080 ** parsed form of the expression and *pnConsumed is set to the number of
109081 ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
109082 ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
109083 */
109084 static int fts3ExprParse(
109085   ParseContext *pParse,                   /* fts3 query parse context */
109086   const char *z, int n,                   /* Text of MATCH query */
109087   Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
109088   int *pnConsumed                         /* OUT: Number of bytes consumed */
109089 ){
109090   Fts3Expr *pRet = 0;
109091   Fts3Expr *pPrev = 0;
109092   Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
109093   int nIn = n;
109094   const char *zIn = z;
109095   int rc = SQLITE_OK;
109096   int isRequirePhrase = 1;
109097
109098   while( rc==SQLITE_OK ){
109099     Fts3Expr *p = 0;
109100     int nByte = 0;
109101     rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
109102     if( rc==SQLITE_OK ){
109103       int isPhrase;
109104
109105       if( !sqlite3_fts3_enable_parentheses 
109106        && p->eType==FTSQUERY_PHRASE && p->pPhrase->isNot 
109107       ){
109108         /* Create an implicit NOT operator. */
109109         Fts3Expr *pNot = sqlite3_malloc(sizeof(Fts3Expr));
109110         if( !pNot ){
109111           sqlite3Fts3ExprFree(p);
109112           rc = SQLITE_NOMEM;
109113           goto exprparse_out;
109114         }
109115         memset(pNot, 0, sizeof(Fts3Expr));
109116         pNot->eType = FTSQUERY_NOT;
109117         pNot->pRight = p;
109118         if( pNotBranch ){
109119           pNot->pLeft = pNotBranch;
109120         }
109121         pNotBranch = pNot;
109122         p = pPrev;
109123       }else{
109124         int eType = p->eType;
109125         assert( eType!=FTSQUERY_PHRASE || !p->pPhrase->isNot );
109126         isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
109127
109128         /* The isRequirePhrase variable is set to true if a phrase or
109129         ** an expression contained in parenthesis is required. If a
109130         ** binary operator (AND, OR, NOT or NEAR) is encounted when
109131         ** isRequirePhrase is set, this is a syntax error.
109132         */
109133         if( !isPhrase && isRequirePhrase ){
109134           sqlite3Fts3ExprFree(p);
109135           rc = SQLITE_ERROR;
109136           goto exprparse_out;
109137         }
109138   
109139         if( isPhrase && !isRequirePhrase ){
109140           /* Insert an implicit AND operator. */
109141           Fts3Expr *pAnd;
109142           assert( pRet && pPrev );
109143           pAnd = sqlite3_malloc(sizeof(Fts3Expr));
109144           if( !pAnd ){
109145             sqlite3Fts3ExprFree(p);
109146             rc = SQLITE_NOMEM;
109147             goto exprparse_out;
109148           }
109149           memset(pAnd, 0, sizeof(Fts3Expr));
109150           pAnd->eType = FTSQUERY_AND;
109151           insertBinaryOperator(&pRet, pPrev, pAnd);
109152           pPrev = pAnd;
109153         }
109154
109155         /* This test catches attempts to make either operand of a NEAR
109156         ** operator something other than a phrase. For example, either of
109157         ** the following:
109158         **
109159         **    (bracketed expression) NEAR phrase
109160         **    phrase NEAR (bracketed expression)
109161         **
109162         ** Return an error in either case.
109163         */
109164         if( pPrev && (
109165             (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
109166          || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
109167         )){
109168           sqlite3Fts3ExprFree(p);
109169           rc = SQLITE_ERROR;
109170           goto exprparse_out;
109171         }
109172   
109173         if( isPhrase ){
109174           if( pRet ){
109175             assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
109176             pPrev->pRight = p;
109177             p->pParent = pPrev;
109178           }else{
109179             pRet = p;
109180           }
109181         }else{
109182           insertBinaryOperator(&pRet, pPrev, p);
109183         }
109184         isRequirePhrase = !isPhrase;
109185       }
109186       assert( nByte>0 );
109187     }
109188     assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
109189     nIn -= nByte;
109190     zIn += nByte;
109191     pPrev = p;
109192   }
109193
109194   if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
109195     rc = SQLITE_ERROR;
109196   }
109197
109198   if( rc==SQLITE_DONE ){
109199     rc = SQLITE_OK;
109200     if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
109201       if( !pRet ){
109202         rc = SQLITE_ERROR;
109203       }else{
109204         Fts3Expr *pIter = pNotBranch;
109205         while( pIter->pLeft ){
109206           pIter = pIter->pLeft;
109207         }
109208         pIter->pLeft = pRet;
109209         pRet = pNotBranch;
109210       }
109211     }
109212   }
109213   *pnConsumed = n - nIn;
109214
109215 exprparse_out:
109216   if( rc!=SQLITE_OK ){
109217     sqlite3Fts3ExprFree(pRet);
109218     sqlite3Fts3ExprFree(pNotBranch);
109219     pRet = 0;
109220   }
109221   *ppExpr = pRet;
109222   return rc;
109223 }
109224
109225 /*
109226 ** Parameters z and n contain a pointer to and length of a buffer containing
109227 ** an fts3 query expression, respectively. This function attempts to parse the
109228 ** query expression and create a tree of Fts3Expr structures representing the
109229 ** parsed expression. If successful, *ppExpr is set to point to the head
109230 ** of the parsed expression tree and SQLITE_OK is returned. If an error
109231 ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
109232 ** error) is returned and *ppExpr is set to 0.
109233 **
109234 ** If parameter n is a negative number, then z is assumed to point to a
109235 ** nul-terminated string and the length is determined using strlen().
109236 **
109237 ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
109238 ** use to normalize query tokens while parsing the expression. The azCol[]
109239 ** array, which is assumed to contain nCol entries, should contain the names
109240 ** of each column in the target fts3 table, in order from left to right. 
109241 ** Column names must be nul-terminated strings.
109242 **
109243 ** The iDefaultCol parameter should be passed the index of the table column
109244 ** that appears on the left-hand-side of the MATCH operator (the default
109245 ** column to match against for tokens for which a column name is not explicitly
109246 ** specified as part of the query string), or -1 if tokens may by default
109247 ** match any table column.
109248 */
109249 SQLITE_PRIVATE int sqlite3Fts3ExprParse(
109250   sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
109251   char **azCol,                       /* Array of column names for fts3 table */
109252   int nCol,                           /* Number of entries in azCol[] */
109253   int iDefaultCol,                    /* Default column to query */
109254   const char *z, int n,               /* Text of MATCH query */
109255   Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
109256 ){
109257   int nParsed;
109258   int rc;
109259   ParseContext sParse;
109260   sParse.pTokenizer = pTokenizer;
109261   sParse.azCol = (const char **)azCol;
109262   sParse.nCol = nCol;
109263   sParse.iDefaultCol = iDefaultCol;
109264   sParse.nNest = 0;
109265   if( z==0 ){
109266     *ppExpr = 0;
109267     return SQLITE_OK;
109268   }
109269   if( n<0 ){
109270     n = (int)strlen(z);
109271   }
109272   rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
109273
109274   /* Check for mismatched parenthesis */
109275   if( rc==SQLITE_OK && sParse.nNest ){
109276     rc = SQLITE_ERROR;
109277     sqlite3Fts3ExprFree(*ppExpr);
109278     *ppExpr = 0;
109279   }
109280
109281   return rc;
109282 }
109283
109284 /*
109285 ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
109286 */
109287 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *p){
109288   if( p ){
109289     sqlite3Fts3ExprFree(p->pLeft);
109290     sqlite3Fts3ExprFree(p->pRight);
109291     sqlite3_free(p->aDoclist);
109292     sqlite3_free(p);
109293   }
109294 }
109295
109296 /****************************************************************************
109297 *****************************************************************************
109298 ** Everything after this point is just test code.
109299 */
109300
109301 #ifdef SQLITE_TEST
109302
109303
109304 /*
109305 ** Function to query the hash-table of tokenizers (see README.tokenizers).
109306 */
109307 static int queryTestTokenizer(
109308   sqlite3 *db, 
109309   const char *zName,  
109310   const sqlite3_tokenizer_module **pp
109311 ){
109312   int rc;
109313   sqlite3_stmt *pStmt;
109314   const char zSql[] = "SELECT fts3_tokenizer(?)";
109315
109316   *pp = 0;
109317   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
109318   if( rc!=SQLITE_OK ){
109319     return rc;
109320   }
109321
109322   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
109323   if( SQLITE_ROW==sqlite3_step(pStmt) ){
109324     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
109325       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
109326     }
109327   }
109328
109329   return sqlite3_finalize(pStmt);
109330 }
109331
109332 /*
109333 ** This function is part of the test interface for the query parser. It
109334 ** writes a text representation of the query expression pExpr into the
109335 ** buffer pointed to by argument zBuf. It is assumed that zBuf is large 
109336 ** enough to store the required text representation.
109337 */
109338 static void exprToString(Fts3Expr *pExpr, char *zBuf){
109339   switch( pExpr->eType ){
109340     case FTSQUERY_PHRASE: {
109341       Fts3Phrase *pPhrase = pExpr->pPhrase;
109342       int i;
109343       zBuf += sprintf(zBuf, "PHRASE %d %d", pPhrase->iColumn, pPhrase->isNot);
109344       for(i=0; i<pPhrase->nToken; i++){
109345         zBuf += sprintf(zBuf," %.*s",pPhrase->aToken[i].n,pPhrase->aToken[i].z);
109346         zBuf += sprintf(zBuf,"%s", (pPhrase->aToken[i].isPrefix?"+":""));
109347       }
109348       return;
109349     }
109350
109351     case FTSQUERY_NEAR:
109352       zBuf += sprintf(zBuf, "NEAR/%d ", pExpr->nNear);
109353       break;
109354     case FTSQUERY_NOT:
109355       zBuf += sprintf(zBuf, "NOT ");
109356       break;
109357     case FTSQUERY_AND:
109358       zBuf += sprintf(zBuf, "AND ");
109359       break;
109360     case FTSQUERY_OR:
109361       zBuf += sprintf(zBuf, "OR ");
109362       break;
109363   }
109364
109365   zBuf += sprintf(zBuf, "{");
109366   exprToString(pExpr->pLeft, zBuf);
109367   zBuf += strlen(zBuf);
109368   zBuf += sprintf(zBuf, "} ");
109369
109370   zBuf += sprintf(zBuf, "{");
109371   exprToString(pExpr->pRight, zBuf);
109372   zBuf += strlen(zBuf);
109373   zBuf += sprintf(zBuf, "}");
109374 }
109375
109376 /*
109377 ** This is the implementation of a scalar SQL function used to test the 
109378 ** expression parser. It should be called as follows:
109379 **
109380 **   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
109381 **
109382 ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
109383 ** to parse the query expression (see README.tokenizers). The second argument
109384 ** is the query expression to parse. Each subsequent argument is the name
109385 ** of a column of the fts3 table that the query expression may refer to.
109386 ** For example:
109387 **
109388 **   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
109389 */
109390 static void fts3ExprTest(
109391   sqlite3_context *context,
109392   int argc,
109393   sqlite3_value **argv
109394 ){
109395   sqlite3_tokenizer_module const *pModule = 0;
109396   sqlite3_tokenizer *pTokenizer = 0;
109397   int rc;
109398   char **azCol = 0;
109399   const char *zExpr;
109400   int nExpr;
109401   int nCol;
109402   int ii;
109403   Fts3Expr *pExpr;
109404   sqlite3 *db = sqlite3_context_db_handle(context);
109405
109406   if( argc<3 ){
109407     sqlite3_result_error(context, 
109408         "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
109409     );
109410     return;
109411   }
109412
109413   rc = queryTestTokenizer(db,
109414                           (const char *)sqlite3_value_text(argv[0]), &pModule);
109415   if( rc==SQLITE_NOMEM ){
109416     sqlite3_result_error_nomem(context);
109417     goto exprtest_out;
109418   }else if( !pModule ){
109419     sqlite3_result_error(context, "No such tokenizer module", -1);
109420     goto exprtest_out;
109421   }
109422
109423   rc = pModule->xCreate(0, 0, &pTokenizer);
109424   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
109425   if( rc==SQLITE_NOMEM ){
109426     sqlite3_result_error_nomem(context);
109427     goto exprtest_out;
109428   }
109429   pTokenizer->pModule = pModule;
109430
109431   zExpr = (const char *)sqlite3_value_text(argv[1]);
109432   nExpr = sqlite3_value_bytes(argv[1]);
109433   nCol = argc-2;
109434   azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
109435   if( !azCol ){
109436     sqlite3_result_error_nomem(context);
109437     goto exprtest_out;
109438   }
109439   for(ii=0; ii<nCol; ii++){
109440     azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
109441   }
109442
109443   rc = sqlite3Fts3ExprParse(
109444       pTokenizer, azCol, nCol, nCol, zExpr, nExpr, &pExpr
109445   );
109446   if( rc==SQLITE_NOMEM ){
109447     sqlite3_result_error_nomem(context);
109448     goto exprtest_out;
109449   }else if( rc==SQLITE_OK ){
109450     char zBuf[4096];
109451     exprToString(pExpr, zBuf);
109452     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
109453     sqlite3Fts3ExprFree(pExpr);
109454   }else{
109455     sqlite3_result_error(context, "Error parsing expression", -1);
109456   }
109457
109458 exprtest_out:
109459   if( pModule && pTokenizer ){
109460     rc = pModule->xDestroy(pTokenizer);
109461   }
109462   sqlite3_free(azCol);
109463 }
109464
109465 /*
109466 ** Register the query expression parser test function fts3_exprtest() 
109467 ** with database connection db. 
109468 */
109469 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
109470   return sqlite3_create_function(
109471       db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
109472   );
109473 }
109474
109475 #endif
109476 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
109477
109478 /************** End of fts3_expr.c *******************************************/
109479 /************** Begin file fts3_hash.c ***************************************/
109480 /*
109481 ** 2001 September 22
109482 **
109483 ** The author disclaims copyright to this source code.  In place of
109484 ** a legal notice, here is a blessing:
109485 **
109486 **    May you do good and not evil.
109487 **    May you find forgiveness for yourself and forgive others.
109488 **    May you share freely, never taking more than you give.
109489 **
109490 *************************************************************************
109491 ** This is the implementation of generic hash-tables used in SQLite.
109492 ** We've modified it slightly to serve as a standalone hash table
109493 ** implementation for the full-text indexing module.
109494 */
109495
109496 /*
109497 ** The code in this file is only compiled if:
109498 **
109499 **     * The FTS3 module is being built as an extension
109500 **       (in which case SQLITE_CORE is not defined), or
109501 **
109502 **     * The FTS3 module is being built into the core of
109503 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
109504 */
109505 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
109506
109507
109508
109509 /*
109510 ** Malloc and Free functions
109511 */
109512 static void *fts3HashMalloc(int n){
109513   void *p = sqlite3_malloc(n);
109514   if( p ){
109515     memset(p, 0, n);
109516   }
109517   return p;
109518 }
109519 static void fts3HashFree(void *p){
109520   sqlite3_free(p);
109521 }
109522
109523 /* Turn bulk memory into a hash table object by initializing the
109524 ** fields of the Hash structure.
109525 **
109526 ** "pNew" is a pointer to the hash table that is to be initialized.
109527 ** keyClass is one of the constants 
109528 ** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass 
109529 ** determines what kind of key the hash table will use.  "copyKey" is
109530 ** true if the hash table should make its own private copy of keys and
109531 ** false if it should just use the supplied pointer.
109532 */
109533 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
109534   assert( pNew!=0 );
109535   assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
109536   pNew->keyClass = keyClass;
109537   pNew->copyKey = copyKey;
109538   pNew->first = 0;
109539   pNew->count = 0;
109540   pNew->htsize = 0;
109541   pNew->ht = 0;
109542 }
109543
109544 /* Remove all entries from a hash table.  Reclaim all memory.
109545 ** Call this routine to delete a hash table or to reset a hash table
109546 ** to the empty state.
109547 */
109548 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
109549   Fts3HashElem *elem;         /* For looping over all elements of the table */
109550
109551   assert( pH!=0 );
109552   elem = pH->first;
109553   pH->first = 0;
109554   fts3HashFree(pH->ht);
109555   pH->ht = 0;
109556   pH->htsize = 0;
109557   while( elem ){
109558     Fts3HashElem *next_elem = elem->next;
109559     if( pH->copyKey && elem->pKey ){
109560       fts3HashFree(elem->pKey);
109561     }
109562     fts3HashFree(elem);
109563     elem = next_elem;
109564   }
109565   pH->count = 0;
109566 }
109567
109568 /*
109569 ** Hash and comparison functions when the mode is FTS3_HASH_STRING
109570 */
109571 static int fts3StrHash(const void *pKey, int nKey){
109572   const char *z = (const char *)pKey;
109573   int h = 0;
109574   if( nKey<=0 ) nKey = (int) strlen(z);
109575   while( nKey > 0  ){
109576     h = (h<<3) ^ h ^ *z++;
109577     nKey--;
109578   }
109579   return h & 0x7fffffff;
109580 }
109581 static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
109582   if( n1!=n2 ) return 1;
109583   return strncmp((const char*)pKey1,(const char*)pKey2,n1);
109584 }
109585
109586 /*
109587 ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
109588 */
109589 static int fts3BinHash(const void *pKey, int nKey){
109590   int h = 0;
109591   const char *z = (const char *)pKey;
109592   while( nKey-- > 0 ){
109593     h = (h<<3) ^ h ^ *(z++);
109594   }
109595   return h & 0x7fffffff;
109596 }
109597 static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
109598   if( n1!=n2 ) return 1;
109599   return memcmp(pKey1,pKey2,n1);
109600 }
109601
109602 /*
109603 ** Return a pointer to the appropriate hash function given the key class.
109604 **
109605 ** The C syntax in this function definition may be unfamilar to some 
109606 ** programmers, so we provide the following additional explanation:
109607 **
109608 ** The name of the function is "ftsHashFunction".  The function takes a
109609 ** single parameter "keyClass".  The return value of ftsHashFunction()
109610 ** is a pointer to another function.  Specifically, the return value
109611 ** of ftsHashFunction() is a pointer to a function that takes two parameters
109612 ** with types "const void*" and "int" and returns an "int".
109613 */
109614 static int (*ftsHashFunction(int keyClass))(const void*,int){
109615   if( keyClass==FTS3_HASH_STRING ){
109616     return &fts3StrHash;
109617   }else{
109618     assert( keyClass==FTS3_HASH_BINARY );
109619     return &fts3BinHash;
109620   }
109621 }
109622
109623 /*
109624 ** Return a pointer to the appropriate hash function given the key class.
109625 **
109626 ** For help in interpreted the obscure C code in the function definition,
109627 ** see the header comment on the previous function.
109628 */
109629 static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
109630   if( keyClass==FTS3_HASH_STRING ){
109631     return &fts3StrCompare;
109632   }else{
109633     assert( keyClass==FTS3_HASH_BINARY );
109634     return &fts3BinCompare;
109635   }
109636 }
109637
109638 /* Link an element into the hash table
109639 */
109640 static void fts3HashInsertElement(
109641   Fts3Hash *pH,            /* The complete hash table */
109642   struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
109643   Fts3HashElem *pNew       /* The element to be inserted */
109644 ){
109645   Fts3HashElem *pHead;     /* First element already in pEntry */
109646   pHead = pEntry->chain;
109647   if( pHead ){
109648     pNew->next = pHead;
109649     pNew->prev = pHead->prev;
109650     if( pHead->prev ){ pHead->prev->next = pNew; }
109651     else             { pH->first = pNew; }
109652     pHead->prev = pNew;
109653   }else{
109654     pNew->next = pH->first;
109655     if( pH->first ){ pH->first->prev = pNew; }
109656     pNew->prev = 0;
109657     pH->first = pNew;
109658   }
109659   pEntry->count++;
109660   pEntry->chain = pNew;
109661 }
109662
109663
109664 /* Resize the hash table so that it cantains "new_size" buckets.
109665 ** "new_size" must be a power of 2.  The hash table might fail 
109666 ** to resize if sqliteMalloc() fails.
109667 **
109668 ** Return non-zero if a memory allocation error occurs.
109669 */
109670 static int fts3Rehash(Fts3Hash *pH, int new_size){
109671   struct _fts3ht *new_ht;          /* The new hash table */
109672   Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
109673   int (*xHash)(const void*,int);   /* The hash function */
109674
109675   assert( (new_size & (new_size-1))==0 );
109676   new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
109677   if( new_ht==0 ) return 1;
109678   fts3HashFree(pH->ht);
109679   pH->ht = new_ht;
109680   pH->htsize = new_size;
109681   xHash = ftsHashFunction(pH->keyClass);
109682   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
109683     int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
109684     next_elem = elem->next;
109685     fts3HashInsertElement(pH, &new_ht[h], elem);
109686   }
109687   return 0;
109688 }
109689
109690 /* This function (for internal use only) locates an element in an
109691 ** hash table that matches the given key.  The hash for this key has
109692 ** already been computed and is passed as the 4th parameter.
109693 */
109694 static Fts3HashElem *fts3FindElementByHash(
109695   const Fts3Hash *pH, /* The pH to be searched */
109696   const void *pKey,   /* The key we are searching for */
109697   int nKey,
109698   int h               /* The hash for this key. */
109699 ){
109700   Fts3HashElem *elem;            /* Used to loop thru the element list */
109701   int count;                     /* Number of elements left to test */
109702   int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
109703
109704   if( pH->ht ){
109705     struct _fts3ht *pEntry = &pH->ht[h];
109706     elem = pEntry->chain;
109707     count = pEntry->count;
109708     xCompare = ftsCompareFunction(pH->keyClass);
109709     while( count-- && elem ){
109710       if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ 
109711         return elem;
109712       }
109713       elem = elem->next;
109714     }
109715   }
109716   return 0;
109717 }
109718
109719 /* Remove a single entry from the hash table given a pointer to that
109720 ** element and a hash on the element's key.
109721 */
109722 static void fts3RemoveElementByHash(
109723   Fts3Hash *pH,         /* The pH containing "elem" */
109724   Fts3HashElem* elem,   /* The element to be removed from the pH */
109725   int h                 /* Hash value for the element */
109726 ){
109727   struct _fts3ht *pEntry;
109728   if( elem->prev ){
109729     elem->prev->next = elem->next; 
109730   }else{
109731     pH->first = elem->next;
109732   }
109733   if( elem->next ){
109734     elem->next->prev = elem->prev;
109735   }
109736   pEntry = &pH->ht[h];
109737   if( pEntry->chain==elem ){
109738     pEntry->chain = elem->next;
109739   }
109740   pEntry->count--;
109741   if( pEntry->count<=0 ){
109742     pEntry->chain = 0;
109743   }
109744   if( pH->copyKey && elem->pKey ){
109745     fts3HashFree(elem->pKey);
109746   }
109747   fts3HashFree( elem );
109748   pH->count--;
109749   if( pH->count<=0 ){
109750     assert( pH->first==0 );
109751     assert( pH->count==0 );
109752     fts3HashClear(pH);
109753   }
109754 }
109755
109756 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
109757   const Fts3Hash *pH, 
109758   const void *pKey, 
109759   int nKey
109760 ){
109761   int h;                          /* A hash on key */
109762   int (*xHash)(const void*,int);  /* The hash function */
109763
109764   if( pH==0 || pH->ht==0 ) return 0;
109765   xHash = ftsHashFunction(pH->keyClass);
109766   assert( xHash!=0 );
109767   h = (*xHash)(pKey,nKey);
109768   assert( (pH->htsize & (pH->htsize-1))==0 );
109769   return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
109770 }
109771
109772 /* 
109773 ** Attempt to locate an element of the hash table pH with a key
109774 ** that matches pKey,nKey.  Return the data for this element if it is
109775 ** found, or NULL if there is no match.
109776 */
109777 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
109778   Fts3HashElem *pElem;            /* The element that matches key (if any) */
109779
109780   pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
109781   return pElem ? pElem->data : 0;
109782 }
109783
109784 /* Insert an element into the hash table pH.  The key is pKey,nKey
109785 ** and the data is "data".
109786 **
109787 ** If no element exists with a matching key, then a new
109788 ** element is created.  A copy of the key is made if the copyKey
109789 ** flag is set.  NULL is returned.
109790 **
109791 ** If another element already exists with the same key, then the
109792 ** new data replaces the old data and the old data is returned.
109793 ** The key is not copied in this instance.  If a malloc fails, then
109794 ** the new data is returned and the hash table is unchanged.
109795 **
109796 ** If the "data" parameter to this function is NULL, then the
109797 ** element corresponding to "key" is removed from the hash table.
109798 */
109799 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
109800   Fts3Hash *pH,        /* The hash table to insert into */
109801   const void *pKey,    /* The key */
109802   int nKey,            /* Number of bytes in the key */
109803   void *data           /* The data */
109804 ){
109805   int hraw;                 /* Raw hash value of the key */
109806   int h;                    /* the hash of the key modulo hash table size */
109807   Fts3HashElem *elem;       /* Used to loop thru the element list */
109808   Fts3HashElem *new_elem;   /* New element added to the pH */
109809   int (*xHash)(const void*,int);  /* The hash function */
109810
109811   assert( pH!=0 );
109812   xHash = ftsHashFunction(pH->keyClass);
109813   assert( xHash!=0 );
109814   hraw = (*xHash)(pKey, nKey);
109815   assert( (pH->htsize & (pH->htsize-1))==0 );
109816   h = hraw & (pH->htsize-1);
109817   elem = fts3FindElementByHash(pH,pKey,nKey,h);
109818   if( elem ){
109819     void *old_data = elem->data;
109820     if( data==0 ){
109821       fts3RemoveElementByHash(pH,elem,h);
109822     }else{
109823       elem->data = data;
109824     }
109825     return old_data;
109826   }
109827   if( data==0 ) return 0;
109828   if( (pH->htsize==0 && fts3Rehash(pH,8))
109829    || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
109830   ){
109831     pH->count = 0;
109832     return data;
109833   }
109834   assert( pH->htsize>0 );
109835   new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
109836   if( new_elem==0 ) return data;
109837   if( pH->copyKey && pKey!=0 ){
109838     new_elem->pKey = fts3HashMalloc( nKey );
109839     if( new_elem->pKey==0 ){
109840       fts3HashFree(new_elem);
109841       return data;
109842     }
109843     memcpy((void*)new_elem->pKey, pKey, nKey);
109844   }else{
109845     new_elem->pKey = (void*)pKey;
109846   }
109847   new_elem->nKey = nKey;
109848   pH->count++;
109849   assert( pH->htsize>0 );
109850   assert( (pH->htsize & (pH->htsize-1))==0 );
109851   h = hraw & (pH->htsize-1);
109852   fts3HashInsertElement(pH, &pH->ht[h], new_elem);
109853   new_elem->data = data;
109854   return 0;
109855 }
109856
109857 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
109858
109859 /************** End of fts3_hash.c *******************************************/
109860 /************** Begin file fts3_porter.c *************************************/
109861 /*
109862 ** 2006 September 30
109863 **
109864 ** The author disclaims copyright to this source code.  In place of
109865 ** a legal notice, here is a blessing:
109866 **
109867 **    May you do good and not evil.
109868 **    May you find forgiveness for yourself and forgive others.
109869 **    May you share freely, never taking more than you give.
109870 **
109871 *************************************************************************
109872 ** Implementation of the full-text-search tokenizer that implements
109873 ** a Porter stemmer.
109874 */
109875
109876 /*
109877 ** The code in this file is only compiled if:
109878 **
109879 **     * The FTS3 module is being built as an extension
109880 **       (in which case SQLITE_CORE is not defined), or
109881 **
109882 **     * The FTS3 module is being built into the core of
109883 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
109884 */
109885 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
109886
109887
109888
109889
109890 /*
109891 ** Class derived from sqlite3_tokenizer
109892 */
109893 typedef struct porter_tokenizer {
109894   sqlite3_tokenizer base;      /* Base class */
109895 } porter_tokenizer;
109896
109897 /*
109898 ** Class derived from sqlit3_tokenizer_cursor
109899 */
109900 typedef struct porter_tokenizer_cursor {
109901   sqlite3_tokenizer_cursor base;
109902   const char *zInput;          /* input we are tokenizing */
109903   int nInput;                  /* size of the input */
109904   int iOffset;                 /* current position in zInput */
109905   int iToken;                  /* index of next token to be returned */
109906   char *zToken;                /* storage for current token */
109907   int nAllocated;              /* space allocated to zToken buffer */
109908 } porter_tokenizer_cursor;
109909
109910
109911 /*
109912 ** Create a new tokenizer instance.
109913 */
109914 static int porterCreate(
109915   int argc, const char * const *argv,
109916   sqlite3_tokenizer **ppTokenizer
109917 ){
109918   porter_tokenizer *t;
109919
109920   UNUSED_PARAMETER(argc);
109921   UNUSED_PARAMETER(argv);
109922
109923   t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
109924   if( t==NULL ) return SQLITE_NOMEM;
109925   memset(t, 0, sizeof(*t));
109926   *ppTokenizer = &t->base;
109927   return SQLITE_OK;
109928 }
109929
109930 /*
109931 ** Destroy a tokenizer
109932 */
109933 static int porterDestroy(sqlite3_tokenizer *pTokenizer){
109934   sqlite3_free(pTokenizer);
109935   return SQLITE_OK;
109936 }
109937
109938 /*
109939 ** Prepare to begin tokenizing a particular string.  The input
109940 ** string to be tokenized is zInput[0..nInput-1].  A cursor
109941 ** used to incrementally tokenize this string is returned in 
109942 ** *ppCursor.
109943 */
109944 static int porterOpen(
109945   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
109946   const char *zInput, int nInput,        /* String to be tokenized */
109947   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
109948 ){
109949   porter_tokenizer_cursor *c;
109950
109951   UNUSED_PARAMETER(pTokenizer);
109952
109953   c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
109954   if( c==NULL ) return SQLITE_NOMEM;
109955
109956   c->zInput = zInput;
109957   if( zInput==0 ){
109958     c->nInput = 0;
109959   }else if( nInput<0 ){
109960     c->nInput = (int)strlen(zInput);
109961   }else{
109962     c->nInput = nInput;
109963   }
109964   c->iOffset = 0;                 /* start tokenizing at the beginning */
109965   c->iToken = 0;
109966   c->zToken = NULL;               /* no space allocated, yet. */
109967   c->nAllocated = 0;
109968
109969   *ppCursor = &c->base;
109970   return SQLITE_OK;
109971 }
109972
109973 /*
109974 ** Close a tokenization cursor previously opened by a call to
109975 ** porterOpen() above.
109976 */
109977 static int porterClose(sqlite3_tokenizer_cursor *pCursor){
109978   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
109979   sqlite3_free(c->zToken);
109980   sqlite3_free(c);
109981   return SQLITE_OK;
109982 }
109983 /*
109984 ** Vowel or consonant
109985 */
109986 static const char cType[] = {
109987    0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
109988    1, 1, 1, 2, 1
109989 };
109990
109991 /*
109992 ** isConsonant() and isVowel() determine if their first character in
109993 ** the string they point to is a consonant or a vowel, according
109994 ** to Porter ruls.  
109995 **
109996 ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
109997 ** 'Y' is a consonant unless it follows another consonant,
109998 ** in which case it is a vowel.
109999 **
110000 ** In these routine, the letters are in reverse order.  So the 'y' rule
110001 ** is that 'y' is a consonant unless it is followed by another
110002 ** consonent.
110003 */
110004 static int isVowel(const char*);
110005 static int isConsonant(const char *z){
110006   int j;
110007   char x = *z;
110008   if( x==0 ) return 0;
110009   assert( x>='a' && x<='z' );
110010   j = cType[x-'a'];
110011   if( j<2 ) return j;
110012   return z[1]==0 || isVowel(z + 1);
110013 }
110014 static int isVowel(const char *z){
110015   int j;
110016   char x = *z;
110017   if( x==0 ) return 0;
110018   assert( x>='a' && x<='z' );
110019   j = cType[x-'a'];
110020   if( j<2 ) return 1-j;
110021   return isConsonant(z + 1);
110022 }
110023
110024 /*
110025 ** Let any sequence of one or more vowels be represented by V and let
110026 ** C be sequence of one or more consonants.  Then every word can be
110027 ** represented as:
110028 **
110029 **           [C] (VC){m} [V]
110030 **
110031 ** In prose:  A word is an optional consonant followed by zero or
110032 ** vowel-consonant pairs followed by an optional vowel.  "m" is the
110033 ** number of vowel consonant pairs.  This routine computes the value
110034 ** of m for the first i bytes of a word.
110035 **
110036 ** Return true if the m-value for z is 1 or more.  In other words,
110037 ** return true if z contains at least one vowel that is followed
110038 ** by a consonant.
110039 **
110040 ** In this routine z[] is in reverse order.  So we are really looking
110041 ** for an instance of of a consonant followed by a vowel.
110042 */
110043 static int m_gt_0(const char *z){
110044   while( isVowel(z) ){ z++; }
110045   if( *z==0 ) return 0;
110046   while( isConsonant(z) ){ z++; }
110047   return *z!=0;
110048 }
110049
110050 /* Like mgt0 above except we are looking for a value of m which is
110051 ** exactly 1
110052 */
110053 static int m_eq_1(const char *z){
110054   while( isVowel(z) ){ z++; }
110055   if( *z==0 ) return 0;
110056   while( isConsonant(z) ){ z++; }
110057   if( *z==0 ) return 0;
110058   while( isVowel(z) ){ z++; }
110059   if( *z==0 ) return 1;
110060   while( isConsonant(z) ){ z++; }
110061   return *z==0;
110062 }
110063
110064 /* Like mgt0 above except we are looking for a value of m>1 instead
110065 ** or m>0
110066 */
110067 static int m_gt_1(const char *z){
110068   while( isVowel(z) ){ z++; }
110069   if( *z==0 ) return 0;
110070   while( isConsonant(z) ){ z++; }
110071   if( *z==0 ) return 0;
110072   while( isVowel(z) ){ z++; }
110073   if( *z==0 ) return 0;
110074   while( isConsonant(z) ){ z++; }
110075   return *z!=0;
110076 }
110077
110078 /*
110079 ** Return TRUE if there is a vowel anywhere within z[0..n-1]
110080 */
110081 static int hasVowel(const char *z){
110082   while( isConsonant(z) ){ z++; }
110083   return *z!=0;
110084 }
110085
110086 /*
110087 ** Return TRUE if the word ends in a double consonant.
110088 **
110089 ** The text is reversed here. So we are really looking at
110090 ** the first two characters of z[].
110091 */
110092 static int doubleConsonant(const char *z){
110093   return isConsonant(z) && z[0]==z[1];
110094 }
110095
110096 /*
110097 ** Return TRUE if the word ends with three letters which
110098 ** are consonant-vowel-consonent and where the final consonant
110099 ** is not 'w', 'x', or 'y'.
110100 **
110101 ** The word is reversed here.  So we are really checking the
110102 ** first three letters and the first one cannot be in [wxy].
110103 */
110104 static int star_oh(const char *z){
110105   return
110106     isConsonant(z) &&
110107     z[0]!='w' && z[0]!='x' && z[0]!='y' &&
110108     isVowel(z+1) &&
110109     isConsonant(z+2);
110110 }
110111
110112 /*
110113 ** If the word ends with zFrom and xCond() is true for the stem
110114 ** of the word that preceeds the zFrom ending, then change the 
110115 ** ending to zTo.
110116 **
110117 ** The input word *pz and zFrom are both in reverse order.  zTo
110118 ** is in normal order. 
110119 **
110120 ** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
110121 ** match.  Not that TRUE is returned even if xCond() fails and
110122 ** no substitution occurs.
110123 */
110124 static int stem(
110125   char **pz,             /* The word being stemmed (Reversed) */
110126   const char *zFrom,     /* If the ending matches this... (Reversed) */
110127   const char *zTo,       /* ... change the ending to this (not reversed) */
110128   int (*xCond)(const char*)   /* Condition that must be true */
110129 ){
110130   char *z = *pz;
110131   while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
110132   if( *zFrom!=0 ) return 0;
110133   if( xCond && !xCond(z) ) return 1;
110134   while( *zTo ){
110135     *(--z) = *(zTo++);
110136   }
110137   *pz = z;
110138   return 1;
110139 }
110140
110141 /*
110142 ** This is the fallback stemmer used when the porter stemmer is
110143 ** inappropriate.  The input word is copied into the output with
110144 ** US-ASCII case folding.  If the input word is too long (more
110145 ** than 20 bytes if it contains no digits or more than 6 bytes if
110146 ** it contains digits) then word is truncated to 20 or 6 bytes
110147 ** by taking 10 or 3 bytes from the beginning and end.
110148 */
110149 static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
110150   int i, mx, j;
110151   int hasDigit = 0;
110152   for(i=0; i<nIn; i++){
110153     char c = zIn[i];
110154     if( c>='A' && c<='Z' ){
110155       zOut[i] = c - 'A' + 'a';
110156     }else{
110157       if( c>='0' && c<='9' ) hasDigit = 1;
110158       zOut[i] = c;
110159     }
110160   }
110161   mx = hasDigit ? 3 : 10;
110162   if( nIn>mx*2 ){
110163     for(j=mx, i=nIn-mx; i<nIn; i++, j++){
110164       zOut[j] = zOut[i];
110165     }
110166     i = j;
110167   }
110168   zOut[i] = 0;
110169   *pnOut = i;
110170 }
110171
110172
110173 /*
110174 ** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
110175 ** zOut is at least big enough to hold nIn bytes.  Write the actual
110176 ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
110177 **
110178 ** Any upper-case characters in the US-ASCII character set ([A-Z])
110179 ** are converted to lower case.  Upper-case UTF characters are
110180 ** unchanged.
110181 **
110182 ** Words that are longer than about 20 bytes are stemmed by retaining
110183 ** a few bytes from the beginning and the end of the word.  If the
110184 ** word contains digits, 3 bytes are taken from the beginning and
110185 ** 3 bytes from the end.  For long words without digits, 10 bytes
110186 ** are taken from each end.  US-ASCII case folding still applies.
110187 ** 
110188 ** If the input word contains not digits but does characters not 
110189 ** in [a-zA-Z] then no stemming is attempted and this routine just 
110190 ** copies the input into the input into the output with US-ASCII
110191 ** case folding.
110192 **
110193 ** Stemming never increases the length of the word.  So there is
110194 ** no chance of overflowing the zOut buffer.
110195 */
110196 static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
110197   int i, j;
110198   char zReverse[28];
110199   char *z, *z2;
110200   if( nIn<3 || nIn>=sizeof(zReverse)-7 ){
110201     /* The word is too big or too small for the porter stemmer.
110202     ** Fallback to the copy stemmer */
110203     copy_stemmer(zIn, nIn, zOut, pnOut);
110204     return;
110205   }
110206   for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
110207     char c = zIn[i];
110208     if( c>='A' && c<='Z' ){
110209       zReverse[j] = c + 'a' - 'A';
110210     }else if( c>='a' && c<='z' ){
110211       zReverse[j] = c;
110212     }else{
110213       /* The use of a character not in [a-zA-Z] means that we fallback
110214       ** to the copy stemmer */
110215       copy_stemmer(zIn, nIn, zOut, pnOut);
110216       return;
110217     }
110218   }
110219   memset(&zReverse[sizeof(zReverse)-5], 0, 5);
110220   z = &zReverse[j+1];
110221
110222
110223   /* Step 1a */
110224   if( z[0]=='s' ){
110225     if(
110226      !stem(&z, "sess", "ss", 0) &&
110227      !stem(&z, "sei", "i", 0)  &&
110228      !stem(&z, "ss", "ss", 0)
110229     ){
110230       z++;
110231     }
110232   }
110233
110234   /* Step 1b */  
110235   z2 = z;
110236   if( stem(&z, "dee", "ee", m_gt_0) ){
110237     /* Do nothing.  The work was all in the test */
110238   }else if( 
110239      (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
110240       && z!=z2
110241   ){
110242      if( stem(&z, "ta", "ate", 0) ||
110243          stem(&z, "lb", "ble", 0) ||
110244          stem(&z, "zi", "ize", 0) ){
110245        /* Do nothing.  The work was all in the test */
110246      }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
110247        z++;
110248      }else if( m_eq_1(z) && star_oh(z) ){
110249        *(--z) = 'e';
110250      }
110251   }
110252
110253   /* Step 1c */
110254   if( z[0]=='y' && hasVowel(z+1) ){
110255     z[0] = 'i';
110256   }
110257
110258   /* Step 2 */
110259   switch( z[1] ){
110260    case 'a':
110261      stem(&z, "lanoita", "ate", m_gt_0) ||
110262      stem(&z, "lanoit", "tion", m_gt_0);
110263      break;
110264    case 'c':
110265      stem(&z, "icne", "ence", m_gt_0) ||
110266      stem(&z, "icna", "ance", m_gt_0);
110267      break;
110268    case 'e':
110269      stem(&z, "rezi", "ize", m_gt_0);
110270      break;
110271    case 'g':
110272      stem(&z, "igol", "log", m_gt_0);
110273      break;
110274    case 'l':
110275      stem(&z, "ilb", "ble", m_gt_0) ||
110276      stem(&z, "illa", "al", m_gt_0) ||
110277      stem(&z, "iltne", "ent", m_gt_0) ||
110278      stem(&z, "ile", "e", m_gt_0) ||
110279      stem(&z, "ilsuo", "ous", m_gt_0);
110280      break;
110281    case 'o':
110282      stem(&z, "noitazi", "ize", m_gt_0) ||
110283      stem(&z, "noita", "ate", m_gt_0) ||
110284      stem(&z, "rota", "ate", m_gt_0);
110285      break;
110286    case 's':
110287      stem(&z, "msila", "al", m_gt_0) ||
110288      stem(&z, "ssenevi", "ive", m_gt_0) ||
110289      stem(&z, "ssenluf", "ful", m_gt_0) ||
110290      stem(&z, "ssensuo", "ous", m_gt_0);
110291      break;
110292    case 't':
110293      stem(&z, "itila", "al", m_gt_0) ||
110294      stem(&z, "itivi", "ive", m_gt_0) ||
110295      stem(&z, "itilib", "ble", m_gt_0);
110296      break;
110297   }
110298
110299   /* Step 3 */
110300   switch( z[0] ){
110301    case 'e':
110302      stem(&z, "etaci", "ic", m_gt_0) ||
110303      stem(&z, "evita", "", m_gt_0)   ||
110304      stem(&z, "ezila", "al", m_gt_0);
110305      break;
110306    case 'i':
110307      stem(&z, "itici", "ic", m_gt_0);
110308      break;
110309    case 'l':
110310      stem(&z, "laci", "ic", m_gt_0) ||
110311      stem(&z, "luf", "", m_gt_0);
110312      break;
110313    case 's':
110314      stem(&z, "ssen", "", m_gt_0);
110315      break;
110316   }
110317
110318   /* Step 4 */
110319   switch( z[1] ){
110320    case 'a':
110321      if( z[0]=='l' && m_gt_1(z+2) ){
110322        z += 2;
110323      }
110324      break;
110325    case 'c':
110326      if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
110327        z += 4;
110328      }
110329      break;
110330    case 'e':
110331      if( z[0]=='r' && m_gt_1(z+2) ){
110332        z += 2;
110333      }
110334      break;
110335    case 'i':
110336      if( z[0]=='c' && m_gt_1(z+2) ){
110337        z += 2;
110338      }
110339      break;
110340    case 'l':
110341      if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
110342        z += 4;
110343      }
110344      break;
110345    case 'n':
110346      if( z[0]=='t' ){
110347        if( z[2]=='a' ){
110348          if( m_gt_1(z+3) ){
110349            z += 3;
110350          }
110351        }else if( z[2]=='e' ){
110352          stem(&z, "tneme", "", m_gt_1) ||
110353          stem(&z, "tnem", "", m_gt_1) ||
110354          stem(&z, "tne", "", m_gt_1);
110355        }
110356      }
110357      break;
110358    case 'o':
110359      if( z[0]=='u' ){
110360        if( m_gt_1(z+2) ){
110361          z += 2;
110362        }
110363      }else if( z[3]=='s' || z[3]=='t' ){
110364        stem(&z, "noi", "", m_gt_1);
110365      }
110366      break;
110367    case 's':
110368      if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
110369        z += 3;
110370      }
110371      break;
110372    case 't':
110373      stem(&z, "eta", "", m_gt_1) ||
110374      stem(&z, "iti", "", m_gt_1);
110375      break;
110376    case 'u':
110377      if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
110378        z += 3;
110379      }
110380      break;
110381    case 'v':
110382    case 'z':
110383      if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
110384        z += 3;
110385      }
110386      break;
110387   }
110388
110389   /* Step 5a */
110390   if( z[0]=='e' ){
110391     if( m_gt_1(z+1) ){
110392       z++;
110393     }else if( m_eq_1(z+1) && !star_oh(z+1) ){
110394       z++;
110395     }
110396   }
110397
110398   /* Step 5b */
110399   if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
110400     z++;
110401   }
110402
110403   /* z[] is now the stemmed word in reverse order.  Flip it back
110404   ** around into forward order and return.
110405   */
110406   *pnOut = i = (int)strlen(z);
110407   zOut[i] = 0;
110408   while( *z ){
110409     zOut[--i] = *(z++);
110410   }
110411 }
110412
110413 /*
110414 ** Characters that can be part of a token.  We assume any character
110415 ** whose value is greater than 0x80 (any UTF character) can be
110416 ** part of a token.  In other words, delimiters all must have
110417 ** values of 0x7f or lower.
110418 */
110419 static const char porterIdChar[] = {
110420 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
110421     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
110422     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
110423     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
110424     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
110425     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
110426 };
110427 #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
110428
110429 /*
110430 ** Extract the next token from a tokenization cursor.  The cursor must
110431 ** have been opened by a prior call to porterOpen().
110432 */
110433 static int porterNext(
110434   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
110435   const char **pzToken,               /* OUT: *pzToken is the token text */
110436   int *pnBytes,                       /* OUT: Number of bytes in token */
110437   int *piStartOffset,                 /* OUT: Starting offset of token */
110438   int *piEndOffset,                   /* OUT: Ending offset of token */
110439   int *piPosition                     /* OUT: Position integer of token */
110440 ){
110441   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
110442   const char *z = c->zInput;
110443
110444   while( c->iOffset<c->nInput ){
110445     int iStartOffset, ch;
110446
110447     /* Scan past delimiter characters */
110448     while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
110449       c->iOffset++;
110450     }
110451
110452     /* Count non-delimiter characters. */
110453     iStartOffset = c->iOffset;
110454     while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
110455       c->iOffset++;
110456     }
110457
110458     if( c->iOffset>iStartOffset ){
110459       int n = c->iOffset-iStartOffset;
110460       if( n>c->nAllocated ){
110461         char *pNew;
110462         c->nAllocated = n+20;
110463         pNew = sqlite3_realloc(c->zToken, c->nAllocated);
110464         if( !pNew ) return SQLITE_NOMEM;
110465         c->zToken = pNew;
110466       }
110467       porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
110468       *pzToken = c->zToken;
110469       *piStartOffset = iStartOffset;
110470       *piEndOffset = c->iOffset;
110471       *piPosition = c->iToken++;
110472       return SQLITE_OK;
110473     }
110474   }
110475   return SQLITE_DONE;
110476 }
110477
110478 /*
110479 ** The set of routines that implement the porter-stemmer tokenizer
110480 */
110481 static const sqlite3_tokenizer_module porterTokenizerModule = {
110482   0,
110483   porterCreate,
110484   porterDestroy,
110485   porterOpen,
110486   porterClose,
110487   porterNext,
110488 };
110489
110490 /*
110491 ** Allocate a new porter tokenizer.  Return a pointer to the new
110492 ** tokenizer in *ppModule
110493 */
110494 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
110495   sqlite3_tokenizer_module const**ppModule
110496 ){
110497   *ppModule = &porterTokenizerModule;
110498 }
110499
110500 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
110501
110502 /************** End of fts3_porter.c *****************************************/
110503 /************** Begin file fts3_tokenizer.c **********************************/
110504 /*
110505 ** 2007 June 22
110506 **
110507 ** The author disclaims copyright to this source code.  In place of
110508 ** a legal notice, here is a blessing:
110509 **
110510 **    May you do good and not evil.
110511 **    May you find forgiveness for yourself and forgive others.
110512 **    May you share freely, never taking more than you give.
110513 **
110514 ******************************************************************************
110515 **
110516 ** This is part of an SQLite module implementing full-text search.
110517 ** This particular file implements the generic tokenizer interface.
110518 */
110519
110520 /*
110521 ** The code in this file is only compiled if:
110522 **
110523 **     * The FTS3 module is being built as an extension
110524 **       (in which case SQLITE_CORE is not defined), or
110525 **
110526 **     * The FTS3 module is being built into the core of
110527 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
110528 */
110529 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
110530
110531 #ifndef SQLITE_CORE
110532   SQLITE_EXTENSION_INIT1
110533 #endif
110534
110535
110536 /*
110537 ** Implementation of the SQL scalar function for accessing the underlying 
110538 ** hash table. This function may be called as follows:
110539 **
110540 **   SELECT <function-name>(<key-name>);
110541 **   SELECT <function-name>(<key-name>, <pointer>);
110542 **
110543 ** where <function-name> is the name passed as the second argument
110544 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
110545 **
110546 ** If the <pointer> argument is specified, it must be a blob value
110547 ** containing a pointer to be stored as the hash data corresponding
110548 ** to the string <key-name>. If <pointer> is not specified, then
110549 ** the string <key-name> must already exist in the has table. Otherwise,
110550 ** an error is returned.
110551 **
110552 ** Whether or not the <pointer> argument is specified, the value returned
110553 ** is a blob containing the pointer stored as the hash data corresponding
110554 ** to string <key-name> (after the hash-table is updated, if applicable).
110555 */
110556 static void scalarFunc(
110557   sqlite3_context *context,
110558   int argc,
110559   sqlite3_value **argv
110560 ){
110561   Fts3Hash *pHash;
110562   void *pPtr = 0;
110563   const unsigned char *zName;
110564   int nName;
110565
110566   assert( argc==1 || argc==2 );
110567
110568   pHash = (Fts3Hash *)sqlite3_user_data(context);
110569
110570   zName = sqlite3_value_text(argv[0]);
110571   nName = sqlite3_value_bytes(argv[0])+1;
110572
110573   if( argc==2 ){
110574     void *pOld;
110575     int n = sqlite3_value_bytes(argv[1]);
110576     if( n!=sizeof(pPtr) ){
110577       sqlite3_result_error(context, "argument type mismatch", -1);
110578       return;
110579     }
110580     pPtr = *(void **)sqlite3_value_blob(argv[1]);
110581     pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
110582     if( pOld==pPtr ){
110583       sqlite3_result_error(context, "out of memory", -1);
110584       return;
110585     }
110586   }else{
110587     pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
110588     if( !pPtr ){
110589       char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
110590       sqlite3_result_error(context, zErr, -1);
110591       sqlite3_free(zErr);
110592       return;
110593     }
110594   }
110595
110596   sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
110597 }
110598
110599 static int fts3IsIdChar(char c){
110600   static const char isFtsIdChar[] = {
110601       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
110602       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
110603       0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
110604       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
110605       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
110606       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
110607       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
110608       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
110609   };
110610   return (c&0x80 || isFtsIdChar[(int)(c)]);
110611 }
110612
110613 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
110614   const char *z1;
110615   const char *z2 = 0;
110616
110617   /* Find the start of the next token. */
110618   z1 = zStr;
110619   while( z2==0 ){
110620     char c = *z1;
110621     switch( c ){
110622       case '\0': return 0;        /* No more tokens here */
110623       case '\'':
110624       case '"':
110625       case '`': {
110626         z2 = z1;
110627         while( *++z2 && (*z2!=c || *++z2==c) );
110628         break;
110629       }
110630       case '[':
110631         z2 = &z1[1];
110632         while( *z2 && z2[0]!=']' ) z2++;
110633         if( *z2 ) z2++;
110634         break;
110635
110636       default:
110637         if( fts3IsIdChar(*z1) ){
110638           z2 = &z1[1];
110639           while( fts3IsIdChar(*z2) ) z2++;
110640         }else{
110641           z1++;
110642         }
110643     }
110644   }
110645
110646   *pn = (int)(z2-z1);
110647   return z1;
110648 }
110649
110650 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
110651   Fts3Hash *pHash,                /* Tokenizer hash table */
110652   const char *zArg,               /* Possible tokenizer specification */
110653   sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
110654   const char **pzTokenizer,       /* OUT: Set to zArg if is tokenizer */
110655   char **pzErr                    /* OUT: Set to malloced error message */
110656 ){
110657   int rc;
110658   char *z = (char *)zArg;
110659   int n;
110660   char *zCopy;
110661   char *zEnd;                     /* Pointer to nul-term of zCopy */
110662   sqlite3_tokenizer_module *m;
110663
110664   if( !z ){
110665     zCopy = sqlite3_mprintf("simple");
110666   }else{
110667     if( sqlite3_strnicmp(z, "tokenize", 8) || fts3IsIdChar(z[8])){
110668       return SQLITE_OK;
110669     }
110670     zCopy = sqlite3_mprintf("%s", &z[8]);
110671     *pzTokenizer = zArg;
110672   }
110673   if( !zCopy ){
110674     return SQLITE_NOMEM;
110675   }
110676
110677   zEnd = &zCopy[strlen(zCopy)];
110678
110679   z = (char *)sqlite3Fts3NextToken(zCopy, &n);
110680   z[n] = '\0';
110681   sqlite3Fts3Dequote(z);
110682
110683   m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, z, (int)strlen(z)+1);
110684   if( !m ){
110685     *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
110686     rc = SQLITE_ERROR;
110687   }else{
110688     char const **aArg = 0;
110689     int iArg = 0;
110690     z = &z[n+1];
110691     while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
110692       int nNew = sizeof(char *)*(iArg+1);
110693       char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
110694       if( !aNew ){
110695         sqlite3_free(zCopy);
110696         sqlite3_free((void *)aArg);
110697         return SQLITE_NOMEM;
110698       }
110699       aArg = aNew;
110700       aArg[iArg++] = z;
110701       z[n] = '\0';
110702       sqlite3Fts3Dequote(z);
110703       z = &z[n+1];
110704     }
110705     rc = m->xCreate(iArg, aArg, ppTok);
110706     assert( rc!=SQLITE_OK || *ppTok );
110707     if( rc!=SQLITE_OK ){
110708       *pzErr = sqlite3_mprintf("unknown tokenizer");
110709     }else{
110710       (*ppTok)->pModule = m; 
110711     }
110712     sqlite3_free((void *)aArg);
110713   }
110714
110715   sqlite3_free(zCopy);
110716   return rc;
110717 }
110718
110719
110720 #ifdef SQLITE_TEST
110721
110722
110723 /*
110724 ** Implementation of a special SQL scalar function for testing tokenizers 
110725 ** designed to be used in concert with the Tcl testing framework. This
110726 ** function must be called with two arguments:
110727 **
110728 **   SELECT <function-name>(<key-name>, <input-string>);
110729 **   SELECT <function-name>(<key-name>, <pointer>);
110730 **
110731 ** where <function-name> is the name passed as the second argument
110732 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
110733 ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
110734 **
110735 ** The return value is a string that may be interpreted as a Tcl
110736 ** list. For each token in the <input-string>, three elements are
110737 ** added to the returned list. The first is the token position, the 
110738 ** second is the token text (folded, stemmed, etc.) and the third is the
110739 ** substring of <input-string> associated with the token. For example, 
110740 ** using the built-in "simple" tokenizer:
110741 **
110742 **   SELECT fts_tokenizer_test('simple', 'I don't see how');
110743 **
110744 ** will return the string:
110745 **
110746 **   "{0 i I 1 dont don't 2 see see 3 how how}"
110747 **   
110748 */
110749 static void testFunc(
110750   sqlite3_context *context,
110751   int argc,
110752   sqlite3_value **argv
110753 ){
110754   Fts3Hash *pHash;
110755   sqlite3_tokenizer_module *p;
110756   sqlite3_tokenizer *pTokenizer = 0;
110757   sqlite3_tokenizer_cursor *pCsr = 0;
110758
110759   const char *zErr = 0;
110760
110761   const char *zName;
110762   int nName;
110763   const char *zInput;
110764   int nInput;
110765
110766   const char *zArg = 0;
110767
110768   const char *zToken;
110769   int nToken;
110770   int iStart;
110771   int iEnd;
110772   int iPos;
110773
110774   Tcl_Obj *pRet;
110775
110776   assert( argc==2 || argc==3 );
110777
110778   nName = sqlite3_value_bytes(argv[0]);
110779   zName = (const char *)sqlite3_value_text(argv[0]);
110780   nInput = sqlite3_value_bytes(argv[argc-1]);
110781   zInput = (const char *)sqlite3_value_text(argv[argc-1]);
110782
110783   if( argc==3 ){
110784     zArg = (const char *)sqlite3_value_text(argv[1]);
110785   }
110786
110787   pHash = (Fts3Hash *)sqlite3_user_data(context);
110788   p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
110789
110790   if( !p ){
110791     char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
110792     sqlite3_result_error(context, zErr, -1);
110793     sqlite3_free(zErr);
110794     return;
110795   }
110796
110797   pRet = Tcl_NewObj();
110798   Tcl_IncrRefCount(pRet);
110799
110800   if( SQLITE_OK!=p->xCreate(zArg ? 1 : 0, &zArg, &pTokenizer) ){
110801     zErr = "error in xCreate()";
110802     goto finish;
110803   }
110804   pTokenizer->pModule = p;
110805   if( SQLITE_OK!=p->xOpen(pTokenizer, zInput, nInput, &pCsr) ){
110806     zErr = "error in xOpen()";
110807     goto finish;
110808   }
110809   pCsr->pTokenizer = pTokenizer;
110810
110811   while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
110812     Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
110813     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
110814     zToken = &zInput[iStart];
110815     nToken = iEnd-iStart;
110816     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
110817   }
110818
110819   if( SQLITE_OK!=p->xClose(pCsr) ){
110820     zErr = "error in xClose()";
110821     goto finish;
110822   }
110823   if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
110824     zErr = "error in xDestroy()";
110825     goto finish;
110826   }
110827
110828 finish:
110829   if( zErr ){
110830     sqlite3_result_error(context, zErr, -1);
110831   }else{
110832     sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
110833   }
110834   Tcl_DecrRefCount(pRet);
110835 }
110836
110837 static
110838 int registerTokenizer(
110839   sqlite3 *db, 
110840   char *zName, 
110841   const sqlite3_tokenizer_module *p
110842 ){
110843   int rc;
110844   sqlite3_stmt *pStmt;
110845   const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
110846
110847   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
110848   if( rc!=SQLITE_OK ){
110849     return rc;
110850   }
110851
110852   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
110853   sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
110854   sqlite3_step(pStmt);
110855
110856   return sqlite3_finalize(pStmt);
110857 }
110858
110859 static
110860 int queryTokenizer(
110861   sqlite3 *db, 
110862   char *zName,  
110863   const sqlite3_tokenizer_module **pp
110864 ){
110865   int rc;
110866   sqlite3_stmt *pStmt;
110867   const char zSql[] = "SELECT fts3_tokenizer(?)";
110868
110869   *pp = 0;
110870   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
110871   if( rc!=SQLITE_OK ){
110872     return rc;
110873   }
110874
110875   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
110876   if( SQLITE_ROW==sqlite3_step(pStmt) ){
110877     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
110878       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
110879     }
110880   }
110881
110882   return sqlite3_finalize(pStmt);
110883 }
110884
110885 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
110886
110887 /*
110888 ** Implementation of the scalar function fts3_tokenizer_internal_test().
110889 ** This function is used for testing only, it is not included in the
110890 ** build unless SQLITE_TEST is defined.
110891 **
110892 ** The purpose of this is to test that the fts3_tokenizer() function
110893 ** can be used as designed by the C-code in the queryTokenizer and
110894 ** registerTokenizer() functions above. These two functions are repeated
110895 ** in the README.tokenizer file as an example, so it is important to
110896 ** test them.
110897 **
110898 ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
110899 ** function with no arguments. An assert() will fail if a problem is
110900 ** detected. i.e.:
110901 **
110902 **     SELECT fts3_tokenizer_internal_test();
110903 **
110904 */
110905 static void intTestFunc(
110906   sqlite3_context *context,
110907   int argc,
110908   sqlite3_value **argv
110909 ){
110910   int rc;
110911   const sqlite3_tokenizer_module *p1;
110912   const sqlite3_tokenizer_module *p2;
110913   sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
110914
110915   UNUSED_PARAMETER(argc);
110916   UNUSED_PARAMETER(argv);
110917
110918   /* Test the query function */
110919   sqlite3Fts3SimpleTokenizerModule(&p1);
110920   rc = queryTokenizer(db, "simple", &p2);
110921   assert( rc==SQLITE_OK );
110922   assert( p1==p2 );
110923   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
110924   assert( rc==SQLITE_ERROR );
110925   assert( p2==0 );
110926   assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
110927
110928   /* Test the storage function */
110929   rc = registerTokenizer(db, "nosuchtokenizer", p1);
110930   assert( rc==SQLITE_OK );
110931   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
110932   assert( rc==SQLITE_OK );
110933   assert( p2==p1 );
110934
110935   sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
110936 }
110937
110938 #endif
110939
110940 /*
110941 ** Set up SQL objects in database db used to access the contents of
110942 ** the hash table pointed to by argument pHash. The hash table must
110943 ** been initialised to use string keys, and to take a private copy 
110944 ** of the key when a value is inserted. i.e. by a call similar to:
110945 **
110946 **    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
110947 **
110948 ** This function adds a scalar function (see header comment above
110949 ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
110950 ** defined at compilation time, a temporary virtual table (see header 
110951 ** comment above struct HashTableVtab) to the database schema. Both 
110952 ** provide read/write access to the contents of *pHash.
110953 **
110954 ** The third argument to this function, zName, is used as the name
110955 ** of both the scalar and, if created, the virtual table.
110956 */
110957 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
110958   sqlite3 *db, 
110959   Fts3Hash *pHash, 
110960   const char *zName
110961 ){
110962   int rc = SQLITE_OK;
110963   void *p = (void *)pHash;
110964   const int any = SQLITE_ANY;
110965
110966 #ifdef SQLITE_TEST
110967   char *zTest = 0;
110968   char *zTest2 = 0;
110969   void *pdb = (void *)db;
110970   zTest = sqlite3_mprintf("%s_test", zName);
110971   zTest2 = sqlite3_mprintf("%s_internal_test", zName);
110972   if( !zTest || !zTest2 ){
110973     rc = SQLITE_NOMEM;
110974   }
110975 #endif
110976
110977   if( SQLITE_OK!=rc
110978    || SQLITE_OK!=(rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0))
110979    || SQLITE_OK!=(rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0))
110980 #ifdef SQLITE_TEST
110981    || SQLITE_OK!=(rc = sqlite3_create_function(db, zTest, 2, any, p, testFunc, 0, 0))
110982    || SQLITE_OK!=(rc = sqlite3_create_function(db, zTest, 3, any, p, testFunc, 0, 0))
110983    || SQLITE_OK!=(rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0))
110984 #endif
110985    );
110986
110987 #ifdef SQLITE_TEST
110988   sqlite3_free(zTest);
110989   sqlite3_free(zTest2);
110990 #endif
110991
110992   return rc;
110993 }
110994
110995 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
110996
110997 /************** End of fts3_tokenizer.c **************************************/
110998 /************** Begin file fts3_tokenizer1.c *********************************/
110999 /*
111000 ** 2006 Oct 10
111001 **
111002 ** The author disclaims copyright to this source code.  In place of
111003 ** a legal notice, here is a blessing:
111004 **
111005 **    May you do good and not evil.
111006 **    May you find forgiveness for yourself and forgive others.
111007 **    May you share freely, never taking more than you give.
111008 **
111009 ******************************************************************************
111010 **
111011 ** Implementation of the "simple" full-text-search tokenizer.
111012 */
111013
111014 /*
111015 ** The code in this file is only compiled if:
111016 **
111017 **     * The FTS3 module is being built as an extension
111018 **       (in which case SQLITE_CORE is not defined), or
111019 **
111020 **     * The FTS3 module is being built into the core of
111021 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
111022 */
111023 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
111024
111025
111026
111027
111028 typedef struct simple_tokenizer {
111029   sqlite3_tokenizer base;
111030   char delim[128];             /* flag ASCII delimiters */
111031 } simple_tokenizer;
111032
111033 typedef struct simple_tokenizer_cursor {
111034   sqlite3_tokenizer_cursor base;
111035   const char *pInput;          /* input we are tokenizing */
111036   int nBytes;                  /* size of the input */
111037   int iOffset;                 /* current position in pInput */
111038   int iToken;                  /* index of next token to be returned */
111039   char *pToken;                /* storage for current token */
111040   int nTokenAllocated;         /* space allocated to zToken buffer */
111041 } simple_tokenizer_cursor;
111042
111043
111044 static int simpleDelim(simple_tokenizer *t, unsigned char c){
111045   return c<0x80 && t->delim[c];
111046 }
111047
111048 /*
111049 ** Create a new tokenizer instance.
111050 */
111051 static int simpleCreate(
111052   int argc, const char * const *argv,
111053   sqlite3_tokenizer **ppTokenizer
111054 ){
111055   simple_tokenizer *t;
111056
111057   t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
111058   if( t==NULL ) return SQLITE_NOMEM;
111059   memset(t, 0, sizeof(*t));
111060
111061   /* TODO(shess) Delimiters need to remain the same from run to run,
111062   ** else we need to reindex.  One solution would be a meta-table to
111063   ** track such information in the database, then we'd only want this
111064   ** information on the initial create.
111065   */
111066   if( argc>1 ){
111067     int i, n = (int)strlen(argv[1]);
111068     for(i=0; i<n; i++){
111069       unsigned char ch = argv[1][i];
111070       /* We explicitly don't support UTF-8 delimiters for now. */
111071       if( ch>=0x80 ){
111072         sqlite3_free(t);
111073         return SQLITE_ERROR;
111074       }
111075       t->delim[ch] = 1;
111076     }
111077   } else {
111078     /* Mark non-alphanumeric ASCII characters as delimiters */
111079     int i;
111080     for(i=1; i<0x80; i++){
111081       t->delim[i] = !isalnum(i) ? -1 : 0;
111082     }
111083   }
111084
111085   *ppTokenizer = &t->base;
111086   return SQLITE_OK;
111087 }
111088
111089 /*
111090 ** Destroy a tokenizer
111091 */
111092 static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
111093   sqlite3_free(pTokenizer);
111094   return SQLITE_OK;
111095 }
111096
111097 /*
111098 ** Prepare to begin tokenizing a particular string.  The input
111099 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
111100 ** used to incrementally tokenize this string is returned in 
111101 ** *ppCursor.
111102 */
111103 static int simpleOpen(
111104   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
111105   const char *pInput, int nBytes,        /* String to be tokenized */
111106   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
111107 ){
111108   simple_tokenizer_cursor *c;
111109
111110   UNUSED_PARAMETER(pTokenizer);
111111
111112   c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
111113   if( c==NULL ) return SQLITE_NOMEM;
111114
111115   c->pInput = pInput;
111116   if( pInput==0 ){
111117     c->nBytes = 0;
111118   }else if( nBytes<0 ){
111119     c->nBytes = (int)strlen(pInput);
111120   }else{
111121     c->nBytes = nBytes;
111122   }
111123   c->iOffset = 0;                 /* start tokenizing at the beginning */
111124   c->iToken = 0;
111125   c->pToken = NULL;               /* no space allocated, yet. */
111126   c->nTokenAllocated = 0;
111127
111128   *ppCursor = &c->base;
111129   return SQLITE_OK;
111130 }
111131
111132 /*
111133 ** Close a tokenization cursor previously opened by a call to
111134 ** simpleOpen() above.
111135 */
111136 static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
111137   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
111138   sqlite3_free(c->pToken);
111139   sqlite3_free(c);
111140   return SQLITE_OK;
111141 }
111142
111143 /*
111144 ** Extract the next token from a tokenization cursor.  The cursor must
111145 ** have been opened by a prior call to simpleOpen().
111146 */
111147 static int simpleNext(
111148   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
111149   const char **ppToken,               /* OUT: *ppToken is the token text */
111150   int *pnBytes,                       /* OUT: Number of bytes in token */
111151   int *piStartOffset,                 /* OUT: Starting offset of token */
111152   int *piEndOffset,                   /* OUT: Ending offset of token */
111153   int *piPosition                     /* OUT: Position integer of token */
111154 ){
111155   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
111156   simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
111157   unsigned char *p = (unsigned char *)c->pInput;
111158
111159   while( c->iOffset<c->nBytes ){
111160     int iStartOffset;
111161
111162     /* Scan past delimiter characters */
111163     while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
111164       c->iOffset++;
111165     }
111166
111167     /* Count non-delimiter characters. */
111168     iStartOffset = c->iOffset;
111169     while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
111170       c->iOffset++;
111171     }
111172
111173     if( c->iOffset>iStartOffset ){
111174       int i, n = c->iOffset-iStartOffset;
111175       if( n>c->nTokenAllocated ){
111176         char *pNew;
111177         c->nTokenAllocated = n+20;
111178         pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
111179         if( !pNew ) return SQLITE_NOMEM;
111180         c->pToken = pNew;
111181       }
111182       for(i=0; i<n; i++){
111183         /* TODO(shess) This needs expansion to handle UTF-8
111184         ** case-insensitivity.
111185         */
111186         unsigned char ch = p[iStartOffset+i];
111187         c->pToken[i] = (char)(ch<0x80 ? tolower(ch) : ch);
111188       }
111189       *ppToken = c->pToken;
111190       *pnBytes = n;
111191       *piStartOffset = iStartOffset;
111192       *piEndOffset = c->iOffset;
111193       *piPosition = c->iToken++;
111194
111195       return SQLITE_OK;
111196     }
111197   }
111198   return SQLITE_DONE;
111199 }
111200
111201 /*
111202 ** The set of routines that implement the simple tokenizer
111203 */
111204 static const sqlite3_tokenizer_module simpleTokenizerModule = {
111205   0,
111206   simpleCreate,
111207   simpleDestroy,
111208   simpleOpen,
111209   simpleClose,
111210   simpleNext,
111211 };
111212
111213 /*
111214 ** Allocate a new simple tokenizer.  Return a pointer to the new
111215 ** tokenizer in *ppModule
111216 */
111217 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
111218   sqlite3_tokenizer_module const**ppModule
111219 ){
111220   *ppModule = &simpleTokenizerModule;
111221 }
111222
111223 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
111224
111225 /************** End of fts3_tokenizer1.c *************************************/
111226 /************** Begin file fts3_write.c **************************************/
111227 /*
111228 ** 2009 Oct 23
111229 **
111230 ** The author disclaims copyright to this source code.  In place of
111231 ** a legal notice, here is a blessing:
111232 **
111233 **    May you do good and not evil.
111234 **    May you find forgiveness for yourself and forgive others.
111235 **    May you share freely, never taking more than you give.
111236 **
111237 ******************************************************************************
111238 **
111239 ** This file is part of the SQLite FTS3 extension module. Specifically,
111240 ** this file contains code to insert, update and delete rows from FTS3
111241 ** tables. It also contains code to merge FTS3 b-tree segments. Some
111242 ** of the sub-routines used to merge segments are also used by the query 
111243 ** code in fts3.c.
111244 */
111245
111246 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
111247
111248
111249 typedef struct PendingList PendingList;
111250 typedef struct SegmentNode SegmentNode;
111251 typedef struct SegmentWriter SegmentWriter;
111252
111253 /*
111254 ** Data structure used while accumulating terms in the pending-terms hash
111255 ** table. The hash table entry maps from term (a string) to a malloc'd
111256 ** instance of this structure.
111257 */
111258 struct PendingList {
111259   int nData;
111260   char *aData;
111261   int nSpace;
111262   sqlite3_int64 iLastDocid;
111263   sqlite3_int64 iLastCol;
111264   sqlite3_int64 iLastPos;
111265 };
111266
111267 /*
111268 ** An instance of this structure is used to iterate through the terms on
111269 ** a contiguous set of segment b-tree leaf nodes. Although the details of
111270 ** this structure are only manipulated by code in this file, opaque handles
111271 ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
111272 ** terms when querying the full-text index. See functions:
111273 **
111274 **   sqlite3Fts3SegReaderNew()
111275 **   sqlite3Fts3SegReaderFree()
111276 **   sqlite3Fts3SegReaderIterate()
111277 **
111278 ** Methods used to manipulate Fts3SegReader structures:
111279 **
111280 **   fts3SegReaderNext()
111281 **   fts3SegReaderFirstDocid()
111282 **   fts3SegReaderNextDocid()
111283 */
111284 struct Fts3SegReader {
111285   int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
111286   sqlite3_int64 iStartBlock;
111287   sqlite3_int64 iEndBlock;
111288   sqlite3_stmt *pStmt;            /* SQL Statement to access leaf nodes */
111289   char *aNode;                    /* Pointer to node data (or NULL) */
111290   int nNode;                      /* Size of buffer at aNode (or 0) */
111291   int nTermAlloc;                 /* Allocated size of zTerm buffer */
111292   Fts3HashElem **ppNextElem;
111293
111294   /* Variables set by fts3SegReaderNext(). These may be read directly
111295   ** by the caller. They are valid from the time SegmentReaderNew() returns
111296   ** until SegmentReaderNext() returns something other than SQLITE_OK
111297   ** (i.e. SQLITE_DONE).
111298   */
111299   int nTerm;                      /* Number of bytes in current term */
111300   char *zTerm;                    /* Pointer to current term */
111301   char *aDoclist;                 /* Pointer to doclist of current entry */
111302   int nDoclist;                   /* Size of doclist in current entry */
111303
111304   /* The following variables are used to iterate through the current doclist */
111305   char *pOffsetList;
111306   sqlite3_int64 iDocid;
111307 };
111308
111309 #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
111310
111311 /*
111312 ** An instance of this structure is used to create a segment b-tree in the
111313 ** database. The internal details of this type are only accessed by the
111314 ** following functions:
111315 **
111316 **   fts3SegWriterAdd()
111317 **   fts3SegWriterFlush()
111318 **   fts3SegWriterFree()
111319 */
111320 struct SegmentWriter {
111321   SegmentNode *pTree;             /* Pointer to interior tree structure */
111322   sqlite3_int64 iFirst;           /* First slot in %_segments written */
111323   sqlite3_int64 iFree;            /* Next free slot in %_segments */
111324   char *zTerm;                    /* Pointer to previous term buffer */
111325   int nTerm;                      /* Number of bytes in zTerm */
111326   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
111327   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
111328   int nSize;                      /* Size of allocation at aData */
111329   int nData;                      /* Bytes of data in aData */
111330   char *aData;                    /* Pointer to block from malloc() */
111331 };
111332
111333 /*
111334 ** Type SegmentNode is used by the following three functions to create
111335 ** the interior part of the segment b+-tree structures (everything except
111336 ** the leaf nodes). These functions and type are only ever used by code
111337 ** within the fts3SegWriterXXX() family of functions described above.
111338 **
111339 **   fts3NodeAddTerm()
111340 **   fts3NodeWrite()
111341 **   fts3NodeFree()
111342 */
111343 struct SegmentNode {
111344   SegmentNode *pParent;           /* Parent node (or NULL for root node) */
111345   SegmentNode *pRight;            /* Pointer to right-sibling */
111346   SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
111347   int nEntry;                     /* Number of terms written to node so far */
111348   char *zTerm;                    /* Pointer to previous term buffer */
111349   int nTerm;                      /* Number of bytes in zTerm */
111350   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
111351   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
111352   int nData;                      /* Bytes of valid data so far */
111353   char *aData;                    /* Node data */
111354 };
111355
111356 /*
111357 ** Valid values for the second argument to fts3SqlStmt().
111358 */
111359 #define SQL_DELETE_CONTENT             0
111360 #define SQL_IS_EMPTY                   1
111361 #define SQL_DELETE_ALL_CONTENT         2 
111362 #define SQL_DELETE_ALL_SEGMENTS        3
111363 #define SQL_DELETE_ALL_SEGDIR          4
111364 #define SQL_DELETE_ALL_DOCSIZE         5
111365 #define SQL_DELETE_ALL_STAT            6
111366 #define SQL_SELECT_CONTENT_BY_ROWID    7
111367 #define SQL_NEXT_SEGMENT_INDEX         8
111368 #define SQL_INSERT_SEGMENTS            9
111369 #define SQL_NEXT_SEGMENTS_ID          10
111370 #define SQL_INSERT_SEGDIR             11
111371 #define SQL_SELECT_LEVEL              12
111372 #define SQL_SELECT_ALL_LEVEL          13
111373 #define SQL_SELECT_LEVEL_COUNT        14
111374 #define SQL_SELECT_SEGDIR_COUNT_MAX   15
111375 #define SQL_DELETE_SEGDIR_BY_LEVEL    16
111376 #define SQL_DELETE_SEGMENTS_RANGE     17
111377 #define SQL_CONTENT_INSERT            18
111378 #define SQL_GET_BLOCK                 19
111379 #define SQL_DELETE_DOCSIZE            20
111380 #define SQL_REPLACE_DOCSIZE           21
111381 #define SQL_SELECT_DOCSIZE            22
111382 #define SQL_SELECT_DOCTOTAL           23
111383 #define SQL_REPLACE_DOCTOTAL          24
111384
111385 /*
111386 ** This function is used to obtain an SQLite prepared statement handle
111387 ** for the statement identified by the second argument. If successful,
111388 ** *pp is set to the requested statement handle and SQLITE_OK returned.
111389 ** Otherwise, an SQLite error code is returned and *pp is set to 0.
111390 **
111391 ** If argument apVal is not NULL, then it must point to an array with
111392 ** at least as many entries as the requested statement has bound 
111393 ** parameters. The values are bound to the statements parameters before
111394 ** returning.
111395 */
111396 static int fts3SqlStmt(
111397   Fts3Table *p,                   /* Virtual table handle */
111398   int eStmt,                      /* One of the SQL_XXX constants above */
111399   sqlite3_stmt **pp,              /* OUT: Statement handle */
111400   sqlite3_value **apVal           /* Values to bind to statement */
111401 ){
111402   const char *azSql[] = {
111403 /* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
111404 /* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
111405 /* 2  */  "DELETE FROM %Q.'%q_content'",
111406 /* 3  */  "DELETE FROM %Q.'%q_segments'",
111407 /* 4  */  "DELETE FROM %Q.'%q_segdir'",
111408 /* 5  */  "DELETE FROM %Q.'%q_docsize'",
111409 /* 6  */  "DELETE FROM %Q.'%q_stat'",
111410 /* 7  */  "SELECT * FROM %Q.'%q_content' WHERE rowid=?",
111411 /* 8  */  "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
111412 /* 9  */  "INSERT INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
111413 /* 10 */  "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
111414 /* 11 */  "INSERT INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
111415
111416           /* Return segments in order from oldest to newest.*/ 
111417 /* 12 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
111418             "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
111419 /* 13 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
111420             "FROM %Q.'%q_segdir' ORDER BY level DESC, idx ASC",
111421
111422 /* 14 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
111423 /* 15 */  "SELECT count(*), max(level) FROM %Q.'%q_segdir'",
111424
111425 /* 16 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
111426 /* 17 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
111427 /* 18 */  "INSERT INTO %Q.'%q_content' VALUES(%z)",
111428 /* 19 */  "SELECT block FROM %Q.'%q_segments' WHERE blockid = ?",
111429 /* 20 */  "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
111430 /* 21 */  "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
111431 /* 22 */  "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
111432 /* 23 */  "SELECT value FROM %Q.'%q_stat' WHERE id=0",
111433 /* 24 */  "REPLACE INTO %Q.'%q_stat' VALUES(0,?)",
111434   };
111435   int rc = SQLITE_OK;
111436   sqlite3_stmt *pStmt;
111437
111438   assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
111439   assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
111440   
111441   pStmt = p->aStmt[eStmt];
111442   if( !pStmt ){
111443     char *zSql;
111444     if( eStmt==SQL_CONTENT_INSERT ){
111445       int i;                      /* Iterator variable */  
111446       char *zVarlist;             /* The "?, ?, ..." string */
111447       zVarlist = (char *)sqlite3_malloc(2*p->nColumn+2);
111448       if( !zVarlist ){
111449         *pp = 0;
111450         return SQLITE_NOMEM;
111451       }
111452       zVarlist[0] = '?';
111453       zVarlist[p->nColumn*2+1] = '\0';
111454       for(i=1; i<=p->nColumn; i++){
111455         zVarlist[i*2-1] = ',';
111456         zVarlist[i*2] = '?';
111457       }
111458       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, zVarlist);
111459     }else{
111460       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
111461     }
111462     if( !zSql ){
111463       rc = SQLITE_NOMEM;
111464     }else{
111465       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
111466       sqlite3_free(zSql);
111467       assert( rc==SQLITE_OK || pStmt==0 );
111468       p->aStmt[eStmt] = pStmt;
111469     }
111470   }
111471   if( apVal ){
111472     int i;
111473     int nParam = sqlite3_bind_parameter_count(pStmt);
111474     for(i=0; rc==SQLITE_OK && i<nParam; i++){
111475       rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
111476     }
111477   }
111478   *pp = pStmt;
111479   return rc;
111480 }
111481
111482 /*
111483 ** Similar to fts3SqlStmt(). Except, after binding the parameters in
111484 ** array apVal[] to the SQL statement identified by eStmt, the statement
111485 ** is executed.
111486 **
111487 ** Returns SQLITE_OK if the statement is successfully executed, or an
111488 ** SQLite error code otherwise.
111489 */
111490 static void fts3SqlExec(
111491   int *pRC,                /* Result code */
111492   Fts3Table *p,            /* The FTS3 table */
111493   int eStmt,               /* Index of statement to evaluate */
111494   sqlite3_value **apVal    /* Parameters to bind */
111495 ){
111496   sqlite3_stmt *pStmt;
111497   int rc;
111498   if( *pRC ) return;
111499   rc = fts3SqlStmt(p, eStmt, &pStmt, apVal); 
111500   if( rc==SQLITE_OK ){
111501     sqlite3_step(pStmt);
111502     rc = sqlite3_reset(pStmt);
111503   }
111504   *pRC = rc;
111505 }
111506
111507
111508 /*
111509 ** Read a single block from the %_segments table. If the specified block
111510 ** does not exist, return SQLITE_CORRUPT. If some other error (malloc, IO 
111511 ** etc.) occurs, return the appropriate SQLite error code.
111512 **
111513 ** Otherwise, if successful, set *pzBlock to point to a buffer containing
111514 ** the block read from the database, and *pnBlock to the size of the read
111515 ** block in bytes.
111516 **
111517 ** WARNING: The returned buffer is only valid until the next call to 
111518 ** sqlite3Fts3ReadBlock().
111519 */
111520 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
111521   Fts3Table *p,
111522   sqlite3_int64 iBlock,
111523   char const **pzBlock,
111524   int *pnBlock
111525 ){
111526   sqlite3_stmt *pStmt;
111527   int rc = fts3SqlStmt(p, SQL_GET_BLOCK, &pStmt, 0);
111528   if( rc!=SQLITE_OK ) return rc;
111529   sqlite3_reset(pStmt);
111530
111531   if( pzBlock ){
111532     sqlite3_bind_int64(pStmt, 1, iBlock);
111533     rc = sqlite3_step(pStmt); 
111534     if( rc!=SQLITE_ROW ){
111535       return (rc==SQLITE_DONE ? SQLITE_CORRUPT : rc);
111536     }
111537   
111538     *pnBlock = sqlite3_column_bytes(pStmt, 0);
111539     *pzBlock = (char *)sqlite3_column_blob(pStmt, 0);
111540     if( sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
111541       return SQLITE_CORRUPT;
111542     }
111543   }
111544   return SQLITE_OK;
111545 }
111546
111547 /*
111548 ** Set *ppStmt to a statement handle that may be used to iterate through
111549 ** all rows in the %_segdir table, from oldest to newest. If successful,
111550 ** return SQLITE_OK. If an error occurs while preparing the statement, 
111551 ** return an SQLite error code.
111552 **
111553 ** There is only ever one instance of this SQL statement compiled for
111554 ** each FTS3 table.
111555 **
111556 ** The statement returns the following columns from the %_segdir table:
111557 **
111558 **   0: idx
111559 **   1: start_block
111560 **   2: leaves_end_block
111561 **   3: end_block
111562 **   4: root
111563 */
111564 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table *p, sqlite3_stmt **ppStmt){
111565   return fts3SqlStmt(p, SQL_SELECT_ALL_LEVEL, ppStmt, 0);
111566 }
111567
111568
111569 /*
111570 ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
111571 ** if successful, or an SQLite error code otherwise.
111572 **
111573 ** This function also serves to allocate the PendingList structure itself.
111574 ** For example, to create a new PendingList structure containing two
111575 ** varints:
111576 **
111577 **   PendingList *p = 0;
111578 **   fts3PendingListAppendVarint(&p, 1);
111579 **   fts3PendingListAppendVarint(&p, 2);
111580 */
111581 static int fts3PendingListAppendVarint(
111582   PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
111583   sqlite3_int64 i                 /* Value to append to data */
111584 ){
111585   PendingList *p = *pp;
111586
111587   /* Allocate or grow the PendingList as required. */
111588   if( !p ){
111589     p = sqlite3_malloc(sizeof(*p) + 100);
111590     if( !p ){
111591       return SQLITE_NOMEM;
111592     }
111593     p->nSpace = 100;
111594     p->aData = (char *)&p[1];
111595     p->nData = 0;
111596   }
111597   else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
111598     int nNew = p->nSpace * 2;
111599     p = sqlite3_realloc(p, sizeof(*p) + nNew);
111600     if( !p ){
111601       sqlite3_free(*pp);
111602       *pp = 0;
111603       return SQLITE_NOMEM;
111604     }
111605     p->nSpace = nNew;
111606     p->aData = (char *)&p[1];
111607   }
111608
111609   /* Append the new serialized varint to the end of the list. */
111610   p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
111611   p->aData[p->nData] = '\0';
111612   *pp = p;
111613   return SQLITE_OK;
111614 }
111615
111616 /*
111617 ** Add a docid/column/position entry to a PendingList structure. Non-zero
111618 ** is returned if the structure is sqlite3_realloced as part of adding
111619 ** the entry. Otherwise, zero.
111620 **
111621 ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
111622 ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
111623 ** it is set to SQLITE_OK.
111624 */
111625 static int fts3PendingListAppend(
111626   PendingList **pp,               /* IN/OUT: PendingList structure */
111627   sqlite3_int64 iDocid,           /* Docid for entry to add */
111628   sqlite3_int64 iCol,             /* Column for entry to add */
111629   sqlite3_int64 iPos,             /* Position of term for entry to add */
111630   int *pRc                        /* OUT: Return code */
111631 ){
111632   PendingList *p = *pp;
111633   int rc = SQLITE_OK;
111634
111635   assert( !p || p->iLastDocid<=iDocid );
111636
111637   if( !p || p->iLastDocid!=iDocid ){
111638     sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
111639     if( p ){
111640       assert( p->nData<p->nSpace );
111641       assert( p->aData[p->nData]==0 );
111642       p->nData++;
111643     }
111644     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
111645       goto pendinglistappend_out;
111646     }
111647     p->iLastCol = -1;
111648     p->iLastPos = 0;
111649     p->iLastDocid = iDocid;
111650   }
111651   if( iCol>0 && p->iLastCol!=iCol ){
111652     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
111653      || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
111654     ){
111655       goto pendinglistappend_out;
111656     }
111657     p->iLastCol = iCol;
111658     p->iLastPos = 0;
111659   }
111660   if( iCol>=0 ){
111661     assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
111662     rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
111663     if( rc==SQLITE_OK ){
111664       p->iLastPos = iPos;
111665     }
111666   }
111667
111668  pendinglistappend_out:
111669   *pRc = rc;
111670   if( p!=*pp ){
111671     *pp = p;
111672     return 1;
111673   }
111674   return 0;
111675 }
111676
111677 /*
111678 ** Tokenize the nul-terminated string zText and add all tokens to the
111679 ** pending-terms hash-table. The docid used is that currently stored in
111680 ** p->iPrevDocid, and the column is specified by argument iCol.
111681 **
111682 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
111683 */
111684 static int fts3PendingTermsAdd(
111685   Fts3Table *p,          /* FTS table into which text will be inserted */
111686   const char *zText,     /* Text of document to be inseted */
111687   int iCol,              /* Column number into which text is inserted */
111688   u32 *pnWord            /* OUT: Number of tokens inserted */
111689 ){
111690   int rc;
111691   int iStart;
111692   int iEnd;
111693   int iPos;
111694   int nWord = 0;
111695
111696   char const *zToken;
111697   int nToken;
111698
111699   sqlite3_tokenizer *pTokenizer = p->pTokenizer;
111700   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
111701   sqlite3_tokenizer_cursor *pCsr;
111702   int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
111703       const char**,int*,int*,int*,int*);
111704
111705   assert( pTokenizer && pModule );
111706
111707   rc = pModule->xOpen(pTokenizer, zText, -1, &pCsr);
111708   if( rc!=SQLITE_OK ){
111709     return rc;
111710   }
111711   pCsr->pTokenizer = pTokenizer;
111712
111713   xNext = pModule->xNext;
111714   while( SQLITE_OK==rc
111715       && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
111716   ){
111717     PendingList *pList;
111718  
111719     if( iPos>=nWord ) nWord = iPos+1;
111720
111721     /* Positions cannot be negative; we use -1 as a terminator internally.
111722     ** Tokens must have a non-zero length.
111723     */
111724     if( iPos<0 || !zToken || nToken<=0 ){
111725       rc = SQLITE_ERROR;
111726       break;
111727     }
111728
111729     pList = (PendingList *)fts3HashFind(&p->pendingTerms, zToken, nToken);
111730     if( pList ){
111731       p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
111732     }
111733     if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
111734       if( pList==fts3HashInsert(&p->pendingTerms, zToken, nToken, pList) ){
111735         /* Malloc failed while inserting the new entry. This can only 
111736         ** happen if there was no previous entry for this token.
111737         */
111738         assert( 0==fts3HashFind(&p->pendingTerms, zToken, nToken) );
111739         sqlite3_free(pList);
111740         rc = SQLITE_NOMEM;
111741       }
111742     }
111743     if( rc==SQLITE_OK ){
111744       p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
111745     }
111746   }
111747
111748   pModule->xClose(pCsr);
111749   *pnWord = nWord;
111750   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
111751 }
111752
111753 /* 
111754 ** Calling this function indicates that subsequent calls to 
111755 ** fts3PendingTermsAdd() are to add term/position-list pairs for the
111756 ** contents of the document with docid iDocid.
111757 */
111758 static int fts3PendingTermsDocid(Fts3Table *p, sqlite_int64 iDocid){
111759   /* TODO(shess) Explore whether partially flushing the buffer on
111760   ** forced-flush would provide better performance.  I suspect that if
111761   ** we ordered the doclists by size and flushed the largest until the
111762   ** buffer was half empty, that would let the less frequent terms
111763   ** generate longer doclists.
111764   */
111765   if( iDocid<=p->iPrevDocid || p->nPendingData>p->nMaxPendingData ){
111766     int rc = sqlite3Fts3PendingTermsFlush(p);
111767     if( rc!=SQLITE_OK ) return rc;
111768   }
111769   p->iPrevDocid = iDocid;
111770   return SQLITE_OK;
111771 }
111772
111773 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
111774   Fts3HashElem *pElem;
111775   for(pElem=fts3HashFirst(&p->pendingTerms); pElem; pElem=fts3HashNext(pElem)){
111776     sqlite3_free(fts3HashData(pElem));
111777   }
111778   fts3HashClear(&p->pendingTerms);
111779   p->nPendingData = 0;
111780 }
111781
111782 /*
111783 ** This function is called by the xUpdate() method as part of an INSERT
111784 ** operation. It adds entries for each term in the new record to the
111785 ** pendingTerms hash table.
111786 **
111787 ** Argument apVal is the same as the similarly named argument passed to
111788 ** fts3InsertData(). Parameter iDocid is the docid of the new row.
111789 */
111790 static int fts3InsertTerms(Fts3Table *p, sqlite3_value **apVal, u32 *aSz){
111791   int i;                          /* Iterator variable */
111792   for(i=2; i<p->nColumn+2; i++){
111793     const char *zText = (const char *)sqlite3_value_text(apVal[i]);
111794     if( zText ){
111795       int rc = fts3PendingTermsAdd(p, zText, i-2, &aSz[i-2]);
111796       if( rc!=SQLITE_OK ){
111797         return rc;
111798       }
111799     }
111800   }
111801   return SQLITE_OK;
111802 }
111803
111804 /*
111805 ** This function is called by the xUpdate() method for an INSERT operation.
111806 ** The apVal parameter is passed a copy of the apVal argument passed by
111807 ** SQLite to the xUpdate() method. i.e:
111808 **
111809 **   apVal[0]                Not used for INSERT.
111810 **   apVal[1]                rowid
111811 **   apVal[2]                Left-most user-defined column
111812 **   ...
111813 **   apVal[p->nColumn+1]     Right-most user-defined column
111814 **   apVal[p->nColumn+2]     Hidden column with same name as table
111815 **   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
111816 */
111817 static int fts3InsertData(
111818   Fts3Table *p,                   /* Full-text table */
111819   sqlite3_value **apVal,          /* Array of values to insert */
111820   sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
111821 ){
111822   int rc;                         /* Return code */
111823   sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
111824
111825   /* Locate the statement handle used to insert data into the %_content
111826   ** table. The SQL for this statement is:
111827   **
111828   **   INSERT INTO %_content VALUES(?, ?, ?, ...)
111829   **
111830   ** The statement features N '?' variables, where N is the number of user
111831   ** defined columns in the FTS3 table, plus one for the docid field.
111832   */
111833   rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
111834   if( rc!=SQLITE_OK ){
111835     return rc;
111836   }
111837
111838   /* There is a quirk here. The users INSERT statement may have specified
111839   ** a value for the "rowid" field, for the "docid" field, or for both.
111840   ** Which is a problem, since "rowid" and "docid" are aliases for the
111841   ** same value. For example:
111842   **
111843   **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
111844   **
111845   ** In FTS3, this is an error. It is an error to specify non-NULL values
111846   ** for both docid and some other rowid alias.
111847   */
111848   if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
111849     if( SQLITE_NULL==sqlite3_value_type(apVal[0])
111850      && SQLITE_NULL!=sqlite3_value_type(apVal[1])
111851     ){
111852       /* A rowid/docid conflict. */
111853       return SQLITE_ERROR;
111854     }
111855     rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
111856     if( rc!=SQLITE_OK ) return rc;
111857   }
111858
111859   /* Execute the statement to insert the record. Set *piDocid to the 
111860   ** new docid value. 
111861   */
111862   sqlite3_step(pContentInsert);
111863   rc = sqlite3_reset(pContentInsert);
111864
111865   *piDocid = sqlite3_last_insert_rowid(p->db);
111866   return rc;
111867 }
111868
111869
111870
111871 /*
111872 ** Remove all data from the FTS3 table. Clear the hash table containing
111873 ** pending terms.
111874 */
111875 static int fts3DeleteAll(Fts3Table *p){
111876   int rc = SQLITE_OK;             /* Return code */
111877
111878   /* Discard the contents of the pending-terms hash table. */
111879   sqlite3Fts3PendingTermsClear(p);
111880
111881   /* Delete everything from the %_content, %_segments and %_segdir tables. */
111882   fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
111883   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
111884   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
111885   if( p->bHasDocsize ){
111886     fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
111887     fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
111888   }
111889   return rc;
111890 }
111891
111892 /*
111893 ** The first element in the apVal[] array is assumed to contain the docid
111894 ** (an integer) of a row about to be deleted. Remove all terms from the
111895 ** full-text index.
111896 */
111897 static void fts3DeleteTerms(
111898   int *pRC,               /* Result code */
111899   Fts3Table *p,           /* The FTS table to delete from */
111900   sqlite3_value **apVal,  /* apVal[] contains the docid to be deleted */
111901   u32 *aSz                /* Sizes of deleted document written here */
111902 ){
111903   int rc;
111904   sqlite3_stmt *pSelect;
111905
111906   if( *pRC ) return;
111907   rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, apVal);
111908   if( rc==SQLITE_OK ){
111909     if( SQLITE_ROW==sqlite3_step(pSelect) ){
111910       int i;
111911       for(i=1; i<=p->nColumn; i++){
111912         const char *zText = (const char *)sqlite3_column_text(pSelect, i);
111913         rc = fts3PendingTermsAdd(p, zText, -1, &aSz[i-1]);
111914         if( rc!=SQLITE_OK ){
111915           sqlite3_reset(pSelect);
111916           *pRC = rc;
111917           return;
111918         }
111919       }
111920     }
111921     rc = sqlite3_reset(pSelect);
111922   }else{
111923     sqlite3_reset(pSelect);
111924   }
111925   *pRC = rc;
111926 }
111927
111928 /*
111929 ** Forward declaration to account for the circular dependency between
111930 ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
111931 */
111932 static int fts3SegmentMerge(Fts3Table *, int);
111933
111934 /* 
111935 ** This function allocates a new level iLevel index in the segdir table.
111936 ** Usually, indexes are allocated within a level sequentially starting
111937 ** with 0, so the allocated index is one greater than the value returned
111938 ** by:
111939 **
111940 **   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
111941 **
111942 ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
111943 ** level, they are merged into a single level (iLevel+1) segment and the 
111944 ** allocated index is 0.
111945 **
111946 ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
111947 ** returned. Otherwise, an SQLite error code is returned.
111948 */
111949 static int fts3AllocateSegdirIdx(Fts3Table *p, int iLevel, int *piIdx){
111950   int rc;                         /* Return Code */
111951   sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
111952   int iNext = 0;                  /* Result of query pNextIdx */
111953
111954   /* Set variable iNext to the next available segdir index at level iLevel. */
111955   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
111956   if( rc==SQLITE_OK ){
111957     sqlite3_bind_int(pNextIdx, 1, iLevel);
111958     if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
111959       iNext = sqlite3_column_int(pNextIdx, 0);
111960     }
111961     rc = sqlite3_reset(pNextIdx);
111962   }
111963
111964   if( rc==SQLITE_OK ){
111965     /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
111966     ** full, merge all segments in level iLevel into a single iLevel+1
111967     ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
111968     ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
111969     */
111970     if( iNext>=FTS3_MERGE_COUNT ){
111971       rc = fts3SegmentMerge(p, iLevel);
111972       *piIdx = 0;
111973     }else{
111974       *piIdx = iNext;
111975     }
111976   }
111977
111978   return rc;
111979 }
111980
111981 /*
111982 ** Move the iterator passed as the first argument to the next term in the
111983 ** segment. If successful, SQLITE_OK is returned. If there is no next term,
111984 ** SQLITE_DONE. Otherwise, an SQLite error code.
111985 */
111986 static int fts3SegReaderNext(Fts3SegReader *pReader){
111987   char *pNext;                    /* Cursor variable */
111988   int nPrefix;                    /* Number of bytes in term prefix */
111989   int nSuffix;                    /* Number of bytes in term suffix */
111990
111991   if( !pReader->aDoclist ){
111992     pNext = pReader->aNode;
111993   }else{
111994     pNext = &pReader->aDoclist[pReader->nDoclist];
111995   }
111996
111997   if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
111998     int rc;
111999     if( fts3SegReaderIsPending(pReader) ){
112000       Fts3HashElem *pElem = *(pReader->ppNextElem);
112001       if( pElem==0 ){
112002         pReader->aNode = 0;
112003       }else{
112004         PendingList *pList = (PendingList *)fts3HashData(pElem);
112005         pReader->zTerm = (char *)fts3HashKey(pElem);
112006         pReader->nTerm = fts3HashKeysize(pElem);
112007         pReader->nNode = pReader->nDoclist = pList->nData + 1;
112008         pReader->aNode = pReader->aDoclist = pList->aData;
112009         pReader->ppNextElem++;
112010         assert( pReader->aNode );
112011       }
112012       return SQLITE_OK;
112013     }
112014     if( !pReader->pStmt ){
112015       pReader->aNode = 0;
112016       return SQLITE_OK;
112017     }
112018     rc = sqlite3_step(pReader->pStmt);
112019     if( rc!=SQLITE_ROW ){
112020       pReader->aNode = 0;
112021       return (rc==SQLITE_DONE ? SQLITE_OK : rc);
112022     }
112023     pReader->nNode = sqlite3_column_bytes(pReader->pStmt, 0);
112024     pReader->aNode = (char *)sqlite3_column_blob(pReader->pStmt, 0);
112025     pNext = pReader->aNode;
112026   }
112027   
112028   pNext += sqlite3Fts3GetVarint32(pNext, &nPrefix);
112029   pNext += sqlite3Fts3GetVarint32(pNext, &nSuffix);
112030
112031   if( nPrefix+nSuffix>pReader->nTermAlloc ){
112032     int nNew = (nPrefix+nSuffix)*2;
112033     char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
112034     if( !zNew ){
112035       return SQLITE_NOMEM;
112036     }
112037     pReader->zTerm = zNew;
112038     pReader->nTermAlloc = nNew;
112039   }
112040   memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
112041   pReader->nTerm = nPrefix+nSuffix;
112042   pNext += nSuffix;
112043   pNext += sqlite3Fts3GetVarint32(pNext, &pReader->nDoclist);
112044   assert( pNext<&pReader->aNode[pReader->nNode] );
112045   pReader->aDoclist = pNext;
112046   pReader->pOffsetList = 0;
112047   return SQLITE_OK;
112048 }
112049
112050 /*
112051 ** Set the SegReader to point to the first docid in the doclist associated
112052 ** with the current term.
112053 */
112054 static void fts3SegReaderFirstDocid(Fts3SegReader *pReader){
112055   int n;
112056   assert( pReader->aDoclist );
112057   assert( !pReader->pOffsetList );
112058   n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
112059   pReader->pOffsetList = &pReader->aDoclist[n];
112060 }
112061
112062 /*
112063 ** Advance the SegReader to point to the next docid in the doclist
112064 ** associated with the current term.
112065 ** 
112066 ** If arguments ppOffsetList and pnOffsetList are not NULL, then 
112067 ** *ppOffsetList is set to point to the first column-offset list
112068 ** in the doclist entry (i.e. immediately past the docid varint).
112069 ** *pnOffsetList is set to the length of the set of column-offset
112070 ** lists, not including the nul-terminator byte. For example:
112071 */
112072 static void fts3SegReaderNextDocid(
112073   Fts3SegReader *pReader,
112074   char **ppOffsetList,
112075   int *pnOffsetList
112076 ){
112077   char *p = pReader->pOffsetList;
112078   char c = 0;
112079
112080   /* Pointer p currently points at the first byte of an offset list. The
112081   ** following two lines advance it to point one byte past the end of
112082   ** the same offset list.
112083   */
112084   while( *p | c ) c = *p++ & 0x80;
112085   p++;
112086
112087   /* If required, populate the output variables with a pointer to and the
112088   ** size of the previous offset-list.
112089   */
112090   if( ppOffsetList ){
112091     *ppOffsetList = pReader->pOffsetList;
112092     *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
112093   }
112094
112095   /* If there are no more entries in the doclist, set pOffsetList to
112096   ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
112097   ** Fts3SegReader.pOffsetList to point to the next offset list before
112098   ** returning.
112099   */
112100   if( p>=&pReader->aDoclist[pReader->nDoclist] ){
112101     pReader->pOffsetList = 0;
112102   }else{
112103     sqlite3_int64 iDelta;
112104     pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
112105     pReader->iDocid += iDelta;
112106   }
112107 }
112108
112109 /*
112110 ** Free all allocations associated with the iterator passed as the 
112111 ** second argument.
112112 */
112113 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3Table *p, Fts3SegReader *pReader){
112114   if( pReader ){
112115     if( pReader->pStmt ){
112116       /* Move the leaf-range SELECT statement to the aLeavesStmt[] array,
112117       ** so that it can be reused when required by another query.
112118       */
112119       assert( p->nLeavesStmt<p->nLeavesTotal );
112120       sqlite3_reset(pReader->pStmt);
112121       p->aLeavesStmt[p->nLeavesStmt++] = pReader->pStmt;
112122     }
112123     if( !fts3SegReaderIsPending(pReader) ){
112124       sqlite3_free(pReader->zTerm);
112125     }
112126     sqlite3_free(pReader);
112127   }
112128 }
112129
112130 /*
112131 ** Allocate a new SegReader object.
112132 */
112133 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
112134   Fts3Table *p,                   /* Virtual table handle */
112135   int iAge,                       /* Segment "age". */
112136   sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
112137   sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
112138   sqlite3_int64 iEndBlock,        /* Final block of segment */
112139   const char *zRoot,              /* Buffer containing root node */
112140   int nRoot,                      /* Size of buffer containing root node */
112141   Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
112142 ){
112143   int rc = SQLITE_OK;             /* Return code */
112144   Fts3SegReader *pReader;         /* Newly allocated SegReader object */
112145   int nExtra = 0;                 /* Bytes to allocate segment root node */
112146
112147   if( iStartLeaf==0 ){
112148     nExtra = nRoot;
112149   }
112150
112151   pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
112152   if( !pReader ){
112153     return SQLITE_NOMEM;
112154   }
112155   memset(pReader, 0, sizeof(Fts3SegReader));
112156   pReader->iStartBlock = iStartLeaf;
112157   pReader->iIdx = iAge;
112158   pReader->iEndBlock = iEndBlock;
112159
112160   if( nExtra ){
112161     /* The entire segment is stored in the root node. */
112162     pReader->aNode = (char *)&pReader[1];
112163     pReader->nNode = nRoot;
112164     memcpy(pReader->aNode, zRoot, nRoot);
112165   }else{
112166     /* If the text of the SQL statement to iterate through a contiguous
112167     ** set of entries in the %_segments table has not yet been composed,
112168     ** compose it now.
112169     */
112170     if( !p->zSelectLeaves ){
112171       p->zSelectLeaves = sqlite3_mprintf(
112172           "SELECT block FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ? "
112173           "ORDER BY blockid", p->zDb, p->zName
112174       );
112175       if( !p->zSelectLeaves ){
112176         rc = SQLITE_NOMEM;
112177         goto finished;
112178       }
112179     }
112180
112181     /* If there are no free statements in the aLeavesStmt[] array, prepare
112182     ** a new statement now. Otherwise, reuse a prepared statement from
112183     ** aLeavesStmt[].
112184     */
112185     if( p->nLeavesStmt==0 ){
112186       if( p->nLeavesTotal==p->nLeavesAlloc ){
112187         int nNew = p->nLeavesAlloc + 16;
112188         sqlite3_stmt **aNew = (sqlite3_stmt **)sqlite3_realloc(
112189             p->aLeavesStmt, nNew*sizeof(sqlite3_stmt *)
112190         );
112191         if( !aNew ){
112192           rc = SQLITE_NOMEM;
112193           goto finished;
112194         }
112195         p->nLeavesAlloc = nNew;
112196         p->aLeavesStmt = aNew;
112197       }
112198       rc = sqlite3_prepare_v2(p->db, p->zSelectLeaves, -1, &pReader->pStmt, 0);
112199       if( rc!=SQLITE_OK ){
112200         goto finished;
112201       }
112202       p->nLeavesTotal++;
112203     }else{
112204       pReader->pStmt = p->aLeavesStmt[--p->nLeavesStmt];
112205     }
112206
112207     /* Bind the start and end leaf blockids to the prepared SQL statement. */
112208     sqlite3_bind_int64(pReader->pStmt, 1, iStartLeaf);
112209     sqlite3_bind_int64(pReader->pStmt, 2, iEndLeaf);
112210   }
112211   rc = fts3SegReaderNext(pReader);
112212
112213  finished:
112214   if( rc==SQLITE_OK ){
112215     *ppReader = pReader;
112216   }else{
112217     sqlite3Fts3SegReaderFree(p, pReader);
112218   }
112219   return rc;
112220 }
112221
112222 /*
112223 ** This is a comparison function used as a qsort() callback when sorting
112224 ** an array of pending terms by term. This occurs as part of flushing
112225 ** the contents of the pending-terms hash table to the database.
112226 */
112227 static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
112228   char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
112229   char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
112230   int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
112231   int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
112232
112233   int n = (n1<n2 ? n1 : n2);
112234   int c = memcmp(z1, z2, n);
112235   if( c==0 ){
112236     c = n1 - n2;
112237   }
112238   return c;
112239 }
112240
112241 /*
112242 ** This function is used to allocate an Fts3SegReader that iterates through
112243 ** a subset of the terms stored in the Fts3Table.pendingTerms array.
112244 */
112245 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
112246   Fts3Table *p,                   /* Virtual table handle */
112247   const char *zTerm,              /* Term to search for */
112248   int nTerm,                      /* Size of buffer zTerm */
112249   int isPrefix,                   /* True for a term-prefix query */
112250   Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
112251 ){
112252   Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
112253   Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
112254   int nElem = 0;                  /* Size of array at aElem */
112255   int rc = SQLITE_OK;             /* Return Code */
112256
112257   if( isPrefix ){
112258     int nAlloc = 0;               /* Size of allocated array at aElem */
112259     Fts3HashElem *pE = 0;         /* Iterator variable */
112260
112261     for(pE=fts3HashFirst(&p->pendingTerms); pE; pE=fts3HashNext(pE)){
112262       char *zKey = (char *)fts3HashKey(pE);
112263       int nKey = fts3HashKeysize(pE);
112264       if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
112265         if( nElem==nAlloc ){
112266           Fts3HashElem **aElem2;
112267           nAlloc += 16;
112268           aElem2 = (Fts3HashElem **)sqlite3_realloc(
112269               aElem, nAlloc*sizeof(Fts3HashElem *)
112270           );
112271           if( !aElem2 ){
112272             rc = SQLITE_NOMEM;
112273             nElem = 0;
112274             break;
112275           }
112276           aElem = aElem2;
112277         }
112278         aElem[nElem++] = pE;
112279       }
112280     }
112281
112282     /* If more than one term matches the prefix, sort the Fts3HashElem
112283     ** objects in term order using qsort(). This uses the same comparison
112284     ** callback as is used when flushing terms to disk.
112285     */
112286     if( nElem>1 ){
112287       qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
112288     }
112289
112290   }else{
112291     Fts3HashElem *pE = fts3HashFindElem(&p->pendingTerms, zTerm, nTerm);
112292     if( pE ){
112293       aElem = &pE;
112294       nElem = 1;
112295     }
112296   }
112297
112298   if( nElem>0 ){
112299     int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
112300     pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
112301     if( !pReader ){
112302       rc = SQLITE_NOMEM;
112303     }else{
112304       memset(pReader, 0, nByte);
112305       pReader->iIdx = 0x7FFFFFFF;
112306       pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
112307       memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
112308       fts3SegReaderNext(pReader);
112309     }
112310   }
112311
112312   if( isPrefix ){
112313     sqlite3_free(aElem);
112314   }
112315   *ppReader = pReader;
112316   return rc;
112317 }
112318
112319
112320 /*
112321 ** The second argument to this function is expected to be a statement of
112322 ** the form:
112323 **
112324 **   SELECT 
112325 **     idx,                  -- col 0
112326 **     start_block,          -- col 1
112327 **     leaves_end_block,     -- col 2
112328 **     end_block,            -- col 3
112329 **     root                  -- col 4
112330 **   FROM %_segdir ...
112331 **
112332 ** This function allocates and initializes a Fts3SegReader structure to
112333 ** iterate through the terms stored in the segment identified by the
112334 ** current row that pStmt is pointing to. 
112335 **
112336 ** If successful, the Fts3SegReader is left pointing to the first term
112337 ** in the segment and SQLITE_OK is returned. Otherwise, an SQLite error
112338 ** code is returned.
112339 */
112340 static int fts3SegReaderNew(
112341   Fts3Table *p,                   /* Virtual table handle */
112342   sqlite3_stmt *pStmt,            /* See above */
112343   int iAge,                       /* Segment "age". */
112344   Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
112345 ){
112346   return sqlite3Fts3SegReaderNew(p, iAge, 
112347       sqlite3_column_int64(pStmt, 1),
112348       sqlite3_column_int64(pStmt, 2),
112349       sqlite3_column_int64(pStmt, 3),
112350       sqlite3_column_blob(pStmt, 4),
112351       sqlite3_column_bytes(pStmt, 4),
112352       ppReader
112353   );
112354 }
112355
112356 /*
112357 ** Compare the entries pointed to by two Fts3SegReader structures. 
112358 ** Comparison is as follows:
112359 **
112360 **   1) EOF is greater than not EOF.
112361 **
112362 **   2) The current terms (if any) are compared using memcmp(). If one
112363 **      term is a prefix of another, the longer term is considered the
112364 **      larger.
112365 **
112366 **   3) By segment age. An older segment is considered larger.
112367 */
112368 static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
112369   int rc;
112370   if( pLhs->aNode && pRhs->aNode ){
112371     int rc2 = pLhs->nTerm - pRhs->nTerm;
112372     if( rc2<0 ){
112373       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
112374     }else{
112375       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
112376     }
112377     if( rc==0 ){
112378       rc = rc2;
112379     }
112380   }else{
112381     rc = (pLhs->aNode==0) - (pRhs->aNode==0);
112382   }
112383   if( rc==0 ){
112384     rc = pRhs->iIdx - pLhs->iIdx;
112385   }
112386   assert( rc!=0 );
112387   return rc;
112388 }
112389
112390 /*
112391 ** A different comparison function for SegReader structures. In this
112392 ** version, it is assumed that each SegReader points to an entry in
112393 ** a doclist for identical terms. Comparison is made as follows:
112394 **
112395 **   1) EOF (end of doclist in this case) is greater than not EOF.
112396 **
112397 **   2) By current docid.
112398 **
112399 **   3) By segment age. An older segment is considered larger.
112400 */
112401 static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
112402   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
112403   if( rc==0 ){
112404     if( pLhs->iDocid==pRhs->iDocid ){
112405       rc = pRhs->iIdx - pLhs->iIdx;
112406     }else{
112407       rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
112408     }
112409   }
112410   assert( pLhs->aNode && pRhs->aNode );
112411   return rc;
112412 }
112413
112414 /*
112415 ** Compare the term that the Fts3SegReader object passed as the first argument
112416 ** points to with the term specified by arguments zTerm and nTerm. 
112417 **
112418 ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
112419 ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
112420 ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
112421 */
112422 static int fts3SegReaderTermCmp(
112423   Fts3SegReader *pSeg,            /* Segment reader object */
112424   const char *zTerm,              /* Term to compare to */
112425   int nTerm                       /* Size of term zTerm in bytes */
112426 ){
112427   int res = 0;
112428   if( pSeg->aNode ){
112429     if( pSeg->nTerm>nTerm ){
112430       res = memcmp(pSeg->zTerm, zTerm, nTerm);
112431     }else{
112432       res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
112433     }
112434     if( res==0 ){
112435       res = pSeg->nTerm-nTerm;
112436     }
112437   }
112438   return res;
112439 }
112440
112441 /*
112442 ** Argument apSegment is an array of nSegment elements. It is known that
112443 ** the final (nSegment-nSuspect) members are already in sorted order
112444 ** (according to the comparison function provided). This function shuffles
112445 ** the array around until all entries are in sorted order.
112446 */
112447 static void fts3SegReaderSort(
112448   Fts3SegReader **apSegment,                     /* Array to sort entries of */
112449   int nSegment,                                  /* Size of apSegment array */
112450   int nSuspect,                                  /* Unsorted entry count */
112451   int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
112452 ){
112453   int i;                          /* Iterator variable */
112454
112455   assert( nSuspect<=nSegment );
112456
112457   if( nSuspect==nSegment ) nSuspect--;
112458   for(i=nSuspect-1; i>=0; i--){
112459     int j;
112460     for(j=i; j<(nSegment-1); j++){
112461       Fts3SegReader *pTmp;
112462       if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
112463       pTmp = apSegment[j+1];
112464       apSegment[j+1] = apSegment[j];
112465       apSegment[j] = pTmp;
112466     }
112467   }
112468
112469 #ifndef NDEBUG
112470   /* Check that the list really is sorted now. */
112471   for(i=0; i<(nSuspect-1); i++){
112472     assert( xCmp(apSegment[i], apSegment[i+1])<0 );
112473   }
112474 #endif
112475 }
112476
112477 /* 
112478 ** Insert a record into the %_segments table.
112479 */
112480 static int fts3WriteSegment(
112481   Fts3Table *p,                   /* Virtual table handle */
112482   sqlite3_int64 iBlock,           /* Block id for new block */
112483   char *z,                        /* Pointer to buffer containing block data */
112484   int n                           /* Size of buffer z in bytes */
112485 ){
112486   sqlite3_stmt *pStmt;
112487   int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
112488   if( rc==SQLITE_OK ){
112489     sqlite3_bind_int64(pStmt, 1, iBlock);
112490     sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
112491     sqlite3_step(pStmt);
112492     rc = sqlite3_reset(pStmt);
112493   }
112494   return rc;
112495 }
112496
112497 /* 
112498 ** Insert a record into the %_segdir table.
112499 */
112500 static int fts3WriteSegdir(
112501   Fts3Table *p,                   /* Virtual table handle */
112502   int iLevel,                     /* Value for "level" field */
112503   int iIdx,                       /* Value for "idx" field */
112504   sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
112505   sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
112506   sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
112507   char *zRoot,                    /* Blob value for "root" field */
112508   int nRoot                       /* Number of bytes in buffer zRoot */
112509 ){
112510   sqlite3_stmt *pStmt;
112511   int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
112512   if( rc==SQLITE_OK ){
112513     sqlite3_bind_int(pStmt, 1, iLevel);
112514     sqlite3_bind_int(pStmt, 2, iIdx);
112515     sqlite3_bind_int64(pStmt, 3, iStartBlock);
112516     sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
112517     sqlite3_bind_int64(pStmt, 5, iEndBlock);
112518     sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
112519     sqlite3_step(pStmt);
112520     rc = sqlite3_reset(pStmt);
112521   }
112522   return rc;
112523 }
112524
112525 /*
112526 ** Return the size of the common prefix (if any) shared by zPrev and
112527 ** zNext, in bytes. For example, 
112528 **
112529 **   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
112530 **   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
112531 **   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
112532 */
112533 static int fts3PrefixCompress(
112534   const char *zPrev,              /* Buffer containing previous term */
112535   int nPrev,                      /* Size of buffer zPrev in bytes */
112536   const char *zNext,              /* Buffer containing next term */
112537   int nNext                       /* Size of buffer zNext in bytes */
112538 ){
112539   int n;
112540   UNUSED_PARAMETER(nNext);
112541   for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
112542   return n;
112543 }
112544
112545 /*
112546 ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
112547 ** (according to memcmp) than the previous term.
112548 */
112549 static int fts3NodeAddTerm(
112550   Fts3Table *p,               /* Virtual table handle */
112551   SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */ 
112552   int isCopyTerm,                 /* True if zTerm/nTerm is transient */
112553   const char *zTerm,              /* Pointer to buffer containing term */
112554   int nTerm                       /* Size of term in bytes */
112555 ){
112556   SegmentNode *pTree = *ppTree;
112557   int rc;
112558   SegmentNode *pNew;
112559
112560   /* First try to append the term to the current node. Return early if 
112561   ** this is possible.
112562   */
112563   if( pTree ){
112564     int nData = pTree->nData;     /* Current size of node in bytes */
112565     int nReq = nData;             /* Required space after adding zTerm */
112566     int nPrefix;                  /* Number of bytes of prefix compression */
112567     int nSuffix;                  /* Suffix length */
112568
112569     nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
112570     nSuffix = nTerm-nPrefix;
112571
112572     nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
112573     if( nReq<=p->nNodeSize || !pTree->zTerm ){
112574
112575       if( nReq>p->nNodeSize ){
112576         /* An unusual case: this is the first term to be added to the node
112577         ** and the static node buffer (p->nNodeSize bytes) is not large
112578         ** enough. Use a separately malloced buffer instead This wastes
112579         ** p->nNodeSize bytes, but since this scenario only comes about when
112580         ** the database contain two terms that share a prefix of almost 2KB, 
112581         ** this is not expected to be a serious problem. 
112582         */
112583         assert( pTree->aData==(char *)&pTree[1] );
112584         pTree->aData = (char *)sqlite3_malloc(nReq);
112585         if( !pTree->aData ){
112586           return SQLITE_NOMEM;
112587         }
112588       }
112589
112590       if( pTree->zTerm ){
112591         /* There is no prefix-length field for first term in a node */
112592         nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
112593       }
112594
112595       nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
112596       memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
112597       pTree->nData = nData + nSuffix;
112598       pTree->nEntry++;
112599
112600       if( isCopyTerm ){
112601         if( pTree->nMalloc<nTerm ){
112602           char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
112603           if( !zNew ){
112604             return SQLITE_NOMEM;
112605           }
112606           pTree->nMalloc = nTerm*2;
112607           pTree->zMalloc = zNew;
112608         }
112609         pTree->zTerm = pTree->zMalloc;
112610         memcpy(pTree->zTerm, zTerm, nTerm);
112611         pTree->nTerm = nTerm;
112612       }else{
112613         pTree->zTerm = (char *)zTerm;
112614         pTree->nTerm = nTerm;
112615       }
112616       return SQLITE_OK;
112617     }
112618   }
112619
112620   /* If control flows to here, it was not possible to append zTerm to the
112621   ** current node. Create a new node (a right-sibling of the current node).
112622   ** If this is the first node in the tree, the term is added to it.
112623   **
112624   ** Otherwise, the term is not added to the new node, it is left empty for
112625   ** now. Instead, the term is inserted into the parent of pTree. If pTree 
112626   ** has no parent, one is created here.
112627   */
112628   pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
112629   if( !pNew ){
112630     return SQLITE_NOMEM;
112631   }
112632   memset(pNew, 0, sizeof(SegmentNode));
112633   pNew->nData = 1 + FTS3_VARINT_MAX;
112634   pNew->aData = (char *)&pNew[1];
112635
112636   if( pTree ){
112637     SegmentNode *pParent = pTree->pParent;
112638     rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
112639     if( pTree->pParent==0 ){
112640       pTree->pParent = pParent;
112641     }
112642     pTree->pRight = pNew;
112643     pNew->pLeftmost = pTree->pLeftmost;
112644     pNew->pParent = pParent;
112645     pNew->zMalloc = pTree->zMalloc;
112646     pNew->nMalloc = pTree->nMalloc;
112647     pTree->zMalloc = 0;
112648   }else{
112649     pNew->pLeftmost = pNew;
112650     rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm); 
112651   }
112652
112653   *ppTree = pNew;
112654   return rc;
112655 }
112656
112657 /*
112658 ** Helper function for fts3NodeWrite().
112659 */
112660 static int fts3TreeFinishNode(
112661   SegmentNode *pTree, 
112662   int iHeight, 
112663   sqlite3_int64 iLeftChild
112664 ){
112665   int nStart;
112666   assert( iHeight>=1 && iHeight<128 );
112667   nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
112668   pTree->aData[nStart] = (char)iHeight;
112669   sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
112670   return nStart;
112671 }
112672
112673 /*
112674 ** Write the buffer for the segment node pTree and all of its peers to the
112675 ** database. Then call this function recursively to write the parent of 
112676 ** pTree and its peers to the database. 
112677 **
112678 ** Except, if pTree is a root node, do not write it to the database. Instead,
112679 ** set output variables *paRoot and *pnRoot to contain the root node.
112680 **
112681 ** If successful, SQLITE_OK is returned and output variable *piLast is
112682 ** set to the largest blockid written to the database (or zero if no
112683 ** blocks were written to the db). Otherwise, an SQLite error code is 
112684 ** returned.
112685 */
112686 static int fts3NodeWrite(
112687   Fts3Table *p,                   /* Virtual table handle */
112688   SegmentNode *pTree,             /* SegmentNode handle */
112689   int iHeight,                    /* Height of this node in tree */
112690   sqlite3_int64 iLeaf,            /* Block id of first leaf node */
112691   sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
112692   sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
112693   char **paRoot,                  /* OUT: Data for root node */
112694   int *pnRoot                     /* OUT: Size of root node in bytes */
112695 ){
112696   int rc = SQLITE_OK;
112697
112698   if( !pTree->pParent ){
112699     /* Root node of the tree. */
112700     int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
112701     *piLast = iFree-1;
112702     *pnRoot = pTree->nData - nStart;
112703     *paRoot = &pTree->aData[nStart];
112704   }else{
112705     SegmentNode *pIter;
112706     sqlite3_int64 iNextFree = iFree;
112707     sqlite3_int64 iNextLeaf = iLeaf;
112708     for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
112709       int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
112710       int nWrite = pIter->nData - nStart;
112711   
112712       rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
112713       iNextFree++;
112714       iNextLeaf += (pIter->nEntry+1);
112715     }
112716     if( rc==SQLITE_OK ){
112717       assert( iNextLeaf==iFree );
112718       rc = fts3NodeWrite(
112719           p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
112720       );
112721     }
112722   }
112723
112724   return rc;
112725 }
112726
112727 /*
112728 ** Free all memory allocations associated with the tree pTree.
112729 */
112730 static void fts3NodeFree(SegmentNode *pTree){
112731   if( pTree ){
112732     SegmentNode *p = pTree->pLeftmost;
112733     fts3NodeFree(p->pParent);
112734     while( p ){
112735       SegmentNode *pRight = p->pRight;
112736       if( p->aData!=(char *)&p[1] ){
112737         sqlite3_free(p->aData);
112738       }
112739       assert( pRight==0 || p->zMalloc==0 );
112740       sqlite3_free(p->zMalloc);
112741       sqlite3_free(p);
112742       p = pRight;
112743     }
112744   }
112745 }
112746
112747 /*
112748 ** Add a term to the segment being constructed by the SegmentWriter object
112749 ** *ppWriter. When adding the first term to a segment, *ppWriter should
112750 ** be passed NULL. This function will allocate a new SegmentWriter object
112751 ** and return it via the input/output variable *ppWriter in this case.
112752 **
112753 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
112754 */
112755 static int fts3SegWriterAdd(
112756   Fts3Table *p,                   /* Virtual table handle */
112757   SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */ 
112758   int isCopyTerm,                 /* True if buffer zTerm must be copied */
112759   const char *zTerm,              /* Pointer to buffer containing term */
112760   int nTerm,                      /* Size of term in bytes */
112761   const char *aDoclist,           /* Pointer to buffer containing doclist */
112762   int nDoclist                    /* Size of doclist in bytes */
112763 ){
112764   int nPrefix;                    /* Size of term prefix in bytes */
112765   int nSuffix;                    /* Size of term suffix in bytes */
112766   int nReq;                       /* Number of bytes required on leaf page */
112767   int nData;
112768   SegmentWriter *pWriter = *ppWriter;
112769
112770   if( !pWriter ){
112771     int rc;
112772     sqlite3_stmt *pStmt;
112773
112774     /* Allocate the SegmentWriter structure */
112775     pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
112776     if( !pWriter ) return SQLITE_NOMEM;
112777     memset(pWriter, 0, sizeof(SegmentWriter));
112778     *ppWriter = pWriter;
112779
112780     /* Allocate a buffer in which to accumulate data */
112781     pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
112782     if( !pWriter->aData ) return SQLITE_NOMEM;
112783     pWriter->nSize = p->nNodeSize;
112784
112785     /* Find the next free blockid in the %_segments table */
112786     rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
112787     if( rc!=SQLITE_OK ) return rc;
112788     if( SQLITE_ROW==sqlite3_step(pStmt) ){
112789       pWriter->iFree = sqlite3_column_int64(pStmt, 0);
112790       pWriter->iFirst = pWriter->iFree;
112791     }
112792     rc = sqlite3_reset(pStmt);
112793     if( rc!=SQLITE_OK ) return rc;
112794   }
112795   nData = pWriter->nData;
112796
112797   nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
112798   nSuffix = nTerm-nPrefix;
112799
112800   /* Figure out how many bytes are required by this new entry */
112801   nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
112802     sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
112803     nSuffix +                               /* Term suffix */
112804     sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
112805     nDoclist;                               /* Doclist data */
112806
112807   if( nData>0 && nData+nReq>p->nNodeSize ){
112808     int rc;
112809
112810     /* The current leaf node is full. Write it out to the database. */
112811     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
112812     if( rc!=SQLITE_OK ) return rc;
112813
112814     /* Add the current term to the interior node tree. The term added to
112815     ** the interior tree must:
112816     **
112817     **   a) be greater than the largest term on the leaf node just written
112818     **      to the database (still available in pWriter->zTerm), and
112819     **
112820     **   b) be less than or equal to the term about to be added to the new
112821     **      leaf node (zTerm/nTerm).
112822     **
112823     ** In other words, it must be the prefix of zTerm 1 byte longer than
112824     ** the common prefix (if any) of zTerm and pWriter->zTerm.
112825     */
112826     assert( nPrefix<nTerm );
112827     rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
112828     if( rc!=SQLITE_OK ) return rc;
112829
112830     nData = 0;
112831     pWriter->nTerm = 0;
112832
112833     nPrefix = 0;
112834     nSuffix = nTerm;
112835     nReq = 1 +                              /* varint containing prefix size */
112836       sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
112837       nTerm +                               /* Term suffix */
112838       sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
112839       nDoclist;                             /* Doclist data */
112840   }
112841
112842   /* If the buffer currently allocated is too small for this entry, realloc
112843   ** the buffer to make it large enough.
112844   */
112845   if( nReq>pWriter->nSize ){
112846     char *aNew = sqlite3_realloc(pWriter->aData, nReq);
112847     if( !aNew ) return SQLITE_NOMEM;
112848     pWriter->aData = aNew;
112849     pWriter->nSize = nReq;
112850   }
112851   assert( nData+nReq<=pWriter->nSize );
112852
112853   /* Append the prefix-compressed term and doclist to the buffer. */
112854   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
112855   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
112856   memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
112857   nData += nSuffix;
112858   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
112859   memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
112860   pWriter->nData = nData + nDoclist;
112861
112862   /* Save the current term so that it can be used to prefix-compress the next.
112863   ** If the isCopyTerm parameter is true, then the buffer pointed to by
112864   ** zTerm is transient, so take a copy of the term data. Otherwise, just
112865   ** store a copy of the pointer.
112866   */
112867   if( isCopyTerm ){
112868     if( nTerm>pWriter->nMalloc ){
112869       char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
112870       if( !zNew ){
112871         return SQLITE_NOMEM;
112872       }
112873       pWriter->nMalloc = nTerm*2;
112874       pWriter->zMalloc = zNew;
112875       pWriter->zTerm = zNew;
112876     }
112877     assert( pWriter->zTerm==pWriter->zMalloc );
112878     memcpy(pWriter->zTerm, zTerm, nTerm);
112879   }else{
112880     pWriter->zTerm = (char *)zTerm;
112881   }
112882   pWriter->nTerm = nTerm;
112883
112884   return SQLITE_OK;
112885 }
112886
112887 /*
112888 ** Flush all data associated with the SegmentWriter object pWriter to the
112889 ** database. This function must be called after all terms have been added
112890 ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
112891 ** returned. Otherwise, an SQLite error code.
112892 */
112893 static int fts3SegWriterFlush(
112894   Fts3Table *p,                   /* Virtual table handle */
112895   SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
112896   int iLevel,                     /* Value for 'level' column of %_segdir */
112897   int iIdx                        /* Value for 'idx' column of %_segdir */
112898 ){
112899   int rc;                         /* Return code */
112900   if( pWriter->pTree ){
112901     sqlite3_int64 iLast = 0;      /* Largest block id written to database */
112902     sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
112903     char *zRoot = NULL;           /* Pointer to buffer containing root node */
112904     int nRoot = 0;                /* Size of buffer zRoot */
112905
112906     iLastLeaf = pWriter->iFree;
112907     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
112908     if( rc==SQLITE_OK ){
112909       rc = fts3NodeWrite(p, pWriter->pTree, 1,
112910           pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
112911     }
112912     if( rc==SQLITE_OK ){
112913       rc = fts3WriteSegdir(
112914           p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot);
112915     }
112916   }else{
112917     /* The entire tree fits on the root node. Write it to the segdir table. */
112918     rc = fts3WriteSegdir(
112919         p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData);
112920   }
112921   return rc;
112922 }
112923
112924 /*
112925 ** Release all memory held by the SegmentWriter object passed as the 
112926 ** first argument.
112927 */
112928 static void fts3SegWriterFree(SegmentWriter *pWriter){
112929   if( pWriter ){
112930     sqlite3_free(pWriter->aData);
112931     sqlite3_free(pWriter->zMalloc);
112932     fts3NodeFree(pWriter->pTree);
112933     sqlite3_free(pWriter);
112934   }
112935 }
112936
112937 /*
112938 ** The first value in the apVal[] array is assumed to contain an integer.
112939 ** This function tests if there exist any documents with docid values that
112940 ** are different from that integer. i.e. if deleting the document with docid
112941 ** apVal[0] would mean the FTS3 table were empty.
112942 **
112943 ** If successful, *pisEmpty is set to true if the table is empty except for
112944 ** document apVal[0], or false otherwise, and SQLITE_OK is returned. If an
112945 ** error occurs, an SQLite error code is returned.
112946 */
112947 static int fts3IsEmpty(Fts3Table *p, sqlite3_value **apVal, int *pisEmpty){
112948   sqlite3_stmt *pStmt;
112949   int rc;
112950   rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, apVal);
112951   if( rc==SQLITE_OK ){
112952     if( SQLITE_ROW==sqlite3_step(pStmt) ){
112953       *pisEmpty = sqlite3_column_int(pStmt, 0);
112954     }
112955     rc = sqlite3_reset(pStmt);
112956   }
112957   return rc;
112958 }
112959
112960 /*
112961 ** Set *pnSegment to the number of segments of level iLevel in the database.
112962 **
112963 ** Return SQLITE_OK if successful, or an SQLite error code if not.
112964 */
112965 static int fts3SegmentCount(Fts3Table *p, int iLevel, int *pnSegment){
112966   sqlite3_stmt *pStmt;
112967   int rc;
112968
112969   assert( iLevel>=0 );
112970   rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_COUNT, &pStmt, 0);
112971   if( rc!=SQLITE_OK ) return rc;
112972   sqlite3_bind_int(pStmt, 1, iLevel);
112973   if( SQLITE_ROW==sqlite3_step(pStmt) ){
112974     *pnSegment = sqlite3_column_int(pStmt, 0);
112975   }
112976   return sqlite3_reset(pStmt);
112977 }
112978
112979 /*
112980 ** Set *pnSegment to the total number of segments in the database. Set
112981 ** *pnMax to the largest segment level in the database (segment levels
112982 ** are stored in the 'level' column of the %_segdir table).
112983 **
112984 ** Return SQLITE_OK if successful, or an SQLite error code if not.
112985 */
112986 static int fts3SegmentCountMax(Fts3Table *p, int *pnSegment, int *pnMax){
112987   sqlite3_stmt *pStmt;
112988   int rc;
112989
112990   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_COUNT_MAX, &pStmt, 0);
112991   if( rc!=SQLITE_OK ) return rc;
112992   if( SQLITE_ROW==sqlite3_step(pStmt) ){
112993     *pnSegment = sqlite3_column_int(pStmt, 0);
112994     *pnMax = sqlite3_column_int(pStmt, 1);
112995   }
112996   return sqlite3_reset(pStmt);
112997 }
112998
112999 /*
113000 ** This function is used after merging multiple segments into a single large
113001 ** segment to delete the old, now redundant, segment b-trees. Specifically,
113002 ** it:
113003 ** 
113004 **   1) Deletes all %_segments entries for the segments associated with 
113005 **      each of the SegReader objects in the array passed as the third 
113006 **      argument, and
113007 **
113008 **   2) deletes all %_segdir entries with level iLevel, or all %_segdir
113009 **      entries regardless of level if (iLevel<0).
113010 **
113011 ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
113012 */
113013 static int fts3DeleteSegdir(
113014   Fts3Table *p,                   /* Virtual table handle */
113015   int iLevel,                     /* Level of %_segdir entries to delete */
113016   Fts3SegReader **apSegment,      /* Array of SegReader objects */
113017   int nReader                     /* Size of array apSegment */
113018 ){
113019   int rc;                         /* Return Code */
113020   int i;                          /* Iterator variable */
113021   sqlite3_stmt *pDelete;          /* SQL statement to delete rows */
113022
113023   rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
113024   for(i=0; rc==SQLITE_OK && i<nReader; i++){
113025     Fts3SegReader *pSegment = apSegment[i];
113026     if( pSegment->iStartBlock ){
113027       sqlite3_bind_int64(pDelete, 1, pSegment->iStartBlock);
113028       sqlite3_bind_int64(pDelete, 2, pSegment->iEndBlock);
113029       sqlite3_step(pDelete);
113030       rc = sqlite3_reset(pDelete);
113031     }
113032   }
113033   if( rc!=SQLITE_OK ){
113034     return rc;
113035   }
113036
113037   if( iLevel>=0 ){
113038     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_BY_LEVEL, &pDelete, 0);
113039     if( rc==SQLITE_OK ){
113040       sqlite3_bind_int(pDelete, 1, iLevel);
113041       sqlite3_step(pDelete);
113042       rc = sqlite3_reset(pDelete);
113043     }
113044   }else{
113045     fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
113046   }
113047
113048   return rc;
113049 }
113050
113051 /*
113052 ** When this function is called, buffer *ppList (size *pnList bytes) contains 
113053 ** a position list that may (or may not) feature multiple columns. This
113054 ** function adjusts the pointer *ppList and the length *pnList so that they
113055 ** identify the subset of the position list that corresponds to column iCol.
113056 **
113057 ** If there are no entries in the input position list for column iCol, then
113058 ** *pnList is set to zero before returning.
113059 */
113060 static void fts3ColumnFilter(
113061   int iCol,                       /* Column to filter on */
113062   char **ppList,                  /* IN/OUT: Pointer to position list */
113063   int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
113064 ){
113065   char *pList = *ppList;
113066   int nList = *pnList;
113067   char *pEnd = &pList[nList];
113068   int iCurrent = 0;
113069   char *p = pList;
113070
113071   assert( iCol>=0 );
113072   while( 1 ){
113073     char c = 0;
113074     while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
113075   
113076     if( iCol==iCurrent ){
113077       nList = (int)(p - pList);
113078       break;
113079     }
113080
113081     nList -= (int)(p - pList);
113082     pList = p;
113083     if( nList==0 ){
113084       break;
113085     }
113086     p = &pList[1];
113087     p += sqlite3Fts3GetVarint32(p, &iCurrent);
113088   }
113089
113090   *ppList = pList;
113091   *pnList = nList;
113092 }
113093
113094 /*
113095 ** sqlite3Fts3SegReaderIterate() callback used when merging multiple 
113096 ** segments to create a single, larger segment.
113097 */
113098 static int fts3MergeCallback(
113099   Fts3Table *p,                   /* FTS3 Virtual table handle */
113100   void *pContext,                 /* Pointer to SegmentWriter* to write with */
113101   char *zTerm,                    /* Term to write to the db */
113102   int nTerm,                      /* Number of bytes in zTerm */
113103   char *aDoclist,                 /* Doclist associated with zTerm */
113104   int nDoclist                    /* Number of bytes in doclist */
113105 ){
113106   SegmentWriter **ppW = (SegmentWriter **)pContext;
113107   return fts3SegWriterAdd(p, ppW, 1, zTerm, nTerm, aDoclist, nDoclist);
113108 }
113109
113110 /*
113111 ** sqlite3Fts3SegReaderIterate() callback used when flushing the contents
113112 ** of the pending-terms hash table to the database.
113113 */
113114 static int fts3FlushCallback(
113115   Fts3Table *p,                   /* FTS3 Virtual table handle */
113116   void *pContext,                 /* Pointer to SegmentWriter* to write with */
113117   char *zTerm,                    /* Term to write to the db */
113118   int nTerm,                      /* Number of bytes in zTerm */
113119   char *aDoclist,                 /* Doclist associated with zTerm */
113120   int nDoclist                    /* Number of bytes in doclist */
113121 ){
113122   SegmentWriter **ppW = (SegmentWriter **)pContext;
113123   return fts3SegWriterAdd(p, ppW, 0, zTerm, nTerm, aDoclist, nDoclist);
113124 }
113125
113126 /*
113127 ** This function is used to iterate through a contiguous set of terms 
113128 ** stored in the full-text index. It merges data contained in one or 
113129 ** more segments to support this.
113130 **
113131 ** The second argument is passed an array of pointers to SegReader objects
113132 ** allocated with sqlite3Fts3SegReaderNew(). This function merges the range 
113133 ** of terms selected by each SegReader. If a single term is present in
113134 ** more than one segment, the associated doclists are merged. For each
113135 ** term and (possibly merged) doclist in the merged range, the callback
113136 ** function xFunc is invoked with its arguments set as follows.
113137 **
113138 **   arg 0: Copy of 'p' parameter passed to this function
113139 **   arg 1: Copy of 'pContext' parameter passed to this function
113140 **   arg 2: Pointer to buffer containing term
113141 **   arg 3: Size of arg 2 buffer in bytes
113142 **   arg 4: Pointer to buffer containing doclist
113143 **   arg 5: Size of arg 2 buffer in bytes
113144 **
113145 ** The 4th argument to this function is a pointer to a structure of type
113146 ** Fts3SegFilter, defined in fts3Int.h. The contents of this structure
113147 ** further restrict the range of terms that callbacks are made for and
113148 ** modify the behaviour of this function. See comments above structure
113149 ** definition for details.
113150 */
113151 SQLITE_PRIVATE int sqlite3Fts3SegReaderIterate(
113152   Fts3Table *p,                   /* Virtual table handle */
113153   Fts3SegReader **apSegment,      /* Array of Fts3SegReader objects */
113154   int nSegment,                   /* Size of apSegment array */
113155   Fts3SegFilter *pFilter,         /* Restrictions on range of iteration */
113156   int (*xFunc)(Fts3Table *, void *, char *, int, char *, int),  /* Callback */
113157   void *pContext                  /* Callback context (2nd argument) */
113158 ){
113159   int i;                          /* Iterator variable */
113160   char *aBuffer = 0;              /* Buffer to merge doclists in */
113161   int nAlloc = 0;                 /* Allocated size of aBuffer buffer */
113162   int rc = SQLITE_OK;             /* Return code */
113163
113164   int isIgnoreEmpty =  (pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
113165   int isRequirePos =   (pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
113166   int isColFilter =    (pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
113167   int isPrefix =       (pFilter->flags & FTS3_SEGMENT_PREFIX);
113168
113169   /* If there are zero segments, this function is a no-op. This scenario
113170   ** comes about only when reading from an empty database.
113171   */
113172   if( nSegment==0 ) goto finished;
113173
113174   /* If the Fts3SegFilter defines a specific term (or term prefix) to search 
113175   ** for, then advance each segment iterator until it points to a term of
113176   ** equal or greater value than the specified term. This prevents many
113177   ** unnecessary merge/sort operations for the case where single segment
113178   ** b-tree leaf nodes contain more than one term.
113179   */
113180   if( pFilter->zTerm ){
113181     int nTerm = pFilter->nTerm;
113182     const char *zTerm = pFilter->zTerm;
113183     for(i=0; i<nSegment; i++){
113184       Fts3SegReader *pSeg = apSegment[i];
113185       while( fts3SegReaderTermCmp(pSeg, zTerm, nTerm)<0 ){
113186         rc = fts3SegReaderNext(pSeg);
113187         if( rc!=SQLITE_OK ) goto finished; }
113188     }
113189   }
113190
113191   fts3SegReaderSort(apSegment, nSegment, nSegment, fts3SegReaderCmp);
113192   while( apSegment[0]->aNode ){
113193     int nTerm = apSegment[0]->nTerm;
113194     char *zTerm = apSegment[0]->zTerm;
113195     int nMerge = 1;
113196
113197     /* If this is a prefix-search, and if the term that apSegment[0] points
113198     ** to does not share a suffix with pFilter->zTerm/nTerm, then all 
113199     ** required callbacks have been made. In this case exit early.
113200     **
113201     ** Similarly, if this is a search for an exact match, and the first term
113202     ** of segment apSegment[0] is not a match, exit early.
113203     */
113204     if( pFilter->zTerm ){
113205       if( nTerm<pFilter->nTerm 
113206        || (!isPrefix && nTerm>pFilter->nTerm)
113207        || memcmp(zTerm, pFilter->zTerm, pFilter->nTerm) 
113208     ){
113209         goto finished;
113210       }
113211     }
113212
113213     while( nMerge<nSegment 
113214         && apSegment[nMerge]->aNode
113215         && apSegment[nMerge]->nTerm==nTerm 
113216         && 0==memcmp(zTerm, apSegment[nMerge]->zTerm, nTerm)
113217     ){
113218       nMerge++;
113219     }
113220
113221     assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
113222     if( nMerge==1 && !isIgnoreEmpty ){
113223       Fts3SegReader *p0 = apSegment[0];
113224       rc = xFunc(p, pContext, zTerm, nTerm, p0->aDoclist, p0->nDoclist);
113225       if( rc!=SQLITE_OK ) goto finished;
113226     }else{
113227       int nDoclist = 0;           /* Size of doclist */
113228       sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
113229
113230       /* The current term of the first nMerge entries in the array
113231       ** of Fts3SegReader objects is the same. The doclists must be merged
113232       ** and a single term added to the new segment.
113233       */
113234       for(i=0; i<nMerge; i++){
113235         fts3SegReaderFirstDocid(apSegment[i]);
113236       }
113237       fts3SegReaderSort(apSegment, nMerge, nMerge, fts3SegReaderDoclistCmp);
113238       while( apSegment[0]->pOffsetList ){
113239         int j;                    /* Number of segments that share a docid */
113240         char *pList;
113241         int nList;
113242         int nByte;
113243         sqlite3_int64 iDocid = apSegment[0]->iDocid;
113244         fts3SegReaderNextDocid(apSegment[0], &pList, &nList);
113245         j = 1;
113246         while( j<nMerge
113247             && apSegment[j]->pOffsetList
113248             && apSegment[j]->iDocid==iDocid
113249         ){
113250           fts3SegReaderNextDocid(apSegment[j], 0, 0);
113251           j++;
113252         }
113253
113254         if( isColFilter ){
113255           fts3ColumnFilter(pFilter->iCol, &pList, &nList);
113256         }
113257
113258         if( !isIgnoreEmpty || nList>0 ){
113259           nByte = sqlite3Fts3VarintLen(iDocid-iPrev) + (isRequirePos?nList+1:0);
113260           if( nDoclist+nByte>nAlloc ){
113261             char *aNew;
113262             nAlloc = nDoclist+nByte*2;
113263             aNew = sqlite3_realloc(aBuffer, nAlloc);
113264             if( !aNew ){
113265               rc = SQLITE_NOMEM;
113266               goto finished;
113267             }
113268             aBuffer = aNew;
113269           }
113270           nDoclist += sqlite3Fts3PutVarint(&aBuffer[nDoclist], iDocid-iPrev);
113271           iPrev = iDocid;
113272           if( isRequirePos ){
113273             memcpy(&aBuffer[nDoclist], pList, nList);
113274             nDoclist += nList;
113275             aBuffer[nDoclist++] = '\0';
113276           }
113277         }
113278
113279         fts3SegReaderSort(apSegment, nMerge, j, fts3SegReaderDoclistCmp);
113280       }
113281
113282       if( nDoclist>0 ){
113283         rc = xFunc(p, pContext, zTerm, nTerm, aBuffer, nDoclist);
113284         if( rc!=SQLITE_OK ) goto finished;
113285       }
113286     }
113287
113288     /* If there is a term specified to filter on, and this is not a prefix
113289     ** search, return now. The callback that corresponds to the required
113290     ** term (if such a term exists in the index) has already been made.
113291     */
113292     if( pFilter->zTerm && !isPrefix ){
113293       goto finished;
113294     }
113295
113296     for(i=0; i<nMerge; i++){
113297       rc = fts3SegReaderNext(apSegment[i]);
113298       if( rc!=SQLITE_OK ) goto finished;
113299     }
113300     fts3SegReaderSort(apSegment, nSegment, nMerge, fts3SegReaderCmp);
113301   }
113302
113303  finished:
113304   sqlite3_free(aBuffer);
113305   return rc;
113306 }
113307
113308 /*
113309 ** Merge all level iLevel segments in the database into a single 
113310 ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
113311 ** single segment with a level equal to the numerically largest level 
113312 ** currently present in the database.
113313 **
113314 ** If this function is called with iLevel<0, but there is only one
113315 ** segment in the database, SQLITE_DONE is returned immediately. 
113316 ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs, 
113317 ** an SQLite error code is returned.
113318 */
113319 static int fts3SegmentMerge(Fts3Table *p, int iLevel){
113320   int i;                          /* Iterator variable */
113321   int rc;                         /* Return code */
113322   int iIdx;                       /* Index of new segment */
113323   int iNewLevel;                  /* Level to create new segment at */
113324   sqlite3_stmt *pStmt = 0;
113325   SegmentWriter *pWriter = 0;
113326   int nSegment = 0;               /* Number of segments being merged */
113327   Fts3SegReader **apSegment = 0;  /* Array of Segment iterators */
113328   Fts3SegReader *pPending = 0;    /* Iterator for pending-terms */
113329   Fts3SegFilter filter;           /* Segment term filter condition */
113330
113331   if( iLevel<0 ){
113332     /* This call is to merge all segments in the database to a single
113333     ** segment. The level of the new segment is equal to the the numerically 
113334     ** greatest segment level currently present in the database. The index
113335     ** of the new segment is always 0.
113336     */
113337     iIdx = 0;
113338     rc = sqlite3Fts3SegReaderPending(p, 0, 0, 1, &pPending);
113339     if( rc!=SQLITE_OK ) goto finished;
113340     rc = fts3SegmentCountMax(p, &nSegment, &iNewLevel);
113341     if( rc!=SQLITE_OK ) goto finished;
113342     nSegment += (pPending!=0);
113343     if( nSegment<=1 ){
113344       return SQLITE_DONE;
113345     }
113346   }else{
113347     /* This call is to merge all segments at level iLevel. Find the next
113348     ** available segment index at level iLevel+1. The call to
113349     ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to 
113350     ** a single iLevel+2 segment if necessary.
113351     */
113352     iNewLevel = iLevel+1;
113353     rc = fts3AllocateSegdirIdx(p, iNewLevel, &iIdx);
113354     if( rc!=SQLITE_OK ) goto finished;
113355     rc = fts3SegmentCount(p, iLevel, &nSegment);
113356     if( rc!=SQLITE_OK ) goto finished;
113357   }
113358   assert( nSegment>0 );
113359   assert( iNewLevel>=0 );
113360
113361   /* Allocate space for an array of pointers to segment iterators. */
113362   apSegment = (Fts3SegReader**)sqlite3_malloc(sizeof(Fts3SegReader *)*nSegment);
113363   if( !apSegment ){
113364     rc = SQLITE_NOMEM;
113365     goto finished;
113366   }
113367   memset(apSegment, 0, sizeof(Fts3SegReader *)*nSegment);
113368
113369   /* Allocate a Fts3SegReader structure for each segment being merged. A 
113370   ** Fts3SegReader stores the state data required to iterate through all 
113371   ** entries on all leaves of a single segment. 
113372   */
113373   assert( SQL_SELECT_LEVEL+1==SQL_SELECT_ALL_LEVEL);
113374   rc = fts3SqlStmt(p, SQL_SELECT_LEVEL+(iLevel<0), &pStmt, 0);
113375   if( rc!=SQLITE_OK ) goto finished;
113376   sqlite3_bind_int(pStmt, 1, iLevel);
113377   for(i=0; SQLITE_ROW==(sqlite3_step(pStmt)); i++){
113378     rc = fts3SegReaderNew(p, pStmt, i, &apSegment[i]);
113379     if( rc!=SQLITE_OK ){
113380       goto finished;
113381     }
113382   }
113383   rc = sqlite3_reset(pStmt);
113384   if( pPending ){
113385     apSegment[i] = pPending;
113386     pPending = 0;
113387   }
113388   pStmt = 0;
113389   if( rc!=SQLITE_OK ) goto finished;
113390
113391   memset(&filter, 0, sizeof(Fts3SegFilter));
113392   filter.flags = FTS3_SEGMENT_REQUIRE_POS;
113393   filter.flags |= (iLevel<0 ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
113394   rc = sqlite3Fts3SegReaderIterate(p, apSegment, nSegment,
113395       &filter, fts3MergeCallback, (void *)&pWriter
113396   );
113397   if( rc!=SQLITE_OK ) goto finished;
113398
113399   rc = fts3DeleteSegdir(p, iLevel, apSegment, nSegment);
113400   if( rc==SQLITE_OK ){
113401     rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
113402   }
113403
113404  finished:
113405   fts3SegWriterFree(pWriter);
113406   if( apSegment ){
113407     for(i=0; i<nSegment; i++){
113408       sqlite3Fts3SegReaderFree(p, apSegment[i]);
113409     }
113410     sqlite3_free(apSegment);
113411   }
113412   sqlite3Fts3SegReaderFree(p, pPending);
113413   sqlite3_reset(pStmt);
113414   return rc;
113415 }
113416
113417
113418 /* 
113419 ** Flush the contents of pendingTerms to a level 0 segment.
113420 */
113421 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
113422   int rc;                         /* Return Code */
113423   int idx;                        /* Index of new segment created */
113424   SegmentWriter *pWriter = 0;     /* Used to write the segment */
113425   Fts3SegReader *pReader = 0;     /* Used to iterate through the hash table */
113426
113427   /* Allocate a SegReader object to iterate through the contents of the
113428   ** pending-terms table. If an error occurs, or if there are no terms
113429   ** in the pending-terms table, return immediately.
113430   */
113431   rc = sqlite3Fts3SegReaderPending(p, 0, 0, 1, &pReader);
113432   if( rc!=SQLITE_OK || pReader==0 ){
113433     return rc;
113434   }
113435
113436   /* Determine the next index at level 0. If level 0 is already full, this
113437   ** call may merge all existing level 0 segments into a single level 1
113438   ** segment.
113439   */
113440   rc = fts3AllocateSegdirIdx(p, 0, &idx);
113441
113442   /* If no errors have occured, iterate through the contents of the 
113443   ** pending-terms hash table using the Fts3SegReader iterator. The callback
113444   ** writes each term (along with its doclist) to the database via the
113445   ** SegmentWriter handle pWriter.
113446   */
113447   if( rc==SQLITE_OK ){
113448     void *c = (void *)&pWriter;   /* SegReaderIterate() callback context */
113449     Fts3SegFilter f;              /* SegReaderIterate() parameters */
113450
113451     memset(&f, 0, sizeof(Fts3SegFilter));
113452     f.flags = FTS3_SEGMENT_REQUIRE_POS;
113453     rc = sqlite3Fts3SegReaderIterate(p, &pReader, 1, &f, fts3FlushCallback, c);
113454   }
113455   assert( pWriter || rc!=SQLITE_OK );
113456
113457   /* If no errors have occured, flush the SegmentWriter object to the
113458   ** database. Then delete the SegmentWriter and Fts3SegReader objects
113459   ** allocated by this function.
113460   */
113461   if( rc==SQLITE_OK ){
113462     rc = fts3SegWriterFlush(p, pWriter, 0, idx);
113463   }
113464   fts3SegWriterFree(pWriter);
113465   sqlite3Fts3SegReaderFree(p, pReader);
113466
113467   if( rc==SQLITE_OK ){
113468     sqlite3Fts3PendingTermsClear(p);
113469   }
113470   return rc;
113471 }
113472
113473 /*
113474 ** Encode N integers as varints into a blob.
113475 */
113476 static void fts3EncodeIntArray(
113477   int N,             /* The number of integers to encode */
113478   u32 *a,            /* The integer values */
113479   char *zBuf,        /* Write the BLOB here */
113480   int *pNBuf         /* Write number of bytes if zBuf[] used here */
113481 ){
113482   int i, j;
113483   for(i=j=0; i<N; i++){
113484     j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
113485   }
113486   *pNBuf = j;
113487 }
113488
113489 /*
113490 ** Decode a blob of varints into N integers
113491 */
113492 static void fts3DecodeIntArray(
113493   int N,             /* The number of integers to decode */
113494   u32 *a,            /* Write the integer values */
113495   const char *zBuf,  /* The BLOB containing the varints */
113496   int nBuf           /* size of the BLOB */
113497 ){
113498   int i, j;
113499   UNUSED_PARAMETER(nBuf);
113500   for(i=j=0; i<N; i++){
113501     sqlite3_int64 x;
113502     j += sqlite3Fts3GetVarint(&zBuf[j], &x);
113503     assert(j<=nBuf);
113504     a[i] = (u32)(x & 0xffffffff);
113505   }
113506 }
113507
113508 /*
113509 ** Fill in the document size auxiliary information for the matchinfo
113510 ** structure.  The auxiliary information is:
113511 **
113512 **    N     Total number of documents in the full-text index
113513 **    a0    Average length of column 0 over the whole index
113514 **    n0    Length of column 0 on the matching row
113515 **    ...
113516 **    aM    Average length of column M over the whole index
113517 **    nM    Length of column M on the matching row
113518 **
113519 ** The fts3MatchinfoDocsizeLocal() routine fills in the nX values.
113520 ** The fts3MatchinfoDocsizeGlobal() routine fills in N and the aX values.
113521 */
113522 SQLITE_PRIVATE int sqlite3Fts3MatchinfoDocsizeLocal(Fts3Cursor *pCur, u32 *a){
113523   const char *pBlob;       /* The BLOB holding %_docsize info */
113524   int nBlob;               /* Size of the BLOB */
113525   sqlite3_stmt *pStmt;     /* Statement for reading and writing */
113526   int i, j;                /* Loop counters */
113527   sqlite3_int64 x;         /* Varint value */
113528   int rc;                  /* Result code from subfunctions */
113529   Fts3Table *p;            /* The FTS table */
113530
113531   p = (Fts3Table*)pCur->base.pVtab;
113532   rc = fts3SqlStmt(p, SQL_SELECT_DOCSIZE, &pStmt, 0);
113533   if( rc ){
113534     return rc;
113535   }
113536   sqlite3_bind_int64(pStmt, 1, pCur->iPrevId);
113537   if( sqlite3_step(pStmt)==SQLITE_ROW ){
113538     nBlob = sqlite3_column_bytes(pStmt, 0);
113539     pBlob = (const char*)sqlite3_column_blob(pStmt, 0);
113540     for(i=j=0; i<p->nColumn && j<nBlob; i++){
113541       j = sqlite3Fts3GetVarint(&pBlob[j], &x);
113542       a[2+i*2] = (u32)(x & 0xffffffff);
113543     }
113544   }
113545   sqlite3_reset(pStmt);
113546   return SQLITE_OK; 
113547 }
113548 SQLITE_PRIVATE int sqlite3Fts3MatchinfoDocsizeGlobal(Fts3Cursor *pCur, u32 *a){
113549   const char *pBlob;       /* The BLOB holding %_stat info */
113550   int nBlob;               /* Size of the BLOB */
113551   sqlite3_stmt *pStmt;     /* Statement for reading and writing */
113552   int i, j;                /* Loop counters */
113553   sqlite3_int64 x;         /* Varint value */
113554   int nDoc;                /* Number of documents */
113555   int rc;                  /* Result code from subfunctions */
113556   Fts3Table *p;            /* The FTS table */
113557
113558   p = (Fts3Table*)pCur->base.pVtab;
113559   rc = fts3SqlStmt(p, SQL_SELECT_DOCTOTAL, &pStmt, 0);
113560   if( rc ){
113561     return rc;
113562   }
113563   if( sqlite3_step(pStmt)==SQLITE_ROW ){
113564     nBlob = sqlite3_column_bytes(pStmt, 0);
113565     pBlob = (const char*)sqlite3_column_blob(pStmt, 0);
113566     j = sqlite3Fts3GetVarint(pBlob, &x);
113567     a[0] = nDoc = (u32)(x & 0xffffffff);
113568     for(i=0; i<p->nColumn && j<nBlob; i++){
113569       j = sqlite3Fts3GetVarint(&pBlob[j], &x);
113570       a[1+i*2] = ((u32)(x & 0xffffffff) + nDoc/2)/nDoc;
113571     }
113572   }
113573   sqlite3_reset(pStmt);
113574   return SQLITE_OK; 
113575 }
113576
113577 /*
113578 ** Insert the sizes (in tokens) for each column of the document
113579 ** with docid equal to p->iPrevDocid.  The sizes are encoded as
113580 ** a blob of varints.
113581 */
113582 static void fts3InsertDocsize(
113583   int *pRC,         /* Result code */
113584   Fts3Table *p,     /* Table into which to insert */
113585   u32 *aSz          /* Sizes of each column */
113586 ){
113587   char *pBlob;             /* The BLOB encoding of the document size */
113588   int nBlob;               /* Number of bytes in the BLOB */
113589   sqlite3_stmt *pStmt;     /* Statement used to insert the encoding */
113590   int rc;                  /* Result code from subfunctions */
113591
113592   if( *pRC ) return;
113593   pBlob = sqlite3_malloc( 10*p->nColumn );
113594   if( pBlob==0 ){
113595     *pRC = SQLITE_NOMEM;
113596     return;
113597   }
113598   fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
113599   rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
113600   if( rc ){
113601     sqlite3_free(pBlob);
113602     *pRC = rc;
113603     return;
113604   }
113605   sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
113606   sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
113607   sqlite3_step(pStmt);
113608   *pRC = sqlite3_reset(pStmt);
113609 }
113610
113611 /*
113612 ** Update the 0 record of the %_stat table so that it holds a blob
113613 ** which contains the document count followed by the cumulative
113614 ** document sizes for all columns.
113615 */
113616 static void fts3UpdateDocTotals(
113617   int *pRC,       /* The result code */
113618   Fts3Table *p,   /* Table being updated */
113619   u32 *aSzIns,    /* Size increases */
113620   u32 *aSzDel,    /* Size decreases */
113621   int nChng       /* Change in the number of documents */
113622 ){
113623   char *pBlob;             /* Storage for BLOB written into %_stat */
113624   int nBlob;               /* Size of BLOB written into %_stat */
113625   u32 *a;                  /* Array of integers that becomes the BLOB */
113626   sqlite3_stmt *pStmt;     /* Statement for reading and writing */
113627   int i;                   /* Loop counter */
113628   int rc;                  /* Result code from subfunctions */
113629
113630   if( *pRC ) return;
113631   a = sqlite3_malloc( (sizeof(u32)+10)*(p->nColumn+1) );
113632   if( a==0 ){
113633     *pRC = SQLITE_NOMEM;
113634     return;
113635   }
113636   pBlob = (char*)&a[p->nColumn+1];
113637   rc = fts3SqlStmt(p, SQL_SELECT_DOCTOTAL, &pStmt, 0);
113638   if( rc ){
113639     sqlite3_free(a);
113640     *pRC = rc;
113641     return;
113642   }
113643   if( sqlite3_step(pStmt)==SQLITE_ROW ){
113644     fts3DecodeIntArray(p->nColumn+1, a,
113645          sqlite3_column_blob(pStmt, 0),
113646          sqlite3_column_bytes(pStmt, 0));
113647   }else{
113648     memset(a, 0, sizeof(u32)*(p->nColumn+1) );
113649   }
113650   sqlite3_reset(pStmt);
113651   if( nChng<0 && a[0]<(u32)(-nChng) ){
113652     a[0] = 0;
113653   }else{
113654     a[0] += nChng;
113655   }
113656   for(i=0; i<p->nColumn; i++){
113657     u32 x = a[i+1];
113658     if( x+aSzIns[i] < aSzDel[i] ){
113659       x = 0;
113660     }else{
113661       x = x + aSzIns[i] - aSzDel[i];
113662     }
113663     a[i+1] = x;
113664   }
113665   fts3EncodeIntArray(p->nColumn+1, a, pBlob, &nBlob);
113666   rc = fts3SqlStmt(p, SQL_REPLACE_DOCTOTAL, &pStmt, 0);
113667   if( rc ){
113668     sqlite3_free(a);
113669     *pRC = rc;
113670     return;
113671   }
113672   sqlite3_bind_blob(pStmt, 1, pBlob, nBlob, SQLITE_STATIC);
113673   sqlite3_step(pStmt);
113674   *pRC = sqlite3_reset(pStmt);
113675   sqlite3_free(a);
113676 }
113677
113678 /*
113679 ** Handle a 'special' INSERT of the form:
113680 **
113681 **   "INSERT INTO tbl(tbl) VALUES(<expr>)"
113682 **
113683 ** Argument pVal contains the result of <expr>. Currently the only 
113684 ** meaningful value to insert is the text 'optimize'.
113685 */
113686 static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
113687   int rc;                         /* Return Code */
113688   const char *zVal = (const char *)sqlite3_value_text(pVal);
113689   int nVal = sqlite3_value_bytes(pVal);
113690
113691   if( !zVal ){
113692     return SQLITE_NOMEM;
113693   }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
113694     rc = fts3SegmentMerge(p, -1);
113695     if( rc==SQLITE_DONE ){
113696       rc = SQLITE_OK;
113697     }else{
113698       sqlite3Fts3PendingTermsClear(p);
113699     }
113700 #ifdef SQLITE_TEST
113701   }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
113702     p->nNodeSize = atoi(&zVal[9]);
113703     rc = SQLITE_OK;
113704   }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
113705     p->nMaxPendingData = atoi(&zVal[11]);
113706     rc = SQLITE_OK;
113707 #endif
113708   }else{
113709     rc = SQLITE_ERROR;
113710   }
113711
113712   return rc;
113713 }
113714
113715 /*
113716 ** This function does the work for the xUpdate method of FTS3 virtual
113717 ** tables.
113718 */
113719 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
113720   sqlite3_vtab *pVtab,            /* FTS3 vtab object */
113721   int nArg,                       /* Size of argument array */
113722   sqlite3_value **apVal,          /* Array of arguments */
113723   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
113724 ){
113725   Fts3Table *p = (Fts3Table *)pVtab;
113726   int rc = SQLITE_OK;             /* Return Code */
113727   int isRemove = 0;               /* True for an UPDATE or DELETE */
113728   sqlite3_int64 iRemove = 0;      /* Rowid removed by UPDATE or DELETE */
113729   u32 *aSzIns;                    /* Sizes of inserted documents */
113730   u32 *aSzDel;                    /* Sizes of deleted documents */
113731   int nChng = 0;                  /* Net change in number of documents */
113732
113733
113734   /* Allocate space to hold the change in document sizes */
113735   aSzIns = sqlite3_malloc( sizeof(aSzIns[0])*p->nColumn*2 );
113736   if( aSzIns==0 ) return SQLITE_NOMEM;
113737   aSzDel = &aSzIns[p->nColumn];
113738   memset(aSzIns, 0, sizeof(aSzIns[0])*p->nColumn*2);
113739
113740   /* If this is a DELETE or UPDATE operation, remove the old record. */
113741   if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
113742     int isEmpty;
113743     rc = fts3IsEmpty(p, apVal, &isEmpty);
113744     if( rc==SQLITE_OK ){
113745       if( isEmpty ){
113746         /* Deleting this row means the whole table is empty. In this case
113747         ** delete the contents of all three tables and throw away any
113748         ** data in the pendingTerms hash table.
113749         */
113750         rc = fts3DeleteAll(p);
113751       }else{
113752         isRemove = 1;
113753         iRemove = sqlite3_value_int64(apVal[0]);
113754         rc = fts3PendingTermsDocid(p, iRemove);
113755         fts3DeleteTerms(&rc, p, apVal, aSzDel);
113756         fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, apVal);
113757         if( p->bHasDocsize ){
113758           fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, apVal);
113759           nChng--;
113760         }
113761       }
113762     }
113763   }else if( sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL ){
113764     sqlite3_free(aSzIns);
113765     return fts3SpecialInsert(p, apVal[p->nColumn+2]);
113766   }
113767   
113768   /* If this is an INSERT or UPDATE operation, insert the new record. */
113769   if( nArg>1 && rc==SQLITE_OK ){
113770     rc = fts3InsertData(p, apVal, pRowid);
113771     if( rc==SQLITE_OK && (!isRemove || *pRowid!=iRemove) ){
113772       rc = fts3PendingTermsDocid(p, *pRowid);
113773     }
113774     if( rc==SQLITE_OK ){
113775       rc = fts3InsertTerms(p, apVal, aSzIns);
113776     }
113777     if( p->bHasDocsize ){
113778       nChng++;
113779       fts3InsertDocsize(&rc, p, aSzIns);
113780     }
113781   }
113782
113783   if( p->bHasDocsize ){
113784     fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
113785   }
113786
113787   sqlite3_free(aSzIns);
113788   return rc;
113789 }
113790
113791 /* 
113792 ** Flush any data in the pending-terms hash table to disk. If successful,
113793 ** merge all segments in the database (including the new segment, if 
113794 ** there was any data to flush) into a single segment. 
113795 */
113796 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
113797   int rc;
113798   rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
113799   if( rc==SQLITE_OK ){
113800     rc = fts3SegmentMerge(p, -1);
113801     if( rc==SQLITE_OK ){
113802       rc = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
113803       if( rc==SQLITE_OK ){
113804         sqlite3Fts3PendingTermsClear(p);
113805       }
113806     }else{
113807       sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
113808       sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
113809     }
113810   }
113811   return rc;
113812 }
113813
113814 #endif
113815
113816 /************** End of fts3_write.c ******************************************/
113817 /************** Begin file fts3_snippet.c ************************************/
113818 /*
113819 ** 2009 Oct 23
113820 **
113821 ** The author disclaims copyright to this source code.  In place of
113822 ** a legal notice, here is a blessing:
113823 **
113824 **    May you do good and not evil.
113825 **    May you find forgiveness for yourself and forgive others.
113826 **    May you share freely, never taking more than you give.
113827 **
113828 ******************************************************************************
113829 */
113830
113831 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
113832
113833
113834
113835 /*
113836 ** Used as an fts3ExprIterate() context when loading phrase doclists to
113837 ** Fts3Expr.aDoclist[]/nDoclist.
113838 */
113839 typedef struct LoadDoclistCtx LoadDoclistCtx;
113840 struct LoadDoclistCtx {
113841   Fts3Table *pTab;                /* FTS3 Table */
113842   int nPhrase;                    /* Number of phrases seen so far */
113843   int nToken;                     /* Number of tokens seen so far */
113844 };
113845
113846 /*
113847 ** The following types are used as part of the implementation of the 
113848 ** fts3BestSnippet() routine.
113849 */
113850 typedef struct SnippetIter SnippetIter;
113851 typedef struct SnippetPhrase SnippetPhrase;
113852 typedef struct SnippetFragment SnippetFragment;
113853
113854 struct SnippetIter {
113855   Fts3Cursor *pCsr;               /* Cursor snippet is being generated from */
113856   int iCol;                       /* Extract snippet from this column */
113857   int nSnippet;                   /* Requested snippet length (in tokens) */
113858   int nPhrase;                    /* Number of phrases in query */
113859   SnippetPhrase *aPhrase;         /* Array of size nPhrase */
113860   int iCurrent;                   /* First token of current snippet */
113861 };
113862
113863 struct SnippetPhrase {
113864   int nToken;                     /* Number of tokens in phrase */
113865   char *pList;                    /* Pointer to start of phrase position list */
113866   int iHead;                      /* Next value in position list */
113867   char *pHead;                    /* Position list data following iHead */
113868   int iTail;                      /* Next value in trailing position list */
113869   char *pTail;                    /* Position list data following iTail */
113870 };
113871
113872 struct SnippetFragment {
113873   int iCol;                       /* Column snippet is extracted from */
113874   int iPos;                       /* Index of first token in snippet */
113875   u64 covered;                    /* Mask of query phrases covered */
113876   u64 hlmask;                     /* Mask of snippet terms to highlight */
113877 };
113878
113879 /*
113880 ** This type is used as an fts3ExprIterate() context object while 
113881 ** accumulating the data returned by the matchinfo() function.
113882 */
113883 typedef struct MatchInfo MatchInfo;
113884 struct MatchInfo {
113885   Fts3Cursor *pCursor;            /* FTS3 Cursor */
113886   int nCol;                       /* Number of columns in table */
113887   u32 *aMatchinfo;                /* Pre-allocated buffer */
113888 };
113889
113890
113891
113892 /*
113893 ** The snippet() and offsets() functions both return text values. An instance
113894 ** of the following structure is used to accumulate those values while the
113895 ** functions are running. See fts3StringAppend() for details.
113896 */
113897 typedef struct StrBuffer StrBuffer;
113898 struct StrBuffer {
113899   char *z;                        /* Pointer to buffer containing string */
113900   int n;                          /* Length of z in bytes (excl. nul-term) */
113901   int nAlloc;                     /* Allocated size of buffer z in bytes */
113902 };
113903
113904
113905 /*
113906 ** This function is used to help iterate through a position-list. A position
113907 ** list is a list of unique integers, sorted from smallest to largest. Each
113908 ** element of the list is represented by an FTS3 varint that takes the value
113909 ** of the difference between the current element and the previous one plus
113910 ** two. For example, to store the position-list:
113911 **
113912 **     4 9 113
113913 **
113914 ** the three varints:
113915 **
113916 **     6 7 106
113917 **
113918 ** are encoded.
113919 **
113920 ** When this function is called, *pp points to the start of an element of
113921 ** the list. *piPos contains the value of the previous entry in the list.
113922 ** After it returns, *piPos contains the value of the next element of the
113923 ** list and *pp is advanced to the following varint.
113924 */
113925 static void fts3GetDeltaPosition(char **pp, int *piPos){
113926   int iVal;
113927   *pp += sqlite3Fts3GetVarint32(*pp, &iVal);
113928   *piPos += (iVal-2);
113929 }
113930
113931 /*
113932 ** Helper function for fts3ExprIterate() (see below).
113933 */
113934 static int fts3ExprIterate2(
113935   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
113936   int *piPhrase,                  /* Pointer to phrase counter */
113937   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
113938   void *pCtx                      /* Second argument to pass to callback */
113939 ){
113940   int rc;                         /* Return code */
113941   int eType = pExpr->eType;       /* Type of expression node pExpr */
113942
113943   if( eType!=FTSQUERY_PHRASE ){
113944     assert( pExpr->pLeft && pExpr->pRight );
113945     rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
113946     if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
113947       rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
113948     }
113949   }else{
113950     rc = x(pExpr, *piPhrase, pCtx);
113951     (*piPhrase)++;
113952   }
113953   return rc;
113954 }
113955
113956 /*
113957 ** Iterate through all phrase nodes in an FTS3 query, except those that
113958 ** are part of a sub-tree that is the right-hand-side of a NOT operator.
113959 ** For each phrase node found, the supplied callback function is invoked.
113960 **
113961 ** If the callback function returns anything other than SQLITE_OK, 
113962 ** the iteration is abandoned and the error code returned immediately.
113963 ** Otherwise, SQLITE_OK is returned after a callback has been made for
113964 ** all eligible phrase nodes.
113965 */
113966 static int fts3ExprIterate(
113967   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
113968   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
113969   void *pCtx                      /* Second argument to pass to callback */
113970 ){
113971   int iPhrase = 0;                /* Variable used as the phrase counter */
113972   return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
113973 }
113974
113975 /*
113976 ** The argument to this function is always a phrase node. Its doclist 
113977 ** (Fts3Expr.aDoclist[]) and the doclists associated with all phrase nodes
113978 ** to the left of this one in the query tree have already been loaded.
113979 **
113980 ** If this phrase node is part of a series of phrase nodes joined by 
113981 ** NEAR operators (and is not the left-most of said series), then elements are
113982 ** removed from the phrases doclist consistent with the NEAR restriction. If
113983 ** required, elements may be removed from the doclists of phrases to the
113984 ** left of this one that are part of the same series of NEAR operator 
113985 ** connected phrases.
113986 **
113987 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
113988 */
113989 static int fts3ExprNearTrim(Fts3Expr *pExpr){
113990   int rc = SQLITE_OK;
113991   Fts3Expr *pParent = pExpr->pParent;
113992
113993   assert( pExpr->eType==FTSQUERY_PHRASE );
113994   while( rc==SQLITE_OK
113995    && pParent 
113996    && pParent->eType==FTSQUERY_NEAR 
113997    && pParent->pRight==pExpr 
113998   ){
113999     /* This expression (pExpr) is the right-hand-side of a NEAR operator. 
114000     ** Find the expression to the left of the same operator.
114001     */
114002     int nNear = pParent->nNear;
114003     Fts3Expr *pLeft = pParent->pLeft;
114004
114005     if( pLeft->eType!=FTSQUERY_PHRASE ){
114006       assert( pLeft->eType==FTSQUERY_NEAR );
114007       assert( pLeft->pRight->eType==FTSQUERY_PHRASE );
114008       pLeft = pLeft->pRight;
114009     }
114010
114011     rc = sqlite3Fts3ExprNearTrim(pLeft, pExpr, nNear);
114012
114013     pExpr = pLeft;
114014     pParent = pExpr->pParent;
114015   }
114016
114017   return rc;
114018 }
114019
114020 /*
114021 ** This is an fts3ExprIterate() callback used while loading the doclists
114022 ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
114023 ** fts3ExprLoadDoclists().
114024 */
114025 static int fts3ExprLoadDoclistsCb1(Fts3Expr *pExpr, int iPhrase, void *ctx){
114026   int rc = SQLITE_OK;
114027   LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
114028
114029   UNUSED_PARAMETER(iPhrase);
114030
114031   p->nPhrase++;
114032   p->nToken += pExpr->pPhrase->nToken;
114033
114034   if( pExpr->isLoaded==0 ){
114035     rc = sqlite3Fts3ExprLoadDoclist(p->pTab, pExpr);
114036     pExpr->isLoaded = 1;
114037     if( rc==SQLITE_OK ){
114038       rc = fts3ExprNearTrim(pExpr);
114039     }
114040   }
114041
114042   return rc;
114043 }
114044
114045 /*
114046 ** This is an fts3ExprIterate() callback used while loading the doclists
114047 ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
114048 ** fts3ExprLoadDoclists().
114049 */
114050 static int fts3ExprLoadDoclistsCb2(Fts3Expr *pExpr, int iPhrase, void *ctx){
114051   UNUSED_PARAMETER(iPhrase);
114052   UNUSED_PARAMETER(ctx);
114053   if( pExpr->aDoclist ){
114054     pExpr->pCurrent = pExpr->aDoclist;
114055     pExpr->iCurrent = 0;
114056     pExpr->pCurrent += sqlite3Fts3GetVarint(pExpr->pCurrent, &pExpr->iCurrent);
114057   }
114058   return SQLITE_OK;
114059 }
114060
114061 /*
114062 ** Load the doclists for each phrase in the query associated with FTS3 cursor
114063 ** pCsr. 
114064 **
114065 ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable 
114066 ** phrases in the expression (all phrases except those directly or 
114067 ** indirectly descended from the right-hand-side of a NOT operator). If 
114068 ** pnToken is not NULL, then it is set to the number of tokens in all
114069 ** matchable phrases of the expression.
114070 */
114071 static int fts3ExprLoadDoclists(
114072   Fts3Cursor *pCsr,               /* Fts3 cursor for current query */
114073   int *pnPhrase,                  /* OUT: Number of phrases in query */
114074   int *pnToken                    /* OUT: Number of tokens in query */
114075 ){
114076   int rc;                         /* Return Code */
114077   LoadDoclistCtx sCtx = {0,0,0};  /* Context for fts3ExprIterate() */
114078   sCtx.pTab = (Fts3Table *)pCsr->base.pVtab;
114079   rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb1, (void *)&sCtx);
114080   if( rc==SQLITE_OK ){
114081     (void)fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb2, 0);
114082   }
114083   if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
114084   if( pnToken ) *pnToken = sCtx.nToken;
114085   return rc;
114086 }
114087
114088 /*
114089 ** Advance the position list iterator specified by the first two 
114090 ** arguments so that it points to the first element with a value greater
114091 ** than or equal to parameter iNext.
114092 */
114093 static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
114094   char *pIter = *ppIter;
114095   if( pIter ){
114096     int iIter = *piIter;
114097
114098     while( iIter<iNext ){
114099       if( 0==(*pIter & 0xFE) ){
114100         iIter = -1;
114101         pIter = 0;
114102         break;
114103       }
114104       fts3GetDeltaPosition(&pIter, &iIter);
114105     }
114106
114107     *piIter = iIter;
114108     *ppIter = pIter;
114109   }
114110 }
114111
114112 /*
114113 ** Advance the snippet iterator to the next candidate snippet.
114114 */
114115 static int fts3SnippetNextCandidate(SnippetIter *pIter){
114116   int i;                          /* Loop counter */
114117
114118   if( pIter->iCurrent<0 ){
114119     /* The SnippetIter object has just been initialized. The first snippet
114120     ** candidate always starts at offset 0 (even if this candidate has a
114121     ** score of 0.0).
114122     */
114123     pIter->iCurrent = 0;
114124
114125     /* Advance the 'head' iterator of each phrase to the first offset that
114126     ** is greater than or equal to (iNext+nSnippet).
114127     */
114128     for(i=0; i<pIter->nPhrase; i++){
114129       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
114130       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
114131     }
114132   }else{
114133     int iStart;
114134     int iEnd = 0x7FFFFFFF;
114135
114136     for(i=0; i<pIter->nPhrase; i++){
114137       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
114138       if( pPhrase->pHead && pPhrase->iHead<iEnd ){
114139         iEnd = pPhrase->iHead;
114140       }
114141     }
114142     if( iEnd==0x7FFFFFFF ){
114143       return 1;
114144     }
114145
114146     pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
114147     for(i=0; i<pIter->nPhrase; i++){
114148       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
114149       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
114150       fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
114151     }
114152   }
114153
114154   return 0;
114155 }
114156
114157 /*
114158 ** Retrieve information about the current candidate snippet of snippet 
114159 ** iterator pIter.
114160 */
114161 static void fts3SnippetDetails(
114162   SnippetIter *pIter,             /* Snippet iterator */
114163   u64 mCovered,                   /* Bitmask of phrases already covered */
114164   int *piToken,                   /* OUT: First token of proposed snippet */
114165   int *piScore,                   /* OUT: "Score" for this snippet */
114166   u64 *pmCover,                   /* OUT: Bitmask of phrases covered */
114167   u64 *pmHighlight                /* OUT: Bitmask of terms to highlight */
114168 ){
114169   int iStart = pIter->iCurrent;   /* First token of snippet */
114170   int iScore = 0;                 /* Score of this snippet */
114171   int i;                          /* Loop counter */
114172   u64 mCover = 0;                 /* Mask of phrases covered by this snippet */
114173   u64 mHighlight = 0;             /* Mask of tokens to highlight in snippet */
114174
114175   for(i=0; i<pIter->nPhrase; i++){
114176     SnippetPhrase *pPhrase = &pIter->aPhrase[i];
114177     if( pPhrase->pTail ){
114178       char *pCsr = pPhrase->pTail;
114179       int iCsr = pPhrase->iTail;
114180
114181       while( iCsr<(iStart+pIter->nSnippet) ){
114182         int j;
114183         u64 mPhrase = (u64)1 << i;
114184         u64 mPos = (u64)1 << (iCsr - iStart);
114185         assert( iCsr>=iStart );
114186         if( (mCover|mCovered)&mPhrase ){
114187           iScore++;
114188         }else{
114189           iScore += 1000;
114190         }
114191         mCover |= mPhrase;
114192
114193         for(j=0; j<pPhrase->nToken; j++){
114194           mHighlight |= (mPos>>j);
114195         }
114196
114197         if( 0==(*pCsr & 0x0FE) ) break;
114198         fts3GetDeltaPosition(&pCsr, &iCsr);
114199       }
114200     }
114201   }
114202
114203   /* Set the output variables before returning. */
114204   *piToken = iStart;
114205   *piScore = iScore;
114206   *pmCover = mCover;
114207   *pmHighlight = mHighlight;
114208 }
114209
114210 /*
114211 ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
114212 ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
114213 */
114214 static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
114215   SnippetIter *p = (SnippetIter *)ctx;
114216   SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
114217   char *pCsr;
114218
114219   pPhrase->nToken = pExpr->pPhrase->nToken;
114220
114221   pCsr = sqlite3Fts3FindPositions(pExpr, p->pCsr->iPrevId, p->iCol);
114222   if( pCsr ){
114223     int iFirst = 0;
114224     pPhrase->pList = pCsr;
114225     fts3GetDeltaPosition(&pCsr, &iFirst);
114226     pPhrase->pHead = pCsr;
114227     pPhrase->pTail = pCsr;
114228     pPhrase->iHead = iFirst;
114229     pPhrase->iTail = iFirst;
114230   }else{
114231     assert( pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0 );
114232   }
114233
114234   return SQLITE_OK;
114235 }
114236
114237 /*
114238 ** Select the fragment of text consisting of nFragment contiguous tokens 
114239 ** from column iCol that represent the "best" snippet. The best snippet
114240 ** is the snippet with the highest score, where scores are calculated
114241 ** by adding:
114242 **
114243 **   (a) +1 point for each occurence of a matchable phrase in the snippet.
114244 **
114245 **   (b) +1000 points for the first occurence of each matchable phrase in 
114246 **       the snippet for which the corresponding mCovered bit is not set.
114247 **
114248 ** The selected snippet parameters are stored in structure *pFragment before
114249 ** returning. The score of the selected snippet is stored in *piScore
114250 ** before returning.
114251 */
114252 static int fts3BestSnippet(
114253   int nSnippet,                   /* Desired snippet length */
114254   Fts3Cursor *pCsr,               /* Cursor to create snippet for */
114255   int iCol,                       /* Index of column to create snippet from */
114256   u64 mCovered,                   /* Mask of phrases already covered */
114257   u64 *pmSeen,                    /* IN/OUT: Mask of phrases seen */
114258   SnippetFragment *pFragment,     /* OUT: Best snippet found */
114259   int *piScore                    /* OUT: Score of snippet pFragment */
114260 ){
114261   int rc;                         /* Return Code */
114262   int nList;                      /* Number of phrases in expression */
114263   SnippetIter sIter;              /* Iterates through snippet candidates */
114264   int nByte;                      /* Number of bytes of space to allocate */
114265   int iBestScore = -1;            /* Best snippet score found so far */
114266   int i;                          /* Loop counter */
114267
114268   memset(&sIter, 0, sizeof(sIter));
114269
114270   /* Iterate through the phrases in the expression to count them. The same
114271   ** callback makes sure the doclists are loaded for each phrase.
114272   */
114273   rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
114274   if( rc!=SQLITE_OK ){
114275     return rc;
114276   }
114277
114278   /* Now that it is known how many phrases there are, allocate and zero
114279   ** the required space using malloc().
114280   */
114281   nByte = sizeof(SnippetPhrase) * nList;
114282   sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
114283   if( !sIter.aPhrase ){
114284     return SQLITE_NOMEM;
114285   }
114286   memset(sIter.aPhrase, 0, nByte);
114287
114288   /* Initialize the contents of the SnippetIter object. Then iterate through
114289   ** the set of phrases in the expression to populate the aPhrase[] array.
114290   */
114291   sIter.pCsr = pCsr;
114292   sIter.iCol = iCol;
114293   sIter.nSnippet = nSnippet;
114294   sIter.nPhrase = nList;
114295   sIter.iCurrent = -1;
114296   (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
114297
114298   /* Set the *pmSeen output variable. */
114299   for(i=0; i<nList; i++){
114300     if( sIter.aPhrase[i].pHead ){
114301       *pmSeen |= (u64)1 << i;
114302     }
114303   }
114304
114305   /* Loop through all candidate snippets. Store the best snippet in 
114306   ** *pFragment. Store its associated 'score' in iBestScore.
114307   */
114308   pFragment->iCol = iCol;
114309   while( !fts3SnippetNextCandidate(&sIter) ){
114310     int iPos;
114311     int iScore;
114312     u64 mCover;
114313     u64 mHighlight;
114314     fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);
114315     assert( iScore>=0 );
114316     if( iScore>iBestScore ){
114317       pFragment->iPos = iPos;
114318       pFragment->hlmask = mHighlight;
114319       pFragment->covered = mCover;
114320       iBestScore = iScore;
114321     }
114322   }
114323
114324   sqlite3_free(sIter.aPhrase);
114325   *piScore = iBestScore;
114326   return SQLITE_OK;
114327 }
114328
114329
114330 /*
114331 ** Append a string to the string-buffer passed as the first argument.
114332 **
114333 ** If nAppend is negative, then the length of the string zAppend is
114334 ** determined using strlen().
114335 */
114336 static int fts3StringAppend(
114337   StrBuffer *pStr,                /* Buffer to append to */
114338   const char *zAppend,            /* Pointer to data to append to buffer */
114339   int nAppend                     /* Size of zAppend in bytes (or -1) */
114340 ){
114341   if( nAppend<0 ){
114342     nAppend = (int)strlen(zAppend);
114343   }
114344
114345   /* If there is insufficient space allocated at StrBuffer.z, use realloc()
114346   ** to grow the buffer until so that it is big enough to accomadate the
114347   ** appended data.
114348   */
114349   if( pStr->n+nAppend+1>=pStr->nAlloc ){
114350     int nAlloc = pStr->nAlloc+nAppend+100;
114351     char *zNew = sqlite3_realloc(pStr->z, nAlloc);
114352     if( !zNew ){
114353       return SQLITE_NOMEM;
114354     }
114355     pStr->z = zNew;
114356     pStr->nAlloc = nAlloc;
114357   }
114358
114359   /* Append the data to the string buffer. */
114360   memcpy(&pStr->z[pStr->n], zAppend, nAppend);
114361   pStr->n += nAppend;
114362   pStr->z[pStr->n] = '\0';
114363
114364   return SQLITE_OK;
114365 }
114366
114367 /*
114368 ** The fts3BestSnippet() function often selects snippets that end with a
114369 ** query term. That is, the final term of the snippet is always a term
114370 ** that requires highlighting. For example, if 'X' is a highlighted term
114371 ** and '.' is a non-highlighted term, BestSnippet() may select:
114372 **
114373 **     ........X.....X
114374 **
114375 ** This function "shifts" the beginning of the snippet forward in the 
114376 ** document so that there are approximately the same number of 
114377 ** non-highlighted terms to the right of the final highlighted term as there
114378 ** are to the left of the first highlighted term. For example, to this:
114379 **
114380 **     ....X.....X....
114381 **
114382 ** This is done as part of extracting the snippet text, not when selecting
114383 ** the snippet. Snippet selection is done based on doclists only, so there
114384 ** is no way for fts3BestSnippet() to know whether or not the document 
114385 ** actually contains terms that follow the final highlighted term. 
114386 */
114387 static int fts3SnippetShift(
114388   Fts3Table *pTab,                /* FTS3 table snippet comes from */
114389   int nSnippet,                   /* Number of tokens desired for snippet */
114390   const char *zDoc,               /* Document text to extract snippet from */
114391   int nDoc,                       /* Size of buffer zDoc in bytes */
114392   int *piPos,                     /* IN/OUT: First token of snippet */
114393   u64 *pHlmask                    /* IN/OUT: Mask of tokens to highlight */
114394 ){
114395   u64 hlmask = *pHlmask;          /* Local copy of initial highlight-mask */
114396
114397   if( hlmask ){
114398     int nLeft;                    /* Tokens to the left of first highlight */
114399     int nRight;                   /* Tokens to the right of last highlight */
114400     int nDesired;                 /* Ideal number of tokens to shift forward */
114401
114402     for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
114403     for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
114404     nDesired = (nLeft-nRight)/2;
114405
114406     /* Ideally, the start of the snippet should be pushed forward in the
114407     ** document nDesired tokens. This block checks if there are actually
114408     ** nDesired tokens to the right of the snippet. If so, *piPos and
114409     ** *pHlMask are updated to shift the snippet nDesired tokens to the
114410     ** right. Otherwise, the snippet is shifted by the number of tokens
114411     ** available.
114412     */
114413     if( nDesired>0 ){
114414       int nShift;                 /* Number of tokens to shift snippet by */
114415       int iCurrent = 0;           /* Token counter */
114416       int rc;                     /* Return Code */
114417       sqlite3_tokenizer_module *pMod;
114418       sqlite3_tokenizer_cursor *pC;
114419       pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
114420
114421       /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
114422       ** or more tokens in zDoc/nDoc.
114423       */
114424       rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
114425       if( rc!=SQLITE_OK ){
114426         return rc;
114427       }
114428       pC->pTokenizer = pTab->pTokenizer;
114429       while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
114430         const char *ZDUMMY; int DUMMY1, DUMMY2, DUMMY3;
114431         rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
114432       }
114433       pMod->xClose(pC);
114434       if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
114435
114436       nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
114437       assert( nShift<=nDesired );
114438       if( nShift>0 ){
114439         *piPos += nShift;
114440         *pHlmask = hlmask >> nShift;
114441       }
114442     }
114443   }
114444   return SQLITE_OK;
114445 }
114446
114447 /*
114448 ** Extract the snippet text for fragment pFragment from cursor pCsr and
114449 ** append it to string buffer pOut.
114450 */
114451 static int fts3SnippetText(
114452   Fts3Cursor *pCsr,               /* FTS3 Cursor */
114453   SnippetFragment *pFragment,     /* Snippet to extract */
114454   int iFragment,                  /* Fragment number */
114455   int isLast,                     /* True for final fragment in snippet */
114456   int nSnippet,                   /* Number of tokens in extracted snippet */
114457   const char *zOpen,              /* String inserted before highlighted term */
114458   const char *zClose,             /* String inserted after highlighted term */
114459   const char *zEllipsis,          /* String inserted between snippets */
114460   StrBuffer *pOut                 /* Write output here */
114461 ){
114462   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
114463   int rc;                         /* Return code */
114464   const char *zDoc;               /* Document text to extract snippet from */
114465   int nDoc;                       /* Size of zDoc in bytes */
114466   int iCurrent = 0;               /* Current token number of document */
114467   int iEnd = 0;                   /* Byte offset of end of current token */
114468   int isShiftDone = 0;            /* True after snippet is shifted */
114469   int iPos = pFragment->iPos;     /* First token of snippet */
114470   u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
114471   int iCol = pFragment->iCol+1;   /* Query column to extract text from */
114472   sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
114473   sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
114474   const char *ZDUMMY;             /* Dummy argument used with tokenizer */
114475   int DUMMY1;                     /* Dummy argument used with tokenizer */
114476   
114477   zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
114478   if( zDoc==0 ){
114479     if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
114480       return SQLITE_NOMEM;
114481     }
114482     return SQLITE_OK;
114483   }
114484   nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
114485
114486   /* Open a token cursor on the document. */
114487   pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
114488   rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
114489   if( rc!=SQLITE_OK ){
114490     return rc;
114491   }
114492   pC->pTokenizer = pTab->pTokenizer;
114493
114494   while( rc==SQLITE_OK ){
114495     int iBegin;                   /* Offset in zDoc of start of token */
114496     int iFin;                     /* Offset in zDoc of end of token */
114497     int isHighlight;              /* True for highlighted terms */
114498
114499     rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
114500     if( rc!=SQLITE_OK ){
114501       if( rc==SQLITE_DONE ){
114502         /* Special case - the last token of the snippet is also the last token
114503         ** of the column. Append any punctuation that occurred between the end
114504         ** of the previous token and the end of the document to the output. 
114505         ** Then break out of the loop. */
114506         rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
114507       }
114508       break;
114509     }
114510     if( iCurrent<iPos ){ continue; }
114511
114512     if( !isShiftDone ){
114513       int n = nDoc - iBegin;
114514       rc = fts3SnippetShift(pTab, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask);
114515       isShiftDone = 1;
114516
114517       /* Now that the shift has been done, check if the initial "..." are
114518       ** required. They are required if (a) this is not the first fragment,
114519       ** or (b) this fragment does not begin at position 0 of its column. 
114520       */
114521       if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){
114522         rc = fts3StringAppend(pOut, zEllipsis, -1);
114523       }
114524       if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
114525     }
114526
114527     if( iCurrent>=(iPos+nSnippet) ){
114528       if( isLast ){
114529         rc = fts3StringAppend(pOut, zEllipsis, -1);
114530       }
114531       break;
114532     }
114533
114534     /* Set isHighlight to true if this term should be highlighted. */
114535     isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
114536
114537     if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
114538     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
114539     if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
114540     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
114541
114542     iEnd = iFin;
114543   }
114544
114545   pMod->xClose(pC);
114546   return rc;
114547 }
114548
114549
114550 /*
114551 ** This function is used to count the entries in a column-list (a 
114552 ** delta-encoded list of term offsets within a single column of a single 
114553 ** row). When this function is called, *ppCollist should point to the
114554 ** beginning of the first varint in the column-list (the varint that
114555 ** contains the position of the first matching term in the column data).
114556 ** Before returning, *ppCollist is set to point to the first byte after
114557 ** the last varint in the column-list (either the 0x00 signifying the end
114558 ** of the position-list, or the 0x01 that precedes the column number of
114559 ** the next column in the position-list).
114560 **
114561 ** The number of elements in the column-list is returned.
114562 */
114563 static int fts3ColumnlistCount(char **ppCollist){
114564   char *pEnd = *ppCollist;
114565   char c = 0;
114566   int nEntry = 0;
114567
114568   /* A column-list is terminated by either a 0x01 or 0x00. */
114569   while( 0xFE & (*pEnd | c) ){
114570     c = *pEnd++ & 0x80;
114571     if( !c ) nEntry++;
114572   }
114573
114574   *ppCollist = pEnd;
114575   return nEntry;
114576 }
114577
114578 static void fts3LoadColumnlistCounts(char **pp, u32 *aOut, int isGlobal){
114579   char *pCsr = *pp;
114580   while( *pCsr ){
114581     int nHit;
114582     sqlite3_int64 iCol = 0;
114583     if( *pCsr==0x01 ){
114584       pCsr++;
114585       pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
114586     }
114587     nHit = fts3ColumnlistCount(&pCsr);
114588     assert( nHit>0 );
114589     if( isGlobal ){
114590       aOut[iCol*3+1]++;
114591     }
114592     aOut[iCol*3] += nHit;
114593   }
114594   pCsr++;
114595   *pp = pCsr;
114596 }
114597
114598 /*
114599 ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
114600 ** for a single query. The "global" stats are those elements of the matchinfo
114601 ** array that are constant for all rows returned by the current query.
114602 */
114603 static int fts3ExprGlobalMatchinfoCb(
114604   Fts3Expr *pExpr,                /* Phrase expression node */
114605   int iPhrase,                    /* Phrase number (numbered from zero) */
114606   void *pCtx                      /* Pointer to MatchInfo structure */
114607 ){
114608   MatchInfo *p = (MatchInfo *)pCtx;
114609   char *pCsr;
114610   char *pEnd;
114611   const int iStart = 2 + (iPhrase * p->nCol * 3) + 1;
114612
114613   assert( pExpr->isLoaded );
114614
114615   /* Fill in the global hit count matrix row for this phrase. */
114616   pCsr = pExpr->aDoclist;
114617   pEnd = &pExpr->aDoclist[pExpr->nDoclist];
114618   while( pCsr<pEnd ){
114619     while( *pCsr++ & 0x80 );      /* Skip past docid. */
114620     fts3LoadColumnlistCounts(&pCsr, &p->aMatchinfo[iStart], 1);
114621   }
114622
114623   return SQLITE_OK;
114624 }
114625
114626 /*
114627 ** fts3ExprIterate() callback used to collect the "local" matchinfo stats
114628 ** for a single query. The "local" stats are those elements of the matchinfo
114629 ** array that are different for each row returned by the query.
114630 */
114631 static int fts3ExprLocalMatchinfoCb(
114632   Fts3Expr *pExpr,                /* Phrase expression node */
114633   int iPhrase,                    /* Phrase number */
114634   void *pCtx                      /* Pointer to MatchInfo structure */
114635 ){
114636   MatchInfo *p = (MatchInfo *)pCtx;
114637
114638   if( pExpr->aDoclist ){
114639     char *pCsr;
114640     int iStart = 2 + (iPhrase * p->nCol * 3);
114641     int i;
114642
114643     for(i=0; i<p->nCol; i++) p->aMatchinfo[iStart+i*3] = 0;
114644
114645     pCsr = sqlite3Fts3FindPositions(pExpr, p->pCursor->iPrevId, -1);
114646     if( pCsr ){
114647       fts3LoadColumnlistCounts(&pCsr, &p->aMatchinfo[iStart], 0);
114648     }
114649   }
114650
114651   return SQLITE_OK;
114652 }
114653
114654 /*
114655 ** Populate pCsr->aMatchinfo[] with data for the current row. The 
114656 ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
114657 */
114658 static int fts3GetMatchinfo(Fts3Cursor *pCsr){
114659   MatchInfo sInfo;
114660   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
114661   int rc = SQLITE_OK;
114662
114663   sInfo.pCursor = pCsr;
114664   sInfo.nCol = pTab->nColumn;
114665
114666   if( pCsr->aMatchinfo==0 ){
114667     /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
114668     ** matchinfo function has been called for this query. In this case 
114669     ** allocate the array used to accumulate the matchinfo data and
114670     ** initialize those elements that are constant for every row.
114671     */
114672     int nPhrase;                  /* Number of phrases */
114673     int nMatchinfo;               /* Number of u32 elements in match-info */
114674
114675     /* Load doclists for each phrase in the query. */
114676     rc = fts3ExprLoadDoclists(pCsr, &nPhrase, 0);
114677     if( rc!=SQLITE_OK ){
114678       return rc;
114679     }
114680     nMatchinfo = 2 + 3*sInfo.nCol*nPhrase;
114681     if( pTab->bHasDocsize ){
114682       nMatchinfo += 1 + 2*pTab->nColumn;
114683     }
114684
114685     sInfo.aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo);
114686     if( !sInfo.aMatchinfo ){ 
114687       return SQLITE_NOMEM;
114688     }
114689     memset(sInfo.aMatchinfo, 0, sizeof(u32)*nMatchinfo);
114690
114691
114692     /* First element of match-info is the number of phrases in the query */
114693     sInfo.aMatchinfo[0] = nPhrase;
114694     sInfo.aMatchinfo[1] = sInfo.nCol;
114695     (void)fts3ExprIterate(pCsr->pExpr, fts3ExprGlobalMatchinfoCb,(void*)&sInfo);
114696     if( pTab->bHasDocsize ){
114697       int ofst = 2 + 3*sInfo.aMatchinfo[0]*sInfo.aMatchinfo[1];
114698       rc = sqlite3Fts3MatchinfoDocsizeGlobal(pCsr, &sInfo.aMatchinfo[ofst]);
114699     }
114700     pCsr->aMatchinfo = sInfo.aMatchinfo;
114701     pCsr->isMatchinfoNeeded = 1;
114702   }
114703
114704   sInfo.aMatchinfo = pCsr->aMatchinfo;
114705   if( rc==SQLITE_OK && pCsr->isMatchinfoNeeded ){
114706     (void)fts3ExprIterate(pCsr->pExpr, fts3ExprLocalMatchinfoCb, (void*)&sInfo);
114707     if( pTab->bHasDocsize ){
114708       int ofst = 2 + 3*sInfo.aMatchinfo[0]*sInfo.aMatchinfo[1];
114709       rc = sqlite3Fts3MatchinfoDocsizeLocal(pCsr, &sInfo.aMatchinfo[ofst]);
114710     }
114711     pCsr->isMatchinfoNeeded = 0;
114712   }
114713
114714   return SQLITE_OK;
114715 }
114716
114717 /*
114718 ** Implementation of snippet() function.
114719 */
114720 SQLITE_PRIVATE void sqlite3Fts3Snippet(
114721   sqlite3_context *pCtx,          /* SQLite function call context */
114722   Fts3Cursor *pCsr,               /* Cursor object */
114723   const char *zStart,             /* Snippet start text - "<b>" */
114724   const char *zEnd,               /* Snippet end text - "</b>" */
114725   const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
114726   int iCol,                       /* Extract snippet from this column */
114727   int nToken                      /* Approximate number of tokens in snippet */
114728 ){
114729   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
114730   int rc = SQLITE_OK;
114731   int i;
114732   StrBuffer res = {0, 0, 0};
114733
114734   /* The returned text includes up to four fragments of text extracted from
114735   ** the data in the current row. The first iteration of the for(...) loop
114736   ** below attempts to locate a single fragment of text nToken tokens in 
114737   ** size that contains at least one instance of all phrases in the query
114738   ** expression that appear in the current row. If such a fragment of text
114739   ** cannot be found, the second iteration of the loop attempts to locate
114740   ** a pair of fragments, and so on.
114741   */
114742   int nSnippet = 0;               /* Number of fragments in this snippet */
114743   SnippetFragment aSnippet[4];    /* Maximum of 4 fragments per snippet */
114744   int nFToken = -1;               /* Number of tokens in each fragment */
114745
114746   if( !pCsr->pExpr ){
114747     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
114748     return;
114749   }
114750
114751   for(nSnippet=1; 1; nSnippet++){
114752
114753     int iSnip;                    /* Loop counter 0..nSnippet-1 */
114754     u64 mCovered = 0;             /* Bitmask of phrases covered by snippet */
114755     u64 mSeen = 0;                /* Bitmask of phrases seen by BestSnippet() */
114756
114757     if( nToken>=0 ){
114758       nFToken = (nToken+nSnippet-1) / nSnippet;
114759     }else{
114760       nFToken = -1 * nToken;
114761     }
114762
114763     for(iSnip=0; iSnip<nSnippet; iSnip++){
114764       int iBestScore = -1;        /* Best score of columns checked so far */
114765       int iRead;                  /* Used to iterate through columns */
114766       SnippetFragment *pFragment = &aSnippet[iSnip];
114767
114768       memset(pFragment, 0, sizeof(*pFragment));
114769
114770       /* Loop through all columns of the table being considered for snippets.
114771       ** If the iCol argument to this function was negative, this means all
114772       ** columns of the FTS3 table. Otherwise, only column iCol is considered.
114773       */
114774       for(iRead=0; iRead<pTab->nColumn; iRead++){
114775         SnippetFragment sF;
114776         int iS;
114777         if( iCol>=0 && iRead!=iCol ) continue;
114778
114779         /* Find the best snippet of nFToken tokens in column iRead. */
114780         rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
114781         if( rc!=SQLITE_OK ){
114782           goto snippet_out;
114783         }
114784         if( iS>iBestScore ){
114785           *pFragment = sF;
114786           iBestScore = iS;
114787         }
114788       }
114789
114790       mCovered |= pFragment->covered;
114791     }
114792
114793     /* If all query phrases seen by fts3BestSnippet() are present in at least
114794     ** one of the nSnippet snippet fragments, break out of the loop.
114795     */
114796     assert( (mCovered&mSeen)==mCovered );
114797     if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
114798   }
114799
114800   assert( nFToken>0 );
114801
114802   for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
114803     rc = fts3SnippetText(pCsr, &aSnippet[i], 
114804         i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
114805     );
114806   }
114807
114808  snippet_out:
114809   if( rc!=SQLITE_OK ){
114810     sqlite3_result_error_code(pCtx, rc);
114811     sqlite3_free(res.z);
114812   }else{
114813     sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
114814   }
114815 }
114816
114817
114818 typedef struct TermOffset TermOffset;
114819 typedef struct TermOffsetCtx TermOffsetCtx;
114820
114821 struct TermOffset {
114822   char *pList;                    /* Position-list */
114823   int iPos;                       /* Position just read from pList */
114824   int iOff;                       /* Offset of this term from read positions */
114825 };
114826
114827 struct TermOffsetCtx {
114828   int iCol;                       /* Column of table to populate aTerm for */
114829   int iTerm;
114830   sqlite3_int64 iDocid;
114831   TermOffset *aTerm;
114832 };
114833
114834 /*
114835 ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
114836 */
114837 static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
114838   TermOffsetCtx *p = (TermOffsetCtx *)ctx;
114839   int nTerm;                      /* Number of tokens in phrase */
114840   int iTerm;                      /* For looping through nTerm phrase terms */
114841   char *pList;                    /* Pointer to position list for phrase */
114842   int iPos = 0;                   /* First position in position-list */
114843
114844   UNUSED_PARAMETER(iPhrase);
114845   pList = sqlite3Fts3FindPositions(pExpr, p->iDocid, p->iCol);
114846   nTerm = pExpr->pPhrase->nToken;
114847   if( pList ){
114848     fts3GetDeltaPosition(&pList, &iPos);
114849     assert( iPos>=0 );
114850   }
114851
114852   for(iTerm=0; iTerm<nTerm; iTerm++){
114853     TermOffset *pT = &p->aTerm[p->iTerm++];
114854     pT->iOff = nTerm-iTerm-1;
114855     pT->pList = pList;
114856     pT->iPos = iPos;
114857   }
114858
114859   return SQLITE_OK;
114860 }
114861
114862 /*
114863 ** Implementation of offsets() function.
114864 */
114865 SQLITE_PRIVATE void sqlite3Fts3Offsets(
114866   sqlite3_context *pCtx,          /* SQLite function call context */
114867   Fts3Cursor *pCsr                /* Cursor object */
114868 ){
114869   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
114870   sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
114871   const char *ZDUMMY;             /* Dummy argument used with xNext() */
114872   int NDUMMY;                     /* Dummy argument used with xNext() */
114873   int rc;                         /* Return Code */
114874   int nToken;                     /* Number of tokens in query */
114875   int iCol;                       /* Column currently being processed */
114876   StrBuffer res = {0, 0, 0};      /* Result string */
114877   TermOffsetCtx sCtx;             /* Context for fts3ExprTermOffsetInit() */
114878
114879   if( !pCsr->pExpr ){
114880     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
114881     return;
114882   }
114883
114884   memset(&sCtx, 0, sizeof(sCtx));
114885   assert( pCsr->isRequireSeek==0 );
114886
114887   /* Count the number of terms in the query */
114888   rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
114889   if( rc!=SQLITE_OK ) goto offsets_out;
114890
114891   /* Allocate the array of TermOffset iterators. */
114892   sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
114893   if( 0==sCtx.aTerm ){
114894     rc = SQLITE_NOMEM;
114895     goto offsets_out;
114896   }
114897   sCtx.iDocid = pCsr->iPrevId;
114898
114899   /* Loop through the table columns, appending offset information to 
114900   ** string-buffer res for each column.
114901   */
114902   for(iCol=0; iCol<pTab->nColumn; iCol++){
114903     sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
114904     int iStart;
114905     int iEnd;
114906     int iCurrent;
114907     const char *zDoc;
114908     int nDoc;
114909
114910     /* Initialize the contents of sCtx.aTerm[] for column iCol. There is 
114911     ** no way that this operation can fail, so the return code from
114912     ** fts3ExprIterate() can be discarded.
114913     */
114914     sCtx.iCol = iCol;
114915     sCtx.iTerm = 0;
114916     (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
114917
114918     /* Retreive the text stored in column iCol. If an SQL NULL is stored 
114919     ** in column iCol, jump immediately to the next iteration of the loop.
114920     ** If an OOM occurs while retrieving the data (this can happen if SQLite
114921     ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM 
114922     ** to the caller. 
114923     */
114924     zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
114925     nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
114926     if( zDoc==0 ){
114927       if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
114928         continue;
114929       }
114930       rc = SQLITE_NOMEM;
114931       goto offsets_out;
114932     }
114933
114934     /* Initialize a tokenizer iterator to iterate through column iCol. */
114935     rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
114936     if( rc!=SQLITE_OK ) goto offsets_out;
114937     pC->pTokenizer = pTab->pTokenizer;
114938
114939     rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
114940     while( rc==SQLITE_OK ){
114941       int i;                      /* Used to loop through terms */
114942       int iMinPos = 0x7FFFFFFF;   /* Position of next token */
114943       TermOffset *pTerm = 0;      /* TermOffset associated with next token */
114944
114945       for(i=0; i<nToken; i++){
114946         TermOffset *pT = &sCtx.aTerm[i];
114947         if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
114948           iMinPos = pT->iPos-pT->iOff;
114949           pTerm = pT;
114950         }
114951       }
114952
114953       if( !pTerm ){
114954         /* All offsets for this column have been gathered. */
114955         break;
114956       }else{
114957         assert( iCurrent<=iMinPos );
114958         if( 0==(0xFE&*pTerm->pList) ){
114959           pTerm->pList = 0;
114960         }else{
114961           fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
114962         }
114963         while( rc==SQLITE_OK && iCurrent<iMinPos ){
114964           rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
114965         }
114966         if( rc==SQLITE_OK ){
114967           char aBuffer[64];
114968           sqlite3_snprintf(sizeof(aBuffer), aBuffer, 
114969               "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
114970           );
114971           rc = fts3StringAppend(&res, aBuffer, -1);
114972         }else if( rc==SQLITE_DONE ){
114973           rc = SQLITE_CORRUPT;
114974         }
114975       }
114976     }
114977     if( rc==SQLITE_DONE ){
114978       rc = SQLITE_OK;
114979     }
114980
114981     pMod->xClose(pC);
114982     if( rc!=SQLITE_OK ) goto offsets_out;
114983   }
114984
114985  offsets_out:
114986   sqlite3_free(sCtx.aTerm);
114987   assert( rc!=SQLITE_DONE );
114988   if( rc!=SQLITE_OK ){
114989     sqlite3_result_error_code(pCtx,  rc);
114990     sqlite3_free(res.z);
114991   }else{
114992     sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
114993   }
114994   return;
114995 }
114996
114997 /*
114998 ** Implementation of matchinfo() function.
114999 */
115000 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *pContext, Fts3Cursor *pCsr){
115001   int rc;
115002   if( !pCsr->pExpr ){
115003     sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
115004     return;
115005   }
115006   rc = fts3GetMatchinfo(pCsr);
115007   if( rc!=SQLITE_OK ){
115008     sqlite3_result_error_code(pContext, rc);
115009   }else{
115010     Fts3Table *pTab = (Fts3Table*)pCsr->base.pVtab;
115011     int n = sizeof(u32)*(2+pCsr->aMatchinfo[0]*pCsr->aMatchinfo[1]*3);
115012     if( pTab->bHasDocsize ){
115013       n += sizeof(u32)*(1 + 2*pTab->nColumn);
115014     }
115015     sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
115016   }
115017 }
115018
115019 #endif
115020
115021 /************** End of fts3_snippet.c ****************************************/
115022 /************** Begin file rtree.c *******************************************/
115023 /*
115024 ** 2001 September 15
115025 **
115026 ** The author disclaims copyright to this source code.  In place of
115027 ** a legal notice, here is a blessing:
115028 **
115029 **    May you do good and not evil.
115030 **    May you find forgiveness for yourself and forgive others.
115031 **    May you share freely, never taking more than you give.
115032 **
115033 *************************************************************************
115034 ** This file contains code for implementations of the r-tree and r*-tree
115035 ** algorithms packaged as an SQLite virtual table module.
115036 */
115037
115038 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
115039
115040 /*
115041 ** This file contains an implementation of a couple of different variants
115042 ** of the r-tree algorithm. See the README file for further details. The 
115043 ** same data-structure is used for all, but the algorithms for insert and
115044 ** delete operations vary. The variants used are selected at compile time 
115045 ** by defining the following symbols:
115046 */
115047
115048 /* Either, both or none of the following may be set to activate 
115049 ** r*tree variant algorithms.
115050 */
115051 #define VARIANT_RSTARTREE_CHOOSESUBTREE 0
115052 #define VARIANT_RSTARTREE_REINSERT      1
115053
115054 /* 
115055 ** Exactly one of the following must be set to 1.
115056 */
115057 #define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
115058 #define VARIANT_GUTTMAN_LINEAR_SPLIT    0
115059 #define VARIANT_RSTARTREE_SPLIT         1
115060
115061 #define VARIANT_GUTTMAN_SPLIT \
115062         (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
115063
115064 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
115065   #define PickNext QuadraticPickNext
115066   #define PickSeeds QuadraticPickSeeds
115067   #define AssignCells splitNodeGuttman
115068 #endif
115069 #if VARIANT_GUTTMAN_LINEAR_SPLIT
115070   #define PickNext LinearPickNext
115071   #define PickSeeds LinearPickSeeds
115072   #define AssignCells splitNodeGuttman
115073 #endif
115074 #if VARIANT_RSTARTREE_SPLIT
115075   #define AssignCells splitNodeStartree
115076 #endif
115077
115078
115079 #ifndef SQLITE_CORE
115080   SQLITE_EXTENSION_INIT1
115081 #else
115082 #endif
115083
115084
115085 #ifndef SQLITE_AMALGAMATION
115086 typedef sqlite3_int64 i64;
115087 typedef unsigned char u8;
115088 typedef unsigned int u32;
115089 #endif
115090
115091 typedef struct Rtree Rtree;
115092 typedef struct RtreeCursor RtreeCursor;
115093 typedef struct RtreeNode RtreeNode;
115094 typedef struct RtreeCell RtreeCell;
115095 typedef struct RtreeConstraint RtreeConstraint;
115096 typedef union RtreeCoord RtreeCoord;
115097
115098 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
115099 #define RTREE_MAX_DIMENSIONS 5
115100
115101 /* Size of hash table Rtree.aHash. This hash table is not expected to
115102 ** ever contain very many entries, so a fixed number of buckets is 
115103 ** used.
115104 */
115105 #define HASHSIZE 128
115106
115107 /* 
115108 ** An rtree virtual-table object.
115109 */
115110 struct Rtree {
115111   sqlite3_vtab base;
115112   sqlite3 *db;                /* Host database connection */
115113   int iNodeSize;              /* Size in bytes of each node in the node table */
115114   int nDim;                   /* Number of dimensions */
115115   int nBytesPerCell;          /* Bytes consumed per cell */
115116   int iDepth;                 /* Current depth of the r-tree structure */
115117   char *zDb;                  /* Name of database containing r-tree table */
115118   char *zName;                /* Name of r-tree table */ 
115119   RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */ 
115120   int nBusy;                  /* Current number of users of this structure */
115121
115122   /* List of nodes removed during a CondenseTree operation. List is
115123   ** linked together via the pointer normally used for hash chains -
115124   ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree 
115125   ** headed by the node (leaf nodes have RtreeNode.iNode==0).
115126   */
115127   RtreeNode *pDeleted;
115128   int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
115129
115130   /* Statements to read/write/delete a record from xxx_node */
115131   sqlite3_stmt *pReadNode;
115132   sqlite3_stmt *pWriteNode;
115133   sqlite3_stmt *pDeleteNode;
115134
115135   /* Statements to read/write/delete a record from xxx_rowid */
115136   sqlite3_stmt *pReadRowid;
115137   sqlite3_stmt *pWriteRowid;
115138   sqlite3_stmt *pDeleteRowid;
115139
115140   /* Statements to read/write/delete a record from xxx_parent */
115141   sqlite3_stmt *pReadParent;
115142   sqlite3_stmt *pWriteParent;
115143   sqlite3_stmt *pDeleteParent;
115144
115145   int eCoordType;
115146 };
115147
115148 /* Possible values for eCoordType: */
115149 #define RTREE_COORD_REAL32 0
115150 #define RTREE_COORD_INT32  1
115151
115152 /*
115153 ** The minimum number of cells allowed for a node is a third of the 
115154 ** maximum. In Gutman's notation:
115155 **
115156 **     m = M/3
115157 **
115158 ** If an R*-tree "Reinsert" operation is required, the same number of
115159 ** cells are removed from the overfull node and reinserted into the tree.
115160 */
115161 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
115162 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
115163 #define RTREE_MAXCELLS 51
115164
115165 /* 
115166 ** An rtree cursor object.
115167 */
115168 struct RtreeCursor {
115169   sqlite3_vtab_cursor base;
115170   RtreeNode *pNode;                 /* Node cursor is currently pointing at */
115171   int iCell;                        /* Index of current cell in pNode */
115172   int iStrategy;                    /* Copy of idxNum search parameter */
115173   int nConstraint;                  /* Number of entries in aConstraint */
115174   RtreeConstraint *aConstraint;     /* Search constraints. */
115175 };
115176
115177 union RtreeCoord {
115178   float f;
115179   int i;
115180 };
115181
115182 /*
115183 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
115184 ** formatted as a double. This macro assumes that local variable pRtree points
115185 ** to the Rtree structure associated with the RtreeCoord.
115186 */
115187 #define DCOORD(coord) (                           \
115188   (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
115189     ((double)coord.f) :                           \
115190     ((double)coord.i)                             \
115191 )
115192
115193 /*
115194 ** A search constraint.
115195 */
115196 struct RtreeConstraint {
115197   int iCoord;                       /* Index of constrained coordinate */
115198   int op;                           /* Constraining operation */
115199   double rValue;                    /* Constraint value. */
115200 };
115201
115202 /* Possible values for RtreeConstraint.op */
115203 #define RTREE_EQ 0x41
115204 #define RTREE_LE 0x42
115205 #define RTREE_LT 0x43
115206 #define RTREE_GE 0x44
115207 #define RTREE_GT 0x45
115208
115209 /* 
115210 ** An rtree structure node.
115211 **
115212 ** Data format (RtreeNode.zData):
115213 **
115214 **   1. If the node is the root node (node 1), then the first 2 bytes
115215 **      of the node contain the tree depth as a big-endian integer.
115216 **      For non-root nodes, the first 2 bytes are left unused.
115217 **
115218 **   2. The next 2 bytes contain the number of entries currently 
115219 **      stored in the node.
115220 **
115221 **   3. The remainder of the node contains the node entries. Each entry
115222 **      consists of a single 8-byte integer followed by an even number
115223 **      of 4-byte coordinates. For leaf nodes the integer is the rowid
115224 **      of a record. For internal nodes it is the node number of a
115225 **      child page.
115226 */
115227 struct RtreeNode {
115228   RtreeNode *pParent;               /* Parent node */
115229   i64 iNode;
115230   int nRef;
115231   int isDirty;
115232   u8 *zData;
115233   RtreeNode *pNext;                 /* Next node in this hash chain */
115234 };
115235 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
115236
115237 /* 
115238 ** Structure to store a deserialized rtree record.
115239 */
115240 struct RtreeCell {
115241   i64 iRowid;
115242   RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
115243 };
115244
115245 #ifndef MAX
115246 # define MAX(x,y) ((x) < (y) ? (y) : (x))
115247 #endif
115248 #ifndef MIN
115249 # define MIN(x,y) ((x) > (y) ? (y) : (x))
115250 #endif
115251
115252 /*
115253 ** Functions to deserialize a 16 bit integer, 32 bit real number and
115254 ** 64 bit integer. The deserialized value is returned.
115255 */
115256 static int readInt16(u8 *p){
115257   return (p[0]<<8) + p[1];
115258 }
115259 static void readCoord(u8 *p, RtreeCoord *pCoord){
115260   u32 i = (
115261     (((u32)p[0]) << 24) + 
115262     (((u32)p[1]) << 16) + 
115263     (((u32)p[2]) <<  8) + 
115264     (((u32)p[3]) <<  0)
115265   );
115266   *(u32 *)pCoord = i;
115267 }
115268 static i64 readInt64(u8 *p){
115269   return (
115270     (((i64)p[0]) << 56) + 
115271     (((i64)p[1]) << 48) + 
115272     (((i64)p[2]) << 40) + 
115273     (((i64)p[3]) << 32) + 
115274     (((i64)p[4]) << 24) + 
115275     (((i64)p[5]) << 16) + 
115276     (((i64)p[6]) <<  8) + 
115277     (((i64)p[7]) <<  0)
115278   );
115279 }
115280
115281 /*
115282 ** Functions to serialize a 16 bit integer, 32 bit real number and
115283 ** 64 bit integer. The value returned is the number of bytes written
115284 ** to the argument buffer (always 2, 4 and 8 respectively).
115285 */
115286 static int writeInt16(u8 *p, int i){
115287   p[0] = (i>> 8)&0xFF;
115288   p[1] = (i>> 0)&0xFF;
115289   return 2;
115290 }
115291 static int writeCoord(u8 *p, RtreeCoord *pCoord){
115292   u32 i;
115293   assert( sizeof(RtreeCoord)==4 );
115294   assert( sizeof(u32)==4 );
115295   i = *(u32 *)pCoord;
115296   p[0] = (i>>24)&0xFF;
115297   p[1] = (i>>16)&0xFF;
115298   p[2] = (i>> 8)&0xFF;
115299   p[3] = (i>> 0)&0xFF;
115300   return 4;
115301 }
115302 static int writeInt64(u8 *p, i64 i){
115303   p[0] = (i>>56)&0xFF;
115304   p[1] = (i>>48)&0xFF;
115305   p[2] = (i>>40)&0xFF;
115306   p[3] = (i>>32)&0xFF;
115307   p[4] = (i>>24)&0xFF;
115308   p[5] = (i>>16)&0xFF;
115309   p[6] = (i>> 8)&0xFF;
115310   p[7] = (i>> 0)&0xFF;
115311   return 8;
115312 }
115313
115314 /*
115315 ** Increment the reference count of node p.
115316 */
115317 static void nodeReference(RtreeNode *p){
115318   if( p ){
115319     p->nRef++;
115320   }
115321 }
115322
115323 /*
115324 ** Clear the content of node p (set all bytes to 0x00).
115325 */
115326 static void nodeZero(Rtree *pRtree, RtreeNode *p){
115327   if( p ){
115328     memset(&p->zData[2], 0, pRtree->iNodeSize-2);
115329     p->isDirty = 1;
115330   }
115331 }
115332
115333 /*
115334 ** Given a node number iNode, return the corresponding key to use
115335 ** in the Rtree.aHash table.
115336 */
115337 static int nodeHash(i64 iNode){
115338   return (
115339     (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^ 
115340     (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
115341   ) % HASHSIZE;
115342 }
115343
115344 /*
115345 ** Search the node hash table for node iNode. If found, return a pointer
115346 ** to it. Otherwise, return 0.
115347 */
115348 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
115349   RtreeNode *p;
115350   assert( iNode!=0 );
115351   for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
115352   return p;
115353 }
115354
115355 /*
115356 ** Add node pNode to the node hash table.
115357 */
115358 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
115359   if( pNode ){
115360     int iHash;
115361     assert( pNode->pNext==0 );
115362     iHash = nodeHash(pNode->iNode);
115363     pNode->pNext = pRtree->aHash[iHash];
115364     pRtree->aHash[iHash] = pNode;
115365   }
115366 }
115367
115368 /*
115369 ** Remove node pNode from the node hash table.
115370 */
115371 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
115372   RtreeNode **pp;
115373   if( pNode->iNode!=0 ){
115374     pp = &pRtree->aHash[nodeHash(pNode->iNode)];
115375     for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
115376     *pp = pNode->pNext;
115377     pNode->pNext = 0;
115378   }
115379 }
115380
115381 /*
115382 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
115383 ** indicating that node has not yet been assigned a node number. It is
115384 ** assigned a node number when nodeWrite() is called to write the
115385 ** node contents out to the database.
115386 */
115387 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent, int zero){
115388   RtreeNode *pNode;
115389   pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
115390   if( pNode ){
115391     memset(pNode, 0, sizeof(RtreeNode) + (zero?pRtree->iNodeSize:0));
115392     pNode->zData = (u8 *)&pNode[1];
115393     pNode->nRef = 1;
115394     pNode->pParent = pParent;
115395     pNode->isDirty = 1;
115396     nodeReference(pParent);
115397   }
115398   return pNode;
115399 }
115400
115401 /*
115402 ** Obtain a reference to an r-tree node.
115403 */
115404 static int
115405 nodeAcquire(
115406   Rtree *pRtree,             /* R-tree structure */
115407   i64 iNode,                 /* Node number to load */
115408   RtreeNode *pParent,        /* Either the parent node or NULL */
115409   RtreeNode **ppNode         /* OUT: Acquired node */
115410 ){
115411   int rc;
115412   RtreeNode *pNode;
115413
115414   /* Check if the requested node is already in the hash table. If so,
115415   ** increase its reference count and return it.
115416   */
115417   if( (pNode = nodeHashLookup(pRtree, iNode)) ){
115418     assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
115419     if( pParent && !pNode->pParent ){
115420       nodeReference(pParent);
115421       pNode->pParent = pParent;
115422     }
115423     pNode->nRef++;
115424     *ppNode = pNode;
115425     return SQLITE_OK;
115426   }
115427
115428   pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
115429   if( !pNode ){
115430     *ppNode = 0;
115431     return SQLITE_NOMEM;
115432   }
115433   pNode->pParent = pParent;
115434   pNode->zData = (u8 *)&pNode[1];
115435   pNode->nRef = 1;
115436   pNode->iNode = iNode;
115437   pNode->isDirty = 0;
115438   pNode->pNext = 0;
115439
115440   sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
115441   rc = sqlite3_step(pRtree->pReadNode);
115442   if( rc==SQLITE_ROW ){
115443     const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
115444     assert( sqlite3_column_bytes(pRtree->pReadNode, 0)==pRtree->iNodeSize );
115445     memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
115446     nodeReference(pParent);
115447   }else{
115448     sqlite3_free(pNode);
115449     pNode = 0;
115450   }
115451
115452   *ppNode = pNode;
115453   rc = sqlite3_reset(pRtree->pReadNode);
115454
115455   if( rc==SQLITE_OK && iNode==1 ){
115456     pRtree->iDepth = readInt16(pNode->zData);
115457   }
115458
115459   assert( (rc==SQLITE_OK && pNode) || (pNode==0 && rc!=SQLITE_OK) );
115460   nodeHashInsert(pRtree, pNode);
115461
115462   return rc;
115463 }
115464
115465 /*
115466 ** Overwrite cell iCell of node pNode with the contents of pCell.
115467 */
115468 static void nodeOverwriteCell(
115469   Rtree *pRtree, 
115470   RtreeNode *pNode,  
115471   RtreeCell *pCell, 
115472   int iCell
115473 ){
115474   int ii;
115475   u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
115476   p += writeInt64(p, pCell->iRowid);
115477   for(ii=0; ii<(pRtree->nDim*2); ii++){
115478     p += writeCoord(p, &pCell->aCoord[ii]);
115479   }
115480   pNode->isDirty = 1;
115481 }
115482
115483 /*
115484 ** Remove cell the cell with index iCell from node pNode.
115485 */
115486 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
115487   u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
115488   u8 *pSrc = &pDst[pRtree->nBytesPerCell];
115489   int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
115490   memmove(pDst, pSrc, nByte);
115491   writeInt16(&pNode->zData[2], NCELL(pNode)-1);
115492   pNode->isDirty = 1;
115493 }
115494
115495 /*
115496 ** Insert the contents of cell pCell into node pNode. If the insert
115497 ** is successful, return SQLITE_OK.
115498 **
115499 ** If there is not enough free space in pNode, return SQLITE_FULL.
115500 */
115501 static int
115502 nodeInsertCell(
115503   Rtree *pRtree, 
115504   RtreeNode *pNode, 
115505   RtreeCell *pCell 
115506 ){
115507   int nCell;                    /* Current number of cells in pNode */
115508   int nMaxCell;                 /* Maximum number of cells for pNode */
115509
115510   nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
115511   nCell = NCELL(pNode);
115512
115513   assert(nCell<=nMaxCell);
115514
115515   if( nCell<nMaxCell ){
115516     nodeOverwriteCell(pRtree, pNode, pCell, nCell);
115517     writeInt16(&pNode->zData[2], nCell+1);
115518     pNode->isDirty = 1;
115519   }
115520
115521   return (nCell==nMaxCell);
115522 }
115523
115524 /*
115525 ** If the node is dirty, write it out to the database.
115526 */
115527 static int
115528 nodeWrite(Rtree *pRtree, RtreeNode *pNode){
115529   int rc = SQLITE_OK;
115530   if( pNode->isDirty ){
115531     sqlite3_stmt *p = pRtree->pWriteNode;
115532     if( pNode->iNode ){
115533       sqlite3_bind_int64(p, 1, pNode->iNode);
115534     }else{
115535       sqlite3_bind_null(p, 1);
115536     }
115537     sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
115538     sqlite3_step(p);
115539     pNode->isDirty = 0;
115540     rc = sqlite3_reset(p);
115541     if( pNode->iNode==0 && rc==SQLITE_OK ){
115542       pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
115543       nodeHashInsert(pRtree, pNode);
115544     }
115545   }
115546   return rc;
115547 }
115548
115549 /*
115550 ** Release a reference to a node. If the node is dirty and the reference
115551 ** count drops to zero, the node data is written to the database.
115552 */
115553 static int
115554 nodeRelease(Rtree *pRtree, RtreeNode *pNode){
115555   int rc = SQLITE_OK;
115556   if( pNode ){
115557     assert( pNode->nRef>0 );
115558     pNode->nRef--;
115559     if( pNode->nRef==0 ){
115560       if( pNode->iNode==1 ){
115561         pRtree->iDepth = -1;
115562       }
115563       if( pNode->pParent ){
115564         rc = nodeRelease(pRtree, pNode->pParent);
115565       }
115566       if( rc==SQLITE_OK ){
115567         rc = nodeWrite(pRtree, pNode);
115568       }
115569       nodeHashDelete(pRtree, pNode);
115570       sqlite3_free(pNode);
115571     }
115572   }
115573   return rc;
115574 }
115575
115576 /*
115577 ** Return the 64-bit integer value associated with cell iCell of
115578 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
115579 ** an internal node, then the 64-bit integer is a child page number.
115580 */
115581 static i64 nodeGetRowid(
115582   Rtree *pRtree, 
115583   RtreeNode *pNode, 
115584   int iCell
115585 ){
115586   assert( iCell<NCELL(pNode) );
115587   return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
115588 }
115589
115590 /*
115591 ** Return coordinate iCoord from cell iCell in node pNode.
115592 */
115593 static void nodeGetCoord(
115594   Rtree *pRtree, 
115595   RtreeNode *pNode, 
115596   int iCell,
115597   int iCoord,
115598   RtreeCoord *pCoord           /* Space to write result to */
115599 ){
115600   readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
115601 }
115602
115603 /*
115604 ** Deserialize cell iCell of node pNode. Populate the structure pointed
115605 ** to by pCell with the results.
115606 */
115607 static void nodeGetCell(
115608   Rtree *pRtree, 
115609   RtreeNode *pNode, 
115610   int iCell,
115611   RtreeCell *pCell
115612 ){
115613   int ii;
115614   pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
115615   for(ii=0; ii<pRtree->nDim*2; ii++){
115616     nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
115617   }
115618 }
115619
115620
115621 /* Forward declaration for the function that does the work of
115622 ** the virtual table module xCreate() and xConnect() methods.
115623 */
115624 static int rtreeInit(
115625   sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
115626 );
115627
115628 /* 
115629 ** Rtree virtual table module xCreate method.
115630 */
115631 static int rtreeCreate(
115632   sqlite3 *db,
115633   void *pAux,
115634   int argc, const char *const*argv,
115635   sqlite3_vtab **ppVtab,
115636   char **pzErr
115637 ){
115638   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
115639 }
115640
115641 /* 
115642 ** Rtree virtual table module xConnect method.
115643 */
115644 static int rtreeConnect(
115645   sqlite3 *db,
115646   void *pAux,
115647   int argc, const char *const*argv,
115648   sqlite3_vtab **ppVtab,
115649   char **pzErr
115650 ){
115651   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
115652 }
115653
115654 /*
115655 ** Increment the r-tree reference count.
115656 */
115657 static void rtreeReference(Rtree *pRtree){
115658   pRtree->nBusy++;
115659 }
115660
115661 /*
115662 ** Decrement the r-tree reference count. When the reference count reaches
115663 ** zero the structure is deleted.
115664 */
115665 static void rtreeRelease(Rtree *pRtree){
115666   pRtree->nBusy--;
115667   if( pRtree->nBusy==0 ){
115668     sqlite3_finalize(pRtree->pReadNode);
115669     sqlite3_finalize(pRtree->pWriteNode);
115670     sqlite3_finalize(pRtree->pDeleteNode);
115671     sqlite3_finalize(pRtree->pReadRowid);
115672     sqlite3_finalize(pRtree->pWriteRowid);
115673     sqlite3_finalize(pRtree->pDeleteRowid);
115674     sqlite3_finalize(pRtree->pReadParent);
115675     sqlite3_finalize(pRtree->pWriteParent);
115676     sqlite3_finalize(pRtree->pDeleteParent);
115677     sqlite3_free(pRtree);
115678   }
115679 }
115680
115681 /* 
115682 ** Rtree virtual table module xDisconnect method.
115683 */
115684 static int rtreeDisconnect(sqlite3_vtab *pVtab){
115685   rtreeRelease((Rtree *)pVtab);
115686   return SQLITE_OK;
115687 }
115688
115689 /* 
115690 ** Rtree virtual table module xDestroy method.
115691 */
115692 static int rtreeDestroy(sqlite3_vtab *pVtab){
115693   Rtree *pRtree = (Rtree *)pVtab;
115694   int rc;
115695   char *zCreate = sqlite3_mprintf(
115696     "DROP TABLE '%q'.'%q_node';"
115697     "DROP TABLE '%q'.'%q_rowid';"
115698     "DROP TABLE '%q'.'%q_parent';",
115699     pRtree->zDb, pRtree->zName, 
115700     pRtree->zDb, pRtree->zName,
115701     pRtree->zDb, pRtree->zName
115702   );
115703   if( !zCreate ){
115704     rc = SQLITE_NOMEM;
115705   }else{
115706     rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
115707     sqlite3_free(zCreate);
115708   }
115709   if( rc==SQLITE_OK ){
115710     rtreeRelease(pRtree);
115711   }
115712
115713   return rc;
115714 }
115715
115716 /* 
115717 ** Rtree virtual table module xOpen method.
115718 */
115719 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
115720   int rc = SQLITE_NOMEM;
115721   RtreeCursor *pCsr;
115722
115723   pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
115724   if( pCsr ){
115725     memset(pCsr, 0, sizeof(RtreeCursor));
115726     pCsr->base.pVtab = pVTab;
115727     rc = SQLITE_OK;
115728   }
115729   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
115730
115731   return rc;
115732 }
115733
115734 /* 
115735 ** Rtree virtual table module xClose method.
115736 */
115737 static int rtreeClose(sqlite3_vtab_cursor *cur){
115738   Rtree *pRtree = (Rtree *)(cur->pVtab);
115739   int rc;
115740   RtreeCursor *pCsr = (RtreeCursor *)cur;
115741   sqlite3_free(pCsr->aConstraint);
115742   rc = nodeRelease(pRtree, pCsr->pNode);
115743   sqlite3_free(pCsr);
115744   return rc;
115745 }
115746
115747 /*
115748 ** Rtree virtual table module xEof method.
115749 **
115750 ** Return non-zero if the cursor does not currently point to a valid 
115751 ** record (i.e if the scan has finished), or zero otherwise.
115752 */
115753 static int rtreeEof(sqlite3_vtab_cursor *cur){
115754   RtreeCursor *pCsr = (RtreeCursor *)cur;
115755   return (pCsr->pNode==0);
115756 }
115757
115758 /* 
115759 ** Cursor pCursor currently points to a cell in a non-leaf page.
115760 ** Return true if the sub-tree headed by the cell is filtered
115761 ** (excluded) by the constraints in the pCursor->aConstraint[] 
115762 ** array, or false otherwise.
115763 */
115764 static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor){
115765   RtreeCell cell;
115766   int ii;
115767   int bRes = 0;
115768
115769   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
115770   for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
115771     RtreeConstraint *p = &pCursor->aConstraint[ii];
115772     double cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
115773     double cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
115774
115775     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
115776         || p->op==RTREE_GT || p->op==RTREE_EQ
115777     );
115778
115779     switch( p->op ){
115780       case RTREE_LE: case RTREE_LT: bRes = p->rValue<cell_min; break;
115781       case RTREE_GE: case RTREE_GT: bRes = p->rValue>cell_max; break;
115782       case RTREE_EQ: 
115783         bRes = (p->rValue>cell_max || p->rValue<cell_min);
115784         break;
115785     }
115786   }
115787
115788   return bRes;
115789 }
115790
115791 /* 
115792 ** Return true if the cell that cursor pCursor currently points to
115793 ** would be filtered (excluded) by the constraints in the 
115794 ** pCursor->aConstraint[] array, or false otherwise.
115795 **
115796 ** This function assumes that the cell is part of a leaf node.
115797 */
115798 static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor){
115799   RtreeCell cell;
115800   int ii;
115801
115802   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
115803   for(ii=0; ii<pCursor->nConstraint; ii++){
115804     RtreeConstraint *p = &pCursor->aConstraint[ii];
115805     double coord = DCOORD(cell.aCoord[p->iCoord]);
115806     int res;
115807     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
115808         || p->op==RTREE_GT || p->op==RTREE_EQ
115809     );
115810     switch( p->op ){
115811       case RTREE_LE: res = (coord<=p->rValue); break;
115812       case RTREE_LT: res = (coord<p->rValue);  break;
115813       case RTREE_GE: res = (coord>=p->rValue); break;
115814       case RTREE_GT: res = (coord>p->rValue);  break;
115815       case RTREE_EQ: res = (coord==p->rValue); break;
115816     }
115817
115818     if( !res ) return 1;
115819   }
115820
115821   return 0;
115822 }
115823
115824 /*
115825 ** Cursor pCursor currently points at a node that heads a sub-tree of
115826 ** height iHeight (if iHeight==0, then the node is a leaf). Descend
115827 ** to point to the left-most cell of the sub-tree that matches the 
115828 ** configured constraints.
115829 */
115830 static int descendToCell(
115831   Rtree *pRtree, 
115832   RtreeCursor *pCursor, 
115833   int iHeight,
115834   int *pEof                 /* OUT: Set to true if cannot descend */
115835 ){
115836   int isEof;
115837   int rc;
115838   int ii;
115839   RtreeNode *pChild;
115840   sqlite3_int64 iRowid;
115841
115842   RtreeNode *pSavedNode = pCursor->pNode;
115843   int iSavedCell = pCursor->iCell;
115844
115845   assert( iHeight>=0 );
115846
115847   if( iHeight==0 ){
115848     isEof = testRtreeEntry(pRtree, pCursor);
115849   }else{
115850     isEof = testRtreeCell(pRtree, pCursor);
115851   }
115852   if( isEof || iHeight==0 ){
115853     *pEof = isEof;
115854     return SQLITE_OK;
115855   }
115856
115857   iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
115858   rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
115859   if( rc!=SQLITE_OK ){
115860     return rc;
115861   }
115862
115863   nodeRelease(pRtree, pCursor->pNode);
115864   pCursor->pNode = pChild;
115865   isEof = 1;
115866   for(ii=0; isEof && ii<NCELL(pChild); ii++){
115867     pCursor->iCell = ii;
115868     rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
115869     if( rc!=SQLITE_OK ){
115870       return rc;
115871     }
115872   }
115873
115874   if( isEof ){
115875     assert( pCursor->pNode==pChild );
115876     nodeReference(pSavedNode);
115877     nodeRelease(pRtree, pChild);
115878     pCursor->pNode = pSavedNode;
115879     pCursor->iCell = iSavedCell;
115880   }
115881
115882   *pEof = isEof;
115883   return SQLITE_OK;
115884 }
115885
115886 /*
115887 ** One of the cells in node pNode is guaranteed to have a 64-bit 
115888 ** integer value equal to iRowid. Return the index of this cell.
115889 */
115890 static int nodeRowidIndex(Rtree *pRtree, RtreeNode *pNode, i64 iRowid){
115891   int ii;
115892   for(ii=0; nodeGetRowid(pRtree, pNode, ii)!=iRowid; ii++){
115893     assert( ii<(NCELL(pNode)-1) );
115894   }
115895   return ii;
115896 }
115897
115898 /*
115899 ** Return the index of the cell containing a pointer to node pNode
115900 ** in its parent. If pNode is the root node, return -1.
115901 */
115902 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode){
115903   RtreeNode *pParent = pNode->pParent;
115904   if( pParent ){
115905     return nodeRowidIndex(pRtree, pParent, pNode->iNode);
115906   }
115907   return -1;
115908 }
115909
115910 /* 
115911 ** Rtree virtual table module xNext method.
115912 */
115913 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
115914   Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
115915   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
115916   int rc = SQLITE_OK;
115917
115918   if( pCsr->iStrategy==1 ){
115919     /* This "scan" is a direct lookup by rowid. There is no next entry. */
115920     nodeRelease(pRtree, pCsr->pNode);
115921     pCsr->pNode = 0;
115922   }
115923
115924   else if( pCsr->pNode ){
115925     /* Move to the next entry that matches the configured constraints. */
115926     int iHeight = 0;
115927     while( pCsr->pNode ){
115928       RtreeNode *pNode = pCsr->pNode;
115929       int nCell = NCELL(pNode);
115930       for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
115931         int isEof;
115932         rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
115933         if( rc!=SQLITE_OK || !isEof ){
115934           return rc;
115935         }
115936       }
115937       pCsr->pNode = pNode->pParent;
115938       pCsr->iCell = nodeParentIndex(pRtree, pNode);
115939       nodeReference(pCsr->pNode);
115940       nodeRelease(pRtree, pNode);
115941       iHeight++;
115942     }
115943   }
115944
115945   return rc;
115946 }
115947
115948 /* 
115949 ** Rtree virtual table module xRowid method.
115950 */
115951 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
115952   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
115953   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
115954
115955   assert(pCsr->pNode);
115956   *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
115957
115958   return SQLITE_OK;
115959 }
115960
115961 /* 
115962 ** Rtree virtual table module xColumn method.
115963 */
115964 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
115965   Rtree *pRtree = (Rtree *)cur->pVtab;
115966   RtreeCursor *pCsr = (RtreeCursor *)cur;
115967
115968   if( i==0 ){
115969     i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
115970     sqlite3_result_int64(ctx, iRowid);
115971   }else{
115972     RtreeCoord c;
115973     nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
115974     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
115975       sqlite3_result_double(ctx, c.f);
115976     }else{
115977       assert( pRtree->eCoordType==RTREE_COORD_INT32 );
115978       sqlite3_result_int(ctx, c.i);
115979     }
115980   }
115981
115982   return SQLITE_OK;
115983 }
115984
115985 /* 
115986 ** Use nodeAcquire() to obtain the leaf node containing the record with 
115987 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
115988 ** return SQLITE_OK. If there is no such record in the table, set
115989 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
115990 ** to zero and return an SQLite error code.
115991 */
115992 static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
115993   int rc;
115994   *ppLeaf = 0;
115995   sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
115996   if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
115997     i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
115998     rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
115999     sqlite3_reset(pRtree->pReadRowid);
116000   }else{
116001     rc = sqlite3_reset(pRtree->pReadRowid);
116002   }
116003   return rc;
116004 }
116005
116006
116007 /* 
116008 ** Rtree virtual table module xFilter method.
116009 */
116010 static int rtreeFilter(
116011   sqlite3_vtab_cursor *pVtabCursor, 
116012   int idxNum, const char *idxStr,
116013   int argc, sqlite3_value **argv
116014 ){
116015   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
116016   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
116017
116018   RtreeNode *pRoot = 0;
116019   int ii;
116020   int rc = SQLITE_OK;
116021
116022   rtreeReference(pRtree);
116023
116024   sqlite3_free(pCsr->aConstraint);
116025   pCsr->aConstraint = 0;
116026   pCsr->iStrategy = idxNum;
116027
116028   if( idxNum==1 ){
116029     /* Special case - lookup by rowid. */
116030     RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
116031     i64 iRowid = sqlite3_value_int64(argv[0]);
116032     rc = findLeafNode(pRtree, iRowid, &pLeaf);
116033     pCsr->pNode = pLeaf; 
116034     if( pLeaf && rc==SQLITE_OK ){
116035       pCsr->iCell = nodeRowidIndex(pRtree, pLeaf, iRowid);
116036     }
116037   }else{
116038     /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array 
116039     ** with the configured constraints. 
116040     */
116041     if( argc>0 ){
116042       pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
116043       pCsr->nConstraint = argc;
116044       if( !pCsr->aConstraint ){
116045         rc = SQLITE_NOMEM;
116046       }else{
116047         assert( (idxStr==0 && argc==0) || strlen(idxStr)==argc*2 );
116048         for(ii=0; ii<argc; ii++){
116049           RtreeConstraint *p = &pCsr->aConstraint[ii];
116050           p->op = idxStr[ii*2];
116051           p->iCoord = idxStr[ii*2+1]-'a';
116052           p->rValue = sqlite3_value_double(argv[ii]);
116053         }
116054       }
116055     }
116056   
116057     if( rc==SQLITE_OK ){
116058       pCsr->pNode = 0;
116059       rc = nodeAcquire(pRtree, 1, 0, &pRoot);
116060     }
116061     if( rc==SQLITE_OK ){
116062       int isEof = 1;
116063       int nCell = NCELL(pRoot);
116064       pCsr->pNode = pRoot;
116065       for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
116066         assert( pCsr->pNode==pRoot );
116067         rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
116068         if( !isEof ){
116069           break;
116070         }
116071       }
116072       if( rc==SQLITE_OK && isEof ){
116073         assert( pCsr->pNode==pRoot );
116074         nodeRelease(pRtree, pRoot);
116075         pCsr->pNode = 0;
116076       }
116077       assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
116078     }
116079   }
116080
116081   rtreeRelease(pRtree);
116082   return rc;
116083 }
116084
116085 /*
116086 ** Rtree virtual table module xBestIndex method. There are three
116087 ** table scan strategies to choose from (in order from most to 
116088 ** least desirable):
116089 **
116090 **   idxNum     idxStr        Strategy
116091 **   ------------------------------------------------
116092 **     1        Unused        Direct lookup by rowid.
116093 **     2        See below     R-tree query.
116094 **     3        Unused        Full table scan.
116095 **   ------------------------------------------------
116096 **
116097 ** If strategy 1 or 3 is used, then idxStr is not meaningful. If strategy
116098 ** 2 is used, idxStr is formatted to contain 2 bytes for each 
116099 ** constraint used. The first two bytes of idxStr correspond to 
116100 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
116101 ** (argvIndex==1) etc.
116102 **
116103 ** The first of each pair of bytes in idxStr identifies the constraint
116104 ** operator as follows:
116105 **
116106 **   Operator    Byte Value
116107 **   ----------------------
116108 **      =        0x41 ('A')
116109 **     <=        0x42 ('B')
116110 **      <        0x43 ('C')
116111 **     >=        0x44 ('D')
116112 **      >        0x45 ('E')
116113 **   ----------------------
116114 **
116115 ** The second of each pair of bytes identifies the coordinate column
116116 ** to which the constraint applies. The leftmost coordinate column
116117 ** is 'a', the second from the left 'b' etc.
116118 */
116119 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
116120   int rc = SQLITE_OK;
116121   int ii, cCol;
116122
116123   int iIdx = 0;
116124   char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
116125   memset(zIdxStr, 0, sizeof(zIdxStr));
116126
116127   assert( pIdxInfo->idxStr==0 );
116128   for(ii=0; ii<pIdxInfo->nConstraint; ii++){
116129     struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
116130
116131     if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
116132       /* We have an equality constraint on the rowid. Use strategy 1. */
116133       int jj;
116134       for(jj=0; jj<ii; jj++){
116135         pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
116136         pIdxInfo->aConstraintUsage[jj].omit = 0;
116137       }
116138       pIdxInfo->idxNum = 1;
116139       pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
116140       pIdxInfo->aConstraintUsage[jj].omit = 1;
116141
116142       /* This strategy involves a two rowid lookups on an B-Tree structures
116143       ** and then a linear search of an R-Tree node. This should be 
116144       ** considered almost as quick as a direct rowid lookup (for which 
116145       ** sqlite uses an internal cost of 0.0).
116146       */ 
116147       pIdxInfo->estimatedCost = 10.0;
116148       return SQLITE_OK;
116149     }
116150
116151     if( p->usable && p->iColumn>0 ){
116152       u8 op = 0;
116153       switch( p->op ){
116154         case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
116155         case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
116156         case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
116157         case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
116158         case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
116159       }
116160       if( op ){
116161         /* Make sure this particular constraint has not been used before.
116162         ** If it has been used before, ignore it.
116163         **
116164         ** A <= or < can be used if there is a prior >= or >.
116165         ** A >= or > can be used if there is a prior < or <=.
116166         ** A <= or < is disqualified if there is a prior <=, <, or ==.
116167         ** A >= or > is disqualified if there is a prior >=, >, or ==.
116168         ** A == is disqualifed if there is any prior constraint.
116169         */
116170         int j, opmsk;
116171         static const unsigned char compatible[] = { 0, 0, 1, 1, 2, 2 };
116172         assert( compatible[RTREE_EQ & 7]==0 );
116173         assert( compatible[RTREE_LT & 7]==1 );
116174         assert( compatible[RTREE_LE & 7]==1 );
116175         assert( compatible[RTREE_GT & 7]==2 );
116176         assert( compatible[RTREE_GE & 7]==2 );
116177         cCol = p->iColumn - 1 + 'a';
116178         opmsk = compatible[op & 7];
116179         for(j=0; j<iIdx; j+=2){
116180           if( zIdxStr[j+1]==cCol && (compatible[zIdxStr[j] & 7] & opmsk)!=0 ){
116181             op = 0;
116182             break;
116183           }
116184         }
116185       }
116186       if( op ){
116187         assert( iIdx<sizeof(zIdxStr)-1 );
116188         zIdxStr[iIdx++] = op;
116189         zIdxStr[iIdx++] = cCol;
116190         pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
116191         pIdxInfo->aConstraintUsage[ii].omit = 1;
116192       }
116193     }
116194   }
116195
116196   pIdxInfo->idxNum = 2;
116197   pIdxInfo->needToFreeIdxStr = 1;
116198   if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
116199     return SQLITE_NOMEM;
116200   }
116201   assert( iIdx>=0 );
116202   pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
116203   return rc;
116204 }
116205
116206 /*
116207 ** Return the N-dimensional volumn of the cell stored in *p.
116208 */
116209 static float cellArea(Rtree *pRtree, RtreeCell *p){
116210   float area = 1.0;
116211   int ii;
116212   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
116213     area = area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
116214   }
116215   return area;
116216 }
116217
116218 /*
116219 ** Return the margin length of cell p. The margin length is the sum
116220 ** of the objects size in each dimension.
116221 */
116222 static float cellMargin(Rtree *pRtree, RtreeCell *p){
116223   float margin = 0.0;
116224   int ii;
116225   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
116226     margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
116227   }
116228   return margin;
116229 }
116230
116231 /*
116232 ** Store the union of cells p1 and p2 in p1.
116233 */
116234 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
116235   int ii;
116236   if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
116237     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
116238       p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
116239       p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
116240     }
116241   }else{
116242     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
116243       p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
116244       p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
116245     }
116246   }
116247 }
116248
116249 /*
116250 ** Return true if the area covered by p2 is a subset of the area covered
116251 ** by p1. False otherwise.
116252 */
116253 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
116254   int ii;
116255   int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
116256   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
116257     RtreeCoord *a1 = &p1->aCoord[ii];
116258     RtreeCoord *a2 = &p2->aCoord[ii];
116259     if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f)) 
116260      || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i)) 
116261     ){
116262       return 0;
116263     }
116264   }
116265   return 1;
116266 }
116267
116268 /*
116269 ** Return the amount cell p would grow by if it were unioned with pCell.
116270 */
116271 static float cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
116272   float area;
116273   RtreeCell cell;
116274   memcpy(&cell, p, sizeof(RtreeCell));
116275   area = cellArea(pRtree, &cell);
116276   cellUnion(pRtree, &cell, pCell);
116277   return (cellArea(pRtree, &cell)-area);
116278 }
116279
116280 #if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
116281 static float cellOverlap(
116282   Rtree *pRtree, 
116283   RtreeCell *p, 
116284   RtreeCell *aCell, 
116285   int nCell, 
116286   int iExclude
116287 ){
116288   int ii;
116289   float overlap = 0.0;
116290   for(ii=0; ii<nCell; ii++){
116291     if( ii!=iExclude ){
116292       int jj;
116293       float o = 1.0;
116294       for(jj=0; jj<(pRtree->nDim*2); jj+=2){
116295         double x1;
116296         double x2;
116297
116298         x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
116299         x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
116300
116301         if( x2<x1 ){
116302           o = 0.0;
116303           break;
116304         }else{
116305           o = o * (x2-x1);
116306         }
116307       }
116308       overlap += o;
116309     }
116310   }
116311   return overlap;
116312 }
116313 #endif
116314
116315 #if VARIANT_RSTARTREE_CHOOSESUBTREE
116316 static float cellOverlapEnlargement(
116317   Rtree *pRtree, 
116318   RtreeCell *p, 
116319   RtreeCell *pInsert, 
116320   RtreeCell *aCell, 
116321   int nCell, 
116322   int iExclude
116323 ){
116324   float before;
116325   float after;
116326   before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
116327   cellUnion(pRtree, p, pInsert);
116328   after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
116329   return after-before;
116330 }
116331 #endif
116332
116333
116334 /*
116335 ** This function implements the ChooseLeaf algorithm from Gutman[84].
116336 ** ChooseSubTree in r*tree terminology.
116337 */
116338 static int ChooseLeaf(
116339   Rtree *pRtree,               /* Rtree table */
116340   RtreeCell *pCell,            /* Cell to insert into rtree */
116341   int iHeight,                 /* Height of sub-tree rooted at pCell */
116342   RtreeNode **ppLeaf           /* OUT: Selected leaf page */
116343 ){
116344   int rc;
116345   int ii;
116346   RtreeNode *pNode;
116347   rc = nodeAcquire(pRtree, 1, 0, &pNode);
116348
116349   for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
116350     int iCell;
116351     sqlite3_int64 iBest;
116352
116353     float fMinGrowth;
116354     float fMinArea;
116355     float fMinOverlap;
116356
116357     int nCell = NCELL(pNode);
116358     RtreeCell cell;
116359     RtreeNode *pChild;
116360
116361     RtreeCell *aCell = 0;
116362
116363 #if VARIANT_RSTARTREE_CHOOSESUBTREE
116364     if( ii==(pRtree->iDepth-1) ){
116365       int jj;
116366       aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
116367       if( !aCell ){
116368         rc = SQLITE_NOMEM;
116369         nodeRelease(pRtree, pNode);
116370         pNode = 0;
116371         continue;
116372       }
116373       for(jj=0; jj<nCell; jj++){
116374         nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
116375       }
116376     }
116377 #endif
116378
116379     /* Select the child node which will be enlarged the least if pCell
116380     ** is inserted into it. Resolve ties by choosing the entry with
116381     ** the smallest area.
116382     */
116383     for(iCell=0; iCell<nCell; iCell++){
116384       float growth;
116385       float area;
116386       float overlap = 0.0;
116387       nodeGetCell(pRtree, pNode, iCell, &cell);
116388       growth = cellGrowth(pRtree, &cell, pCell);
116389       area = cellArea(pRtree, &cell);
116390 #if VARIANT_RSTARTREE_CHOOSESUBTREE
116391       if( ii==(pRtree->iDepth-1) ){
116392         overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
116393       }
116394 #endif
116395       if( (iCell==0) 
116396        || (overlap<fMinOverlap) 
116397        || (overlap==fMinOverlap && growth<fMinGrowth)
116398        || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
116399       ){
116400         fMinOverlap = overlap;
116401         fMinGrowth = growth;
116402         fMinArea = area;
116403         iBest = cell.iRowid;
116404       }
116405     }
116406
116407     sqlite3_free(aCell);
116408     rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
116409     nodeRelease(pRtree, pNode);
116410     pNode = pChild;
116411   }
116412
116413   *ppLeaf = pNode;
116414   return rc;
116415 }
116416
116417 /*
116418 ** A cell with the same content as pCell has just been inserted into
116419 ** the node pNode. This function updates the bounding box cells in
116420 ** all ancestor elements.
116421 */
116422 static void AdjustTree(
116423   Rtree *pRtree,                    /* Rtree table */
116424   RtreeNode *pNode,                 /* Adjust ancestry of this node. */
116425   RtreeCell *pCell                  /* This cell was just inserted */
116426 ){
116427   RtreeNode *p = pNode;
116428   while( p->pParent ){
116429     RtreeCell cell;
116430     RtreeNode *pParent = p->pParent;
116431     int iCell = nodeParentIndex(pRtree, p);
116432
116433     nodeGetCell(pRtree, pParent, iCell, &cell);
116434     if( !cellContains(pRtree, &cell, pCell) ){
116435       cellUnion(pRtree, &cell, pCell);
116436       nodeOverwriteCell(pRtree, pParent, &cell, iCell);
116437     }
116438  
116439     p = pParent;
116440   }
116441 }
116442
116443 /*
116444 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
116445 */
116446 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
116447   sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
116448   sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
116449   sqlite3_step(pRtree->pWriteRowid);
116450   return sqlite3_reset(pRtree->pWriteRowid);
116451 }
116452
116453 /*
116454 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
116455 */
116456 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
116457   sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
116458   sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
116459   sqlite3_step(pRtree->pWriteParent);
116460   return sqlite3_reset(pRtree->pWriteParent);
116461 }
116462
116463 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
116464
116465 #if VARIANT_GUTTMAN_LINEAR_SPLIT
116466 /*
116467 ** Implementation of the linear variant of the PickNext() function from
116468 ** Guttman[84].
116469 */
116470 static RtreeCell *LinearPickNext(
116471   Rtree *pRtree,
116472   RtreeCell *aCell, 
116473   int nCell, 
116474   RtreeCell *pLeftBox, 
116475   RtreeCell *pRightBox,
116476   int *aiUsed
116477 ){
116478   int ii;
116479   for(ii=0; aiUsed[ii]; ii++);
116480   aiUsed[ii] = 1;
116481   return &aCell[ii];
116482 }
116483
116484 /*
116485 ** Implementation of the linear variant of the PickSeeds() function from
116486 ** Guttman[84].
116487 */
116488 static void LinearPickSeeds(
116489   Rtree *pRtree,
116490   RtreeCell *aCell, 
116491   int nCell, 
116492   int *piLeftSeed, 
116493   int *piRightSeed
116494 ){
116495   int i;
116496   int iLeftSeed = 0;
116497   int iRightSeed = 1;
116498   float maxNormalInnerWidth = 0.0;
116499
116500   /* Pick two "seed" cells from the array of cells. The algorithm used
116501   ** here is the LinearPickSeeds algorithm from Gutman[1984]. The 
116502   ** indices of the two seed cells in the array are stored in local
116503   ** variables iLeftSeek and iRightSeed.
116504   */
116505   for(i=0; i<pRtree->nDim; i++){
116506     float x1 = DCOORD(aCell[0].aCoord[i*2]);
116507     float x2 = DCOORD(aCell[0].aCoord[i*2+1]);
116508     float x3 = x1;
116509     float x4 = x2;
116510     int jj;
116511
116512     int iCellLeft = 0;
116513     int iCellRight = 0;
116514
116515     for(jj=1; jj<nCell; jj++){
116516       float left = DCOORD(aCell[jj].aCoord[i*2]);
116517       float right = DCOORD(aCell[jj].aCoord[i*2+1]);
116518
116519       if( left<x1 ) x1 = left;
116520       if( right>x4 ) x4 = right;
116521       if( left>x3 ){
116522         x3 = left;
116523         iCellRight = jj;
116524       }
116525       if( right<x2 ){
116526         x2 = right;
116527         iCellLeft = jj;
116528       }
116529     }
116530
116531     if( x4!=x1 ){
116532       float normalwidth = (x3 - x2) / (x4 - x1);
116533       if( normalwidth>maxNormalInnerWidth ){
116534         iLeftSeed = iCellLeft;
116535         iRightSeed = iCellRight;
116536       }
116537     }
116538   }
116539
116540   *piLeftSeed = iLeftSeed;
116541   *piRightSeed = iRightSeed;
116542 }
116543 #endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
116544
116545 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
116546 /*
116547 ** Implementation of the quadratic variant of the PickNext() function from
116548 ** Guttman[84].
116549 */
116550 static RtreeCell *QuadraticPickNext(
116551   Rtree *pRtree,
116552   RtreeCell *aCell, 
116553   int nCell, 
116554   RtreeCell *pLeftBox, 
116555   RtreeCell *pRightBox,
116556   int *aiUsed
116557 ){
116558   #define FABS(a) ((a)<0.0?-1.0*(a):(a))
116559
116560   int iSelect = -1;
116561   float fDiff;
116562   int ii;
116563   for(ii=0; ii<nCell; ii++){
116564     if( aiUsed[ii]==0 ){
116565       float left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
116566       float right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
116567       float diff = FABS(right-left);
116568       if( iSelect<0 || diff>fDiff ){
116569         fDiff = diff;
116570         iSelect = ii;
116571       }
116572     }
116573   }
116574   aiUsed[iSelect] = 1;
116575   return &aCell[iSelect];
116576 }
116577
116578 /*
116579 ** Implementation of the quadratic variant of the PickSeeds() function from
116580 ** Guttman[84].
116581 */
116582 static void QuadraticPickSeeds(
116583   Rtree *pRtree,
116584   RtreeCell *aCell, 
116585   int nCell, 
116586   int *piLeftSeed, 
116587   int *piRightSeed
116588 ){
116589   int ii;
116590   int jj;
116591
116592   int iLeftSeed = 0;
116593   int iRightSeed = 1;
116594   float fWaste = 0.0;
116595
116596   for(ii=0; ii<nCell; ii++){
116597     for(jj=ii+1; jj<nCell; jj++){
116598       float right = cellArea(pRtree, &aCell[jj]);
116599       float growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
116600       float waste = growth - right;
116601
116602       if( waste>fWaste ){
116603         iLeftSeed = ii;
116604         iRightSeed = jj;
116605         fWaste = waste;
116606       }
116607     }
116608   }
116609
116610   *piLeftSeed = iLeftSeed;
116611   *piRightSeed = iRightSeed;
116612 }
116613 #endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
116614
116615 /*
116616 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
116617 ** nIdx. The aIdx array contains the set of integers from 0 to 
116618 ** (nIdx-1) in no particular order. This function sorts the values
116619 ** in aIdx according to the indexed values in aDistance. For
116620 ** example, assuming the inputs:
116621 **
116622 **   aIdx      = { 0,   1,   2,   3 }
116623 **   aDistance = { 5.0, 2.0, 7.0, 6.0 }
116624 **
116625 ** this function sets the aIdx array to contain:
116626 **
116627 **   aIdx      = { 0,   1,   2,   3 }
116628 **
116629 ** The aSpare array is used as temporary working space by the
116630 ** sorting algorithm.
116631 */
116632 static void SortByDistance(
116633   int *aIdx, 
116634   int nIdx, 
116635   float *aDistance, 
116636   int *aSpare
116637 ){
116638   if( nIdx>1 ){
116639     int iLeft = 0;
116640     int iRight = 0;
116641
116642     int nLeft = nIdx/2;
116643     int nRight = nIdx-nLeft;
116644     int *aLeft = aIdx;
116645     int *aRight = &aIdx[nLeft];
116646
116647     SortByDistance(aLeft, nLeft, aDistance, aSpare);
116648     SortByDistance(aRight, nRight, aDistance, aSpare);
116649
116650     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
116651     aLeft = aSpare;
116652
116653     while( iLeft<nLeft || iRight<nRight ){
116654       if( iLeft==nLeft ){
116655         aIdx[iLeft+iRight] = aRight[iRight];
116656         iRight++;
116657       }else if( iRight==nRight ){
116658         aIdx[iLeft+iRight] = aLeft[iLeft];
116659         iLeft++;
116660       }else{
116661         float fLeft = aDistance[aLeft[iLeft]];
116662         float fRight = aDistance[aRight[iRight]];
116663         if( fLeft<fRight ){
116664           aIdx[iLeft+iRight] = aLeft[iLeft];
116665           iLeft++;
116666         }else{
116667           aIdx[iLeft+iRight] = aRight[iRight];
116668           iRight++;
116669         }
116670       }
116671     }
116672
116673 #if 0
116674     /* Check that the sort worked */
116675     {
116676       int jj;
116677       for(jj=1; jj<nIdx; jj++){
116678         float left = aDistance[aIdx[jj-1]];
116679         float right = aDistance[aIdx[jj]];
116680         assert( left<=right );
116681       }
116682     }
116683 #endif
116684   }
116685 }
116686
116687 /*
116688 ** Arguments aIdx, aCell and aSpare all point to arrays of size
116689 ** nIdx. The aIdx array contains the set of integers from 0 to 
116690 ** (nIdx-1) in no particular order. This function sorts the values
116691 ** in aIdx according to dimension iDim of the cells in aCell. The
116692 ** minimum value of dimension iDim is considered first, the
116693 ** maximum used to break ties.
116694 **
116695 ** The aSpare array is used as temporary working space by the
116696 ** sorting algorithm.
116697 */
116698 static void SortByDimension(
116699   Rtree *pRtree,
116700   int *aIdx, 
116701   int nIdx, 
116702   int iDim, 
116703   RtreeCell *aCell, 
116704   int *aSpare
116705 ){
116706   if( nIdx>1 ){
116707
116708     int iLeft = 0;
116709     int iRight = 0;
116710
116711     int nLeft = nIdx/2;
116712     int nRight = nIdx-nLeft;
116713     int *aLeft = aIdx;
116714     int *aRight = &aIdx[nLeft];
116715
116716     SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
116717     SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
116718
116719     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
116720     aLeft = aSpare;
116721     while( iLeft<nLeft || iRight<nRight ){
116722       double xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
116723       double xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
116724       double xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
116725       double xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
116726       if( (iLeft!=nLeft) && ((iRight==nRight)
116727        || (xleft1<xright1)
116728        || (xleft1==xright1 && xleft2<xright2)
116729       )){
116730         aIdx[iLeft+iRight] = aLeft[iLeft];
116731         iLeft++;
116732       }else{
116733         aIdx[iLeft+iRight] = aRight[iRight];
116734         iRight++;
116735       }
116736     }
116737
116738 #if 0
116739     /* Check that the sort worked */
116740     {
116741       int jj;
116742       for(jj=1; jj<nIdx; jj++){
116743         float xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
116744         float xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
116745         float xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
116746         float xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
116747         assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
116748       }
116749     }
116750 #endif
116751   }
116752 }
116753
116754 #if VARIANT_RSTARTREE_SPLIT
116755 /*
116756 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
116757 */
116758 static int splitNodeStartree(
116759   Rtree *pRtree,
116760   RtreeCell *aCell,
116761   int nCell,
116762   RtreeNode *pLeft,
116763   RtreeNode *pRight,
116764   RtreeCell *pBboxLeft,
116765   RtreeCell *pBboxRight
116766 ){
116767   int **aaSorted;
116768   int *aSpare;
116769   int ii;
116770
116771   int iBestDim;
116772   int iBestSplit;
116773   float fBestMargin;
116774
116775   int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
116776
116777   aaSorted = (int **)sqlite3_malloc(nByte);
116778   if( !aaSorted ){
116779     return SQLITE_NOMEM;
116780   }
116781
116782   aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
116783   memset(aaSorted, 0, nByte);
116784   for(ii=0; ii<pRtree->nDim; ii++){
116785     int jj;
116786     aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
116787     for(jj=0; jj<nCell; jj++){
116788       aaSorted[ii][jj] = jj;
116789     }
116790     SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
116791   }
116792
116793   for(ii=0; ii<pRtree->nDim; ii++){
116794     float margin = 0.0;
116795     float fBestOverlap;
116796     float fBestArea;
116797     int iBestLeft;
116798     int nLeft;
116799
116800     for(
116801       nLeft=RTREE_MINCELLS(pRtree); 
116802       nLeft<=(nCell-RTREE_MINCELLS(pRtree)); 
116803       nLeft++
116804     ){
116805       RtreeCell left;
116806       RtreeCell right;
116807       int kk;
116808       float overlap;
116809       float area;
116810
116811       memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
116812       memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
116813       for(kk=1; kk<(nCell-1); kk++){
116814         if( kk<nLeft ){
116815           cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
116816         }else{
116817           cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
116818         }
116819       }
116820       margin += cellMargin(pRtree, &left);
116821       margin += cellMargin(pRtree, &right);
116822       overlap = cellOverlap(pRtree, &left, &right, 1, -1);
116823       area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
116824       if( (nLeft==RTREE_MINCELLS(pRtree))
116825        || (overlap<fBestOverlap)
116826        || (overlap==fBestOverlap && area<fBestArea)
116827       ){
116828         iBestLeft = nLeft;
116829         fBestOverlap = overlap;
116830         fBestArea = area;
116831       }
116832     }
116833
116834     if( ii==0 || margin<fBestMargin ){
116835       iBestDim = ii;
116836       fBestMargin = margin;
116837       iBestSplit = iBestLeft;
116838     }
116839   }
116840
116841   memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
116842   memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
116843   for(ii=0; ii<nCell; ii++){
116844     RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
116845     RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
116846     RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
116847     nodeInsertCell(pRtree, pTarget, pCell);
116848     cellUnion(pRtree, pBbox, pCell);
116849   }
116850
116851   sqlite3_free(aaSorted);
116852   return SQLITE_OK;
116853 }
116854 #endif
116855
116856 #if VARIANT_GUTTMAN_SPLIT
116857 /*
116858 ** Implementation of the regular R-tree SplitNode from Guttman[1984].
116859 */
116860 static int splitNodeGuttman(
116861   Rtree *pRtree,
116862   RtreeCell *aCell,
116863   int nCell,
116864   RtreeNode *pLeft,
116865   RtreeNode *pRight,
116866   RtreeCell *pBboxLeft,
116867   RtreeCell *pBboxRight
116868 ){
116869   int iLeftSeed = 0;
116870   int iRightSeed = 1;
116871   int *aiUsed;
116872   int i;
116873
116874   aiUsed = sqlite3_malloc(sizeof(int)*nCell);
116875   if( !aiUsed ){
116876     return SQLITE_NOMEM;
116877   }
116878   memset(aiUsed, 0, sizeof(int)*nCell);
116879
116880   PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
116881
116882   memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
116883   memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
116884   nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
116885   nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
116886   aiUsed[iLeftSeed] = 1;
116887   aiUsed[iRightSeed] = 1;
116888
116889   for(i=nCell-2; i>0; i--){
116890     RtreeCell *pNext;
116891     pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
116892     float diff =  
116893       cellGrowth(pRtree, pBboxLeft, pNext) - 
116894       cellGrowth(pRtree, pBboxRight, pNext)
116895     ;
116896     if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
116897      || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
116898     ){
116899       nodeInsertCell(pRtree, pRight, pNext);
116900       cellUnion(pRtree, pBboxRight, pNext);
116901     }else{
116902       nodeInsertCell(pRtree, pLeft, pNext);
116903       cellUnion(pRtree, pBboxLeft, pNext);
116904     }
116905   }
116906
116907   sqlite3_free(aiUsed);
116908   return SQLITE_OK;
116909 }
116910 #endif
116911
116912 static int updateMapping(
116913   Rtree *pRtree, 
116914   i64 iRowid, 
116915   RtreeNode *pNode, 
116916   int iHeight
116917 ){
116918   int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
116919   xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
116920   if( iHeight>0 ){
116921     RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
116922     if( pChild ){
116923       nodeRelease(pRtree, pChild->pParent);
116924       nodeReference(pNode);
116925       pChild->pParent = pNode;
116926     }
116927   }
116928   return xSetMapping(pRtree, iRowid, pNode->iNode);
116929 }
116930
116931 static int SplitNode(
116932   Rtree *pRtree,
116933   RtreeNode *pNode,
116934   RtreeCell *pCell,
116935   int iHeight
116936 ){
116937   int i;
116938   int newCellIsRight = 0;
116939
116940   int rc = SQLITE_OK;
116941   int nCell = NCELL(pNode);
116942   RtreeCell *aCell;
116943   int *aiUsed;
116944
116945   RtreeNode *pLeft = 0;
116946   RtreeNode *pRight = 0;
116947
116948   RtreeCell leftbbox;
116949   RtreeCell rightbbox;
116950
116951   /* Allocate an array and populate it with a copy of pCell and 
116952   ** all cells from node pLeft. Then zero the original node.
116953   */
116954   aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
116955   if( !aCell ){
116956     rc = SQLITE_NOMEM;
116957     goto splitnode_out;
116958   }
116959   aiUsed = (int *)&aCell[nCell+1];
116960   memset(aiUsed, 0, sizeof(int)*(nCell+1));
116961   for(i=0; i<nCell; i++){
116962     nodeGetCell(pRtree, pNode, i, &aCell[i]);
116963   }
116964   nodeZero(pRtree, pNode);
116965   memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
116966   nCell++;
116967
116968   if( pNode->iNode==1 ){
116969     pRight = nodeNew(pRtree, pNode, 1);
116970     pLeft = nodeNew(pRtree, pNode, 1);
116971     pRtree->iDepth++;
116972     pNode->isDirty = 1;
116973     writeInt16(pNode->zData, pRtree->iDepth);
116974   }else{
116975     pLeft = pNode;
116976     pRight = nodeNew(pRtree, pLeft->pParent, 1);
116977     nodeReference(pLeft);
116978   }
116979
116980   if( !pLeft || !pRight ){
116981     rc = SQLITE_NOMEM;
116982     goto splitnode_out;
116983   }
116984
116985   memset(pLeft->zData, 0, pRtree->iNodeSize);
116986   memset(pRight->zData, 0, pRtree->iNodeSize);
116987
116988   rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
116989   if( rc!=SQLITE_OK ){
116990     goto splitnode_out;
116991   }
116992
116993   /* Ensure both child nodes have node numbers assigned to them. */
116994   if( (0==pRight->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pRight)))
116995    || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
116996   ){
116997     goto splitnode_out;
116998   }
116999
117000   rightbbox.iRowid = pRight->iNode;
117001   leftbbox.iRowid = pLeft->iNode;
117002
117003   if( pNode->iNode==1 ){
117004     rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
117005     if( rc!=SQLITE_OK ){
117006       goto splitnode_out;
117007     }
117008   }else{
117009     RtreeNode *pParent = pLeft->pParent;
117010     int iCell = nodeParentIndex(pRtree, pLeft);
117011     nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
117012     AdjustTree(pRtree, pParent, &leftbbox);
117013   }
117014   if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
117015     goto splitnode_out;
117016   }
117017
117018   for(i=0; i<NCELL(pRight); i++){
117019     i64 iRowid = nodeGetRowid(pRtree, pRight, i);
117020     rc = updateMapping(pRtree, iRowid, pRight, iHeight);
117021     if( iRowid==pCell->iRowid ){
117022       newCellIsRight = 1;
117023     }
117024     if( rc!=SQLITE_OK ){
117025       goto splitnode_out;
117026     }
117027   }
117028   if( pNode->iNode==1 ){
117029     for(i=0; i<NCELL(pLeft); i++){
117030       i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
117031       rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
117032       if( rc!=SQLITE_OK ){
117033         goto splitnode_out;
117034       }
117035     }
117036   }else if( newCellIsRight==0 ){
117037     rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
117038   }
117039
117040   if( rc==SQLITE_OK ){
117041     rc = nodeRelease(pRtree, pRight);
117042     pRight = 0;
117043   }
117044   if( rc==SQLITE_OK ){
117045     rc = nodeRelease(pRtree, pLeft);
117046     pLeft = 0;
117047   }
117048
117049 splitnode_out:
117050   nodeRelease(pRtree, pRight);
117051   nodeRelease(pRtree, pLeft);
117052   sqlite3_free(aCell);
117053   return rc;
117054 }
117055
117056 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
117057   int rc = SQLITE_OK;
117058   if( pLeaf->iNode!=1 && pLeaf->pParent==0 ){
117059     sqlite3_bind_int64(pRtree->pReadParent, 1, pLeaf->iNode);
117060     if( sqlite3_step(pRtree->pReadParent)==SQLITE_ROW ){
117061       i64 iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
117062       rc = nodeAcquire(pRtree, iNode, 0, &pLeaf->pParent);
117063     }else{
117064       rc = SQLITE_ERROR;
117065     }
117066     sqlite3_reset(pRtree->pReadParent);
117067     if( rc==SQLITE_OK ){
117068       rc = fixLeafParent(pRtree, pLeaf->pParent);
117069     }
117070   }
117071   return rc;
117072 }
117073
117074 static int deleteCell(Rtree *, RtreeNode *, int, int);
117075
117076 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
117077   int rc;
117078   RtreeNode *pParent;
117079   int iCell;
117080
117081   assert( pNode->nRef==1 );
117082
117083   /* Remove the entry in the parent cell. */
117084   iCell = nodeParentIndex(pRtree, pNode);
117085   pParent = pNode->pParent;
117086   pNode->pParent = 0;
117087   if( SQLITE_OK!=(rc = deleteCell(pRtree, pParent, iCell, iHeight+1)) 
117088    || SQLITE_OK!=(rc = nodeRelease(pRtree, pParent))
117089   ){
117090     return rc;
117091   }
117092
117093   /* Remove the xxx_node entry. */
117094   sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
117095   sqlite3_step(pRtree->pDeleteNode);
117096   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
117097     return rc;
117098   }
117099
117100   /* Remove the xxx_parent entry. */
117101   sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
117102   sqlite3_step(pRtree->pDeleteParent);
117103   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
117104     return rc;
117105   }
117106   
117107   /* Remove the node from the in-memory hash table and link it into
117108   ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
117109   */
117110   nodeHashDelete(pRtree, pNode);
117111   pNode->iNode = iHeight;
117112   pNode->pNext = pRtree->pDeleted;
117113   pNode->nRef++;
117114   pRtree->pDeleted = pNode;
117115
117116   return SQLITE_OK;
117117 }
117118
117119 static void fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
117120   RtreeNode *pParent = pNode->pParent;
117121   if( pParent ){
117122     int ii; 
117123     int nCell = NCELL(pNode);
117124     RtreeCell box;                            /* Bounding box for pNode */
117125     nodeGetCell(pRtree, pNode, 0, &box);
117126     for(ii=1; ii<nCell; ii++){
117127       RtreeCell cell;
117128       nodeGetCell(pRtree, pNode, ii, &cell);
117129       cellUnion(pRtree, &box, &cell);
117130     }
117131     box.iRowid = pNode->iNode;
117132     ii = nodeParentIndex(pRtree, pNode);
117133     nodeOverwriteCell(pRtree, pParent, &box, ii);
117134     fixBoundingBox(pRtree, pParent);
117135   }
117136 }
117137
117138 /*
117139 ** Delete the cell at index iCell of node pNode. After removing the
117140 ** cell, adjust the r-tree data structure if required.
117141 */
117142 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
117143   int rc;
117144
117145   if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
117146     return rc;
117147   }
117148
117149   /* Remove the cell from the node. This call just moves bytes around
117150   ** the in-memory node image, so it cannot fail.
117151   */
117152   nodeDeleteCell(pRtree, pNode, iCell);
117153
117154   /* If the node is not the tree root and now has less than the minimum
117155   ** number of cells, remove it from the tree. Otherwise, update the
117156   ** cell in the parent node so that it tightly contains the updated
117157   ** node.
117158   */
117159   if( pNode->iNode!=1 ){
117160     RtreeNode *pParent = pNode->pParent;
117161     if( (pParent->iNode!=1 || NCELL(pParent)!=1) 
117162      && (NCELL(pNode)<RTREE_MINCELLS(pRtree))
117163     ){
117164       rc = removeNode(pRtree, pNode, iHeight);
117165     }else{
117166       fixBoundingBox(pRtree, pNode);
117167     }
117168   }
117169
117170   return rc;
117171 }
117172
117173 static int Reinsert(
117174   Rtree *pRtree, 
117175   RtreeNode *pNode, 
117176   RtreeCell *pCell, 
117177   int iHeight
117178 ){
117179   int *aOrder;
117180   int *aSpare;
117181   RtreeCell *aCell;
117182   float *aDistance;
117183   int nCell;
117184   float aCenterCoord[RTREE_MAX_DIMENSIONS];
117185   int iDim;
117186   int ii;
117187   int rc = SQLITE_OK;
117188
117189   memset(aCenterCoord, 0, sizeof(float)*RTREE_MAX_DIMENSIONS);
117190
117191   nCell = NCELL(pNode)+1;
117192
117193   /* Allocate the buffers used by this operation. The allocation is
117194   ** relinquished before this function returns.
117195   */
117196   aCell = (RtreeCell *)sqlite3_malloc(nCell * (
117197     sizeof(RtreeCell) +         /* aCell array */
117198     sizeof(int)       +         /* aOrder array */
117199     sizeof(int)       +         /* aSpare array */
117200     sizeof(float)               /* aDistance array */
117201   ));
117202   if( !aCell ){
117203     return SQLITE_NOMEM;
117204   }
117205   aOrder    = (int *)&aCell[nCell];
117206   aSpare    = (int *)&aOrder[nCell];
117207   aDistance = (float *)&aSpare[nCell];
117208
117209   for(ii=0; ii<nCell; ii++){
117210     if( ii==(nCell-1) ){
117211       memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
117212     }else{
117213       nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
117214     }
117215     aOrder[ii] = ii;
117216     for(iDim=0; iDim<pRtree->nDim; iDim++){
117217       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
117218       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
117219     }
117220   }
117221   for(iDim=0; iDim<pRtree->nDim; iDim++){
117222     aCenterCoord[iDim] = aCenterCoord[iDim]/((float)nCell*2.0);
117223   }
117224
117225   for(ii=0; ii<nCell; ii++){
117226     aDistance[ii] = 0.0;
117227     for(iDim=0; iDim<pRtree->nDim; iDim++){
117228       float coord = DCOORD(aCell[ii].aCoord[iDim*2+1]) - 
117229           DCOORD(aCell[ii].aCoord[iDim*2]);
117230       aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
117231     }
117232   }
117233
117234   SortByDistance(aOrder, nCell, aDistance, aSpare);
117235   nodeZero(pRtree, pNode);
117236
117237   for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
117238     RtreeCell *p = &aCell[aOrder[ii]];
117239     nodeInsertCell(pRtree, pNode, p);
117240     if( p->iRowid==pCell->iRowid ){
117241       if( iHeight==0 ){
117242         rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
117243       }else{
117244         rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
117245       }
117246     }
117247   }
117248   if( rc==SQLITE_OK ){
117249     fixBoundingBox(pRtree, pNode);
117250   }
117251   for(; rc==SQLITE_OK && ii<nCell; ii++){
117252     /* Find a node to store this cell in. pNode->iNode currently contains
117253     ** the height of the sub-tree headed by the cell.
117254     */
117255     RtreeNode *pInsert;
117256     RtreeCell *p = &aCell[aOrder[ii]];
117257     rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
117258     if( rc==SQLITE_OK ){
117259       int rc2;
117260       rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
117261       rc2 = nodeRelease(pRtree, pInsert);
117262       if( rc==SQLITE_OK ){
117263         rc = rc2;
117264       }
117265     }
117266   }
117267
117268   sqlite3_free(aCell);
117269   return rc;
117270 }
117271
117272 /*
117273 ** Insert cell pCell into node pNode. Node pNode is the head of a 
117274 ** subtree iHeight high (leaf nodes have iHeight==0).
117275 */
117276 static int rtreeInsertCell(
117277   Rtree *pRtree,
117278   RtreeNode *pNode,
117279   RtreeCell *pCell,
117280   int iHeight
117281 ){
117282   int rc = SQLITE_OK;
117283   if( iHeight>0 ){
117284     RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
117285     if( pChild ){
117286       nodeRelease(pRtree, pChild->pParent);
117287       nodeReference(pNode);
117288       pChild->pParent = pNode;
117289     }
117290   }
117291   if( nodeInsertCell(pRtree, pNode, pCell) ){
117292 #if VARIANT_RSTARTREE_REINSERT
117293     if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
117294       rc = SplitNode(pRtree, pNode, pCell, iHeight);
117295     }else{
117296       pRtree->iReinsertHeight = iHeight;
117297       rc = Reinsert(pRtree, pNode, pCell, iHeight);
117298     }
117299 #else
117300     rc = SplitNode(pRtree, pNode, pCell, iHeight);
117301 #endif
117302   }else{
117303     AdjustTree(pRtree, pNode, pCell);
117304     if( iHeight==0 ){
117305       rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
117306     }else{
117307       rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
117308     }
117309   }
117310   return rc;
117311 }
117312
117313 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
117314   int ii;
117315   int rc = SQLITE_OK;
117316   int nCell = NCELL(pNode);
117317
117318   for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
117319     RtreeNode *pInsert;
117320     RtreeCell cell;
117321     nodeGetCell(pRtree, pNode, ii, &cell);
117322
117323     /* Find a node to store this cell in. pNode->iNode currently contains
117324     ** the height of the sub-tree headed by the cell.
117325     */
117326     rc = ChooseLeaf(pRtree, &cell, pNode->iNode, &pInsert);
117327     if( rc==SQLITE_OK ){
117328       int rc2;
117329       rc = rtreeInsertCell(pRtree, pInsert, &cell, pNode->iNode);
117330       rc2 = nodeRelease(pRtree, pInsert);
117331       if( rc==SQLITE_OK ){
117332         rc = rc2;
117333       }
117334     }
117335   }
117336   return rc;
117337 }
117338
117339 /*
117340 ** Select a currently unused rowid for a new r-tree record.
117341 */
117342 static int newRowid(Rtree *pRtree, i64 *piRowid){
117343   int rc;
117344   sqlite3_bind_null(pRtree->pWriteRowid, 1);
117345   sqlite3_bind_null(pRtree->pWriteRowid, 2);
117346   sqlite3_step(pRtree->pWriteRowid);
117347   rc = sqlite3_reset(pRtree->pWriteRowid);
117348   *piRowid = sqlite3_last_insert_rowid(pRtree->db);
117349   return rc;
117350 }
117351
117352 #ifndef NDEBUG
117353 static int hashIsEmpty(Rtree *pRtree){
117354   int ii;
117355   for(ii=0; ii<HASHSIZE; ii++){
117356     assert( !pRtree->aHash[ii] );
117357   }
117358   return 1;
117359 }
117360 #endif
117361
117362 /*
117363 ** The xUpdate method for rtree module virtual tables.
117364 */
117365 static int rtreeUpdate(
117366   sqlite3_vtab *pVtab, 
117367   int nData, 
117368   sqlite3_value **azData, 
117369   sqlite_int64 *pRowid
117370 ){
117371   Rtree *pRtree = (Rtree *)pVtab;
117372   int rc = SQLITE_OK;
117373
117374   rtreeReference(pRtree);
117375
117376   assert(nData>=1);
117377   assert(hashIsEmpty(pRtree));
117378
117379   /* If azData[0] is not an SQL NULL value, it is the rowid of a
117380   ** record to delete from the r-tree table. The following block does
117381   ** just that.
117382   */
117383   if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
117384     i64 iDelete;                /* The rowid to delete */
117385     RtreeNode *pLeaf;           /* Leaf node containing record iDelete */
117386     int iCell;                  /* Index of iDelete cell in pLeaf */
117387     RtreeNode *pRoot;
117388
117389     /* Obtain a reference to the root node to initialise Rtree.iDepth */
117390     rc = nodeAcquire(pRtree, 1, 0, &pRoot);
117391
117392     /* Obtain a reference to the leaf node that contains the entry 
117393     ** about to be deleted. 
117394     */
117395     if( rc==SQLITE_OK ){
117396       iDelete = sqlite3_value_int64(azData[0]);
117397       rc = findLeafNode(pRtree, iDelete, &pLeaf);
117398     }
117399
117400     /* Delete the cell in question from the leaf node. */
117401     if( rc==SQLITE_OK ){
117402       int rc2;
117403       iCell = nodeRowidIndex(pRtree, pLeaf, iDelete);
117404       rc = deleteCell(pRtree, pLeaf, iCell, 0);
117405       rc2 = nodeRelease(pRtree, pLeaf);
117406       if( rc==SQLITE_OK ){
117407         rc = rc2;
117408       }
117409     }
117410
117411     /* Delete the corresponding entry in the <rtree>_rowid table. */
117412     if( rc==SQLITE_OK ){
117413       sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
117414       sqlite3_step(pRtree->pDeleteRowid);
117415       rc = sqlite3_reset(pRtree->pDeleteRowid);
117416     }
117417
117418     /* Check if the root node now has exactly one child. If so, remove
117419     ** it, schedule the contents of the child for reinsertion and 
117420     ** reduce the tree height by one.
117421     **
117422     ** This is equivalent to copying the contents of the child into
117423     ** the root node (the operation that Gutman's paper says to perform 
117424     ** in this scenario).
117425     */
117426     if( rc==SQLITE_OK && pRtree->iDepth>0 ){
117427       if( rc==SQLITE_OK && NCELL(pRoot)==1 ){
117428         RtreeNode *pChild;
117429         i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
117430         rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
117431         if( rc==SQLITE_OK ){
117432           rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
117433         }
117434         if( rc==SQLITE_OK ){
117435           pRtree->iDepth--;
117436           writeInt16(pRoot->zData, pRtree->iDepth);
117437           pRoot->isDirty = 1;
117438         }
117439       }
117440     }
117441
117442     /* Re-insert the contents of any underfull nodes removed from the tree. */
117443     for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
117444       if( rc==SQLITE_OK ){
117445         rc = reinsertNodeContent(pRtree, pLeaf);
117446       }
117447       pRtree->pDeleted = pLeaf->pNext;
117448       sqlite3_free(pLeaf);
117449     }
117450
117451     /* Release the reference to the root node. */
117452     if( rc==SQLITE_OK ){
117453       rc = nodeRelease(pRtree, pRoot);
117454     }else{
117455       nodeRelease(pRtree, pRoot);
117456     }
117457   }
117458
117459   /* If the azData[] array contains more than one element, elements
117460   ** (azData[2]..azData[argc-1]) contain a new record to insert into
117461   ** the r-tree structure.
117462   */
117463   if( rc==SQLITE_OK && nData>1 ){
117464     /* Insert a new record into the r-tree */
117465     RtreeCell cell;
117466     int ii;
117467     RtreeNode *pLeaf;
117468
117469     /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
117470     assert( nData==(pRtree->nDim*2 + 3) );
117471     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
117472       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
117473         cell.aCoord[ii].f = (float)sqlite3_value_double(azData[ii+3]);
117474         cell.aCoord[ii+1].f = (float)sqlite3_value_double(azData[ii+4]);
117475         if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
117476           rc = SQLITE_CONSTRAINT;
117477           goto constraint;
117478         }
117479       }
117480     }else{
117481       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
117482         cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
117483         cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
117484         if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
117485           rc = SQLITE_CONSTRAINT;
117486           goto constraint;
117487         }
117488       }
117489     }
117490
117491     /* Figure out the rowid of the new row. */
117492     if( sqlite3_value_type(azData[2])==SQLITE_NULL ){
117493       rc = newRowid(pRtree, &cell.iRowid);
117494     }else{
117495       cell.iRowid = sqlite3_value_int64(azData[2]);
117496       sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
117497       if( SQLITE_ROW==sqlite3_step(pRtree->pReadRowid) ){
117498         sqlite3_reset(pRtree->pReadRowid);
117499         rc = SQLITE_CONSTRAINT;
117500         goto constraint;
117501       }
117502       rc = sqlite3_reset(pRtree->pReadRowid);
117503     }
117504     *pRowid = cell.iRowid;
117505
117506     if( rc==SQLITE_OK ){
117507       rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
117508     }
117509     if( rc==SQLITE_OK ){
117510       int rc2;
117511       pRtree->iReinsertHeight = -1;
117512       rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
117513       rc2 = nodeRelease(pRtree, pLeaf);
117514       if( rc==SQLITE_OK ){
117515         rc = rc2;
117516       }
117517     }
117518   }
117519
117520 constraint:
117521   rtreeRelease(pRtree);
117522   return rc;
117523 }
117524
117525 /*
117526 ** The xRename method for rtree module virtual tables.
117527 */
117528 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
117529   Rtree *pRtree = (Rtree *)pVtab;
117530   int rc = SQLITE_NOMEM;
117531   char *zSql = sqlite3_mprintf(
117532     "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
117533     "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
117534     "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
117535     , pRtree->zDb, pRtree->zName, zNewName 
117536     , pRtree->zDb, pRtree->zName, zNewName 
117537     , pRtree->zDb, pRtree->zName, zNewName
117538   );
117539   if( zSql ){
117540     rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
117541     sqlite3_free(zSql);
117542   }
117543   return rc;
117544 }
117545
117546 static sqlite3_module rtreeModule = {
117547   0,                         /* iVersion */
117548   rtreeCreate,                /* xCreate - create a table */
117549   rtreeConnect,               /* xConnect - connect to an existing table */
117550   rtreeBestIndex,             /* xBestIndex - Determine search strategy */
117551   rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
117552   rtreeDestroy,               /* xDestroy - Drop a table */
117553   rtreeOpen,                  /* xOpen - open a cursor */
117554   rtreeClose,                 /* xClose - close a cursor */
117555   rtreeFilter,                /* xFilter - configure scan constraints */
117556   rtreeNext,                  /* xNext - advance a cursor */
117557   rtreeEof,                   /* xEof */
117558   rtreeColumn,                /* xColumn - read data */
117559   rtreeRowid,                 /* xRowid - read data */
117560   rtreeUpdate,                /* xUpdate - write data */
117561   0,                          /* xBegin - begin transaction */
117562   0,                          /* xSync - sync transaction */
117563   0,                          /* xCommit - commit transaction */
117564   0,                          /* xRollback - rollback transaction */
117565   0,                          /* xFindFunction - function overloading */
117566   rtreeRename                 /* xRename - rename the table */
117567 };
117568
117569 static int rtreeSqlInit(
117570   Rtree *pRtree, 
117571   sqlite3 *db, 
117572   const char *zDb, 
117573   const char *zPrefix, 
117574   int isCreate
117575 ){
117576   int rc = SQLITE_OK;
117577
117578   #define N_STATEMENT 9
117579   static const char *azSql[N_STATEMENT] = {
117580     /* Read and write the xxx_node table */
117581     "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
117582     "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
117583     "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
117584
117585     /* Read and write the xxx_rowid table */
117586     "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
117587     "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
117588     "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
117589
117590     /* Read and write the xxx_parent table */
117591     "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
117592     "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
117593     "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
117594   };
117595   sqlite3_stmt **appStmt[N_STATEMENT];
117596   int i;
117597
117598   pRtree->db = db;
117599
117600   if( isCreate ){
117601     char *zCreate = sqlite3_mprintf(
117602 "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
117603 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
117604 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
117605 "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
117606       zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
117607     );
117608     if( !zCreate ){
117609       return SQLITE_NOMEM;
117610     }
117611     rc = sqlite3_exec(db, zCreate, 0, 0, 0);
117612     sqlite3_free(zCreate);
117613     if( rc!=SQLITE_OK ){
117614       return rc;
117615     }
117616   }
117617
117618   appStmt[0] = &pRtree->pReadNode;
117619   appStmt[1] = &pRtree->pWriteNode;
117620   appStmt[2] = &pRtree->pDeleteNode;
117621   appStmt[3] = &pRtree->pReadRowid;
117622   appStmt[4] = &pRtree->pWriteRowid;
117623   appStmt[5] = &pRtree->pDeleteRowid;
117624   appStmt[6] = &pRtree->pReadParent;
117625   appStmt[7] = &pRtree->pWriteParent;
117626   appStmt[8] = &pRtree->pDeleteParent;
117627
117628   for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
117629     char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
117630     if( zSql ){
117631       rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0); 
117632     }else{
117633       rc = SQLITE_NOMEM;
117634     }
117635     sqlite3_free(zSql);
117636   }
117637
117638   return rc;
117639 }
117640
117641 /*
117642 ** The second argument to this function contains the text of an SQL statement
117643 ** that returns a single integer value. The statement is compiled and executed
117644 ** using database connection db. If successful, the integer value returned
117645 ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
117646 ** code is returned and the value of *piVal after returning is not defined.
117647 */
117648 static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
117649   int rc = SQLITE_NOMEM;
117650   if( zSql ){
117651     sqlite3_stmt *pStmt = 0;
117652     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
117653     if( rc==SQLITE_OK ){
117654       if( SQLITE_ROW==sqlite3_step(pStmt) ){
117655         *piVal = sqlite3_column_int(pStmt, 0);
117656       }
117657       rc = sqlite3_finalize(pStmt);
117658     }
117659   }
117660   return rc;
117661 }
117662
117663 /*
117664 ** This function is called from within the xConnect() or xCreate() method to
117665 ** determine the node-size used by the rtree table being created or connected
117666 ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
117667 ** Otherwise, an SQLite error code is returned.
117668 **
117669 ** If this function is being called as part of an xConnect(), then the rtree
117670 ** table already exists. In this case the node-size is determined by inspecting
117671 ** the root node of the tree.
117672 **
117673 ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size. 
117674 ** This ensures that each node is stored on a single database page. If the 
117675 ** database page-size is so large that more than RTREE_MAXCELLS entries 
117676 ** would fit in a single node, use a smaller node-size.
117677 */
117678 static int getNodeSize(
117679   sqlite3 *db,                    /* Database handle */
117680   Rtree *pRtree,                  /* Rtree handle */
117681   int isCreate                    /* True for xCreate, false for xConnect */
117682 ){
117683   int rc;
117684   char *zSql;
117685   if( isCreate ){
117686     int iPageSize;
117687     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
117688     rc = getIntFromStmt(db, zSql, &iPageSize);
117689     if( rc==SQLITE_OK ){
117690       pRtree->iNodeSize = iPageSize-64;
117691       if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
117692         pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
117693       }
117694     }
117695   }else{
117696     zSql = sqlite3_mprintf(
117697         "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
117698         pRtree->zDb, pRtree->zName
117699     );
117700     rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
117701   }
117702
117703   sqlite3_free(zSql);
117704   return rc;
117705 }
117706
117707 /* 
117708 ** This function is the implementation of both the xConnect and xCreate
117709 ** methods of the r-tree virtual table.
117710 **
117711 **   argv[0]   -> module name
117712 **   argv[1]   -> database name
117713 **   argv[2]   -> table name
117714 **   argv[...] -> column names...
117715 */
117716 static int rtreeInit(
117717   sqlite3 *db,                        /* Database connection */
117718   void *pAux,                         /* One of the RTREE_COORD_* constants */
117719   int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
117720   sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
117721   char **pzErr,                       /* OUT: Error message, if any */
117722   int isCreate                        /* True for xCreate, false for xConnect */
117723 ){
117724   int rc = SQLITE_OK;
117725   Rtree *pRtree;
117726   int nDb;              /* Length of string argv[1] */
117727   int nName;            /* Length of string argv[2] */
117728   int eCoordType = (int)pAux;
117729
117730   const char *aErrMsg[] = {
117731     0,                                                    /* 0 */
117732     "Wrong number of columns for an rtree table",         /* 1 */
117733     "Too few columns for an rtree table",                 /* 2 */
117734     "Too many columns for an rtree table"                 /* 3 */
117735   };
117736
117737   int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
117738   if( aErrMsg[iErr] ){
117739     *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
117740     return SQLITE_ERROR;
117741   }
117742
117743   /* Allocate the sqlite3_vtab structure */
117744   nDb = strlen(argv[1]);
117745   nName = strlen(argv[2]);
117746   pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
117747   if( !pRtree ){
117748     return SQLITE_NOMEM;
117749   }
117750   memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
117751   pRtree->nBusy = 1;
117752   pRtree->base.pModule = &rtreeModule;
117753   pRtree->zDb = (char *)&pRtree[1];
117754   pRtree->zName = &pRtree->zDb[nDb+1];
117755   pRtree->nDim = (argc-4)/2;
117756   pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
117757   pRtree->eCoordType = eCoordType;
117758   memcpy(pRtree->zDb, argv[1], nDb);
117759   memcpy(pRtree->zName, argv[2], nName);
117760
117761   /* Figure out the node size to use. */
117762   rc = getNodeSize(db, pRtree, isCreate);
117763
117764   /* Create/Connect to the underlying relational database schema. If
117765   ** that is successful, call sqlite3_declare_vtab() to configure
117766   ** the r-tree table schema.
117767   */
117768   if( rc==SQLITE_OK ){
117769     if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
117770       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
117771     }else{
117772       char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
117773       char *zTmp;
117774       int ii;
117775       for(ii=4; zSql && ii<argc; ii++){
117776         zTmp = zSql;
117777         zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
117778         sqlite3_free(zTmp);
117779       }
117780       if( zSql ){
117781         zTmp = zSql;
117782         zSql = sqlite3_mprintf("%s);", zTmp);
117783         sqlite3_free(zTmp);
117784       }
117785       if( !zSql ){
117786         rc = SQLITE_NOMEM;
117787       }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
117788         *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
117789       }
117790       sqlite3_free(zSql);
117791     }
117792   }
117793
117794   if( rc==SQLITE_OK ){
117795     *ppVtab = (sqlite3_vtab *)pRtree;
117796   }else{
117797     rtreeRelease(pRtree);
117798   }
117799   return rc;
117800 }
117801
117802
117803 /*
117804 ** Implementation of a scalar function that decodes r-tree nodes to
117805 ** human readable strings. This can be used for debugging and analysis.
117806 **
117807 ** The scalar function takes two arguments, a blob of data containing
117808 ** an r-tree node, and the number of dimensions the r-tree indexes.
117809 ** For a two-dimensional r-tree structure called "rt", to deserialize
117810 ** all nodes, a statement like:
117811 **
117812 **   SELECT rtreenode(2, data) FROM rt_node;
117813 **
117814 ** The human readable string takes the form of a Tcl list with one
117815 ** entry for each cell in the r-tree node. Each entry is itself a
117816 ** list, containing the 8-byte rowid/pageno followed by the 
117817 ** <num-dimension>*2 coordinates.
117818 */
117819 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
117820   char *zText = 0;
117821   RtreeNode node;
117822   Rtree tree;
117823   int ii;
117824
117825   memset(&node, 0, sizeof(RtreeNode));
117826   memset(&tree, 0, sizeof(Rtree));
117827   tree.nDim = sqlite3_value_int(apArg[0]);
117828   tree.nBytesPerCell = 8 + 8 * tree.nDim;
117829   node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
117830
117831   for(ii=0; ii<NCELL(&node); ii++){
117832     char zCell[512];
117833     int nCell = 0;
117834     RtreeCell cell;
117835     int jj;
117836
117837     nodeGetCell(&tree, &node, ii, &cell);
117838     sqlite3_snprintf(512-nCell,&zCell[nCell],"%d", cell.iRowid);
117839     nCell = strlen(zCell);
117840     for(jj=0; jj<tree.nDim*2; jj++){
117841       sqlite3_snprintf(512-nCell,&zCell[nCell]," %f",(double)cell.aCoord[jj].f);
117842       nCell = strlen(zCell);
117843     }
117844
117845     if( zText ){
117846       char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
117847       sqlite3_free(zText);
117848       zText = zTextNew;
117849     }else{
117850       zText = sqlite3_mprintf("{%s}", zCell);
117851     }
117852   }
117853   
117854   sqlite3_result_text(ctx, zText, -1, sqlite3_free);
117855 }
117856
117857 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
117858   if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB 
117859    || sqlite3_value_bytes(apArg[0])<2
117860   ){
117861     sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1); 
117862   }else{
117863     u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
117864     sqlite3_result_int(ctx, readInt16(zBlob));
117865   }
117866 }
117867
117868 /*
117869 ** Register the r-tree module with database handle db. This creates the
117870 ** virtual table module "rtree" and the debugging/analysis scalar 
117871 ** function "rtreenode".
117872 */
117873 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
117874   int rc = SQLITE_OK;
117875
117876   if( rc==SQLITE_OK ){
117877     int utf8 = SQLITE_UTF8;
117878     rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
117879   }
117880   if( rc==SQLITE_OK ){
117881     int utf8 = SQLITE_UTF8;
117882     rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
117883   }
117884   if( rc==SQLITE_OK ){
117885     void *c = (void *)RTREE_COORD_REAL32;
117886     rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
117887   }
117888   if( rc==SQLITE_OK ){
117889     void *c = (void *)RTREE_COORD_INT32;
117890     rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
117891   }
117892
117893   return rc;
117894 }
117895
117896 #if !SQLITE_CORE
117897 SQLITE_API int sqlite3_extension_init(
117898   sqlite3 *db,
117899   char **pzErrMsg,
117900   const sqlite3_api_routines *pApi
117901 ){
117902   SQLITE_EXTENSION_INIT2(pApi)
117903   return sqlite3RtreeInit(db);
117904 }
117905 #endif
117906
117907 #endif
117908
117909 /************** End of rtree.c ***********************************************/
117910 /************** Begin file icu.c *********************************************/
117911 /*
117912 ** 2007 May 6
117913 **
117914 ** The author disclaims copyright to this source code.  In place of
117915 ** a legal notice, here is a blessing:
117916 **
117917 **    May you do good and not evil.
117918 **    May you find forgiveness for yourself and forgive others.
117919 **    May you share freely, never taking more than you give.
117920 **
117921 *************************************************************************
117922 ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
117923 **
117924 ** This file implements an integration between the ICU library 
117925 ** ("International Components for Unicode", an open-source library 
117926 ** for handling unicode data) and SQLite. The integration uses 
117927 ** ICU to provide the following to SQLite:
117928 **
117929 **   * An implementation of the SQL regexp() function (and hence REGEXP
117930 **     operator) using the ICU uregex_XX() APIs.
117931 **
117932 **   * Implementations of the SQL scalar upper() and lower() functions
117933 **     for case mapping.
117934 **
117935 **   * Integration of ICU and SQLite collation seqences.
117936 **
117937 **   * An implementation of the LIKE operator that uses ICU to 
117938 **     provide case-independent matching.
117939 */
117940
117941 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
117942
117943 /* Include ICU headers */
117944 #include <unicode/utypes.h>
117945 #include <unicode/uregex.h>
117946 #include <unicode/ustring.h>
117947 #include <unicode/ucol.h>
117948
117949
117950 #ifndef SQLITE_CORE
117951   SQLITE_EXTENSION_INIT1
117952 #else
117953 #endif
117954
117955 /*
117956 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
117957 ** operator.
117958 */
117959 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
117960 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
117961 #endif
117962
117963 /*
117964 ** Version of sqlite3_free() that is always a function, never a macro.
117965 */
117966 static void xFree(void *p){
117967   sqlite3_free(p);
117968 }
117969
117970 /*
117971 ** Compare two UTF-8 strings for equality where the first string is
117972 ** a "LIKE" expression. Return true (1) if they are the same and 
117973 ** false (0) if they are different.
117974 */
117975 static int icuLikeCompare(
117976   const uint8_t *zPattern,   /* LIKE pattern */
117977   const uint8_t *zString,    /* The UTF-8 string to compare against */
117978   const UChar32 uEsc         /* The escape character */
117979 ){
117980   static const int MATCH_ONE = (UChar32)'_';
117981   static const int MATCH_ALL = (UChar32)'%';
117982
117983   int iPattern = 0;       /* Current byte index in zPattern */
117984   int iString = 0;        /* Current byte index in zString */
117985
117986   int prevEscape = 0;     /* True if the previous character was uEsc */
117987
117988   while( zPattern[iPattern]!=0 ){
117989
117990     /* Read (and consume) the next character from the input pattern. */
117991     UChar32 uPattern;
117992     U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
117993     assert(uPattern!=0);
117994
117995     /* There are now 4 possibilities:
117996     **
117997     **     1. uPattern is an unescaped match-all character "%",
117998     **     2. uPattern is an unescaped match-one character "_",
117999     **     3. uPattern is an unescaped escape character, or
118000     **     4. uPattern is to be handled as an ordinary character
118001     */
118002     if( !prevEscape && uPattern==MATCH_ALL ){
118003       /* Case 1. */
118004       uint8_t c;
118005
118006       /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
118007       ** MATCH_ALL. For each MATCH_ONE, skip one character in the 
118008       ** test string.
118009       */
118010       while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
118011         if( c==MATCH_ONE ){
118012           if( zString[iString]==0 ) return 0;
118013           U8_FWD_1_UNSAFE(zString, iString);
118014         }
118015         iPattern++;
118016       }
118017
118018       if( zPattern[iPattern]==0 ) return 1;
118019
118020       while( zString[iString] ){
118021         if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
118022           return 1;
118023         }
118024         U8_FWD_1_UNSAFE(zString, iString);
118025       }
118026       return 0;
118027
118028     }else if( !prevEscape && uPattern==MATCH_ONE ){
118029       /* Case 2. */
118030       if( zString[iString]==0 ) return 0;
118031       U8_FWD_1_UNSAFE(zString, iString);
118032
118033     }else if( !prevEscape && uPattern==uEsc){
118034       /* Case 3. */
118035       prevEscape = 1;
118036
118037     }else{
118038       /* Case 4. */
118039       UChar32 uString;
118040       U8_NEXT_UNSAFE(zString, iString, uString);
118041       uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
118042       uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
118043       if( uString!=uPattern ){
118044         return 0;
118045       }
118046       prevEscape = 0;
118047     }
118048   }
118049
118050   return zString[iString]==0;
118051 }
118052
118053 /*
118054 ** Implementation of the like() SQL function.  This function implements
118055 ** the build-in LIKE operator.  The first argument to the function is the
118056 ** pattern and the second argument is the string.  So, the SQL statements:
118057 **
118058 **       A LIKE B
118059 **
118060 ** is implemented as like(B, A). If there is an escape character E, 
118061 **
118062 **       A LIKE B ESCAPE E
118063 **
118064 ** is mapped to like(B, A, E).
118065 */
118066 static void icuLikeFunc(
118067   sqlite3_context *context, 
118068   int argc, 
118069   sqlite3_value **argv
118070 ){
118071   const unsigned char *zA = sqlite3_value_text(argv[0]);
118072   const unsigned char *zB = sqlite3_value_text(argv[1]);
118073   UChar32 uEsc = 0;
118074
118075   /* Limit the length of the LIKE or GLOB pattern to avoid problems
118076   ** of deep recursion and N*N behavior in patternCompare().
118077   */
118078   if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
118079     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
118080     return;
118081   }
118082
118083
118084   if( argc==3 ){
118085     /* The escape character string must consist of a single UTF-8 character.
118086     ** Otherwise, return an error.
118087     */
118088     int nE= sqlite3_value_bytes(argv[2]);
118089     const unsigned char *zE = sqlite3_value_text(argv[2]);
118090     int i = 0;
118091     if( zE==0 ) return;
118092     U8_NEXT(zE, i, nE, uEsc);
118093     if( i!=nE){
118094       sqlite3_result_error(context, 
118095           "ESCAPE expression must be a single character", -1);
118096       return;
118097     }
118098   }
118099
118100   if( zA && zB ){
118101     sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
118102   }
118103 }
118104
118105 /*
118106 ** This function is called when an ICU function called from within
118107 ** the implementation of an SQL scalar function returns an error.
118108 **
118109 ** The scalar function context passed as the first argument is 
118110 ** loaded with an error message based on the following two args.
118111 */
118112 static void icuFunctionError(
118113   sqlite3_context *pCtx,       /* SQLite scalar function context */
118114   const char *zName,           /* Name of ICU function that failed */
118115   UErrorCode e                 /* Error code returned by ICU function */
118116 ){
118117   char zBuf[128];
118118   sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
118119   zBuf[127] = '\0';
118120   sqlite3_result_error(pCtx, zBuf, -1);
118121 }
118122
118123 /*
118124 ** Function to delete compiled regexp objects. Registered as
118125 ** a destructor function with sqlite3_set_auxdata().
118126 */
118127 static void icuRegexpDelete(void *p){
118128   URegularExpression *pExpr = (URegularExpression *)p;
118129   uregex_close(pExpr);
118130 }
118131
118132 /*
118133 ** Implementation of SQLite REGEXP operator. This scalar function takes
118134 ** two arguments. The first is a regular expression pattern to compile
118135 ** the second is a string to match against that pattern. If either 
118136 ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
118137 ** is 1 if the string matches the pattern, or 0 otherwise.
118138 **
118139 ** SQLite maps the regexp() function to the regexp() operator such
118140 ** that the following two are equivalent:
118141 **
118142 **     zString REGEXP zPattern
118143 **     regexp(zPattern, zString)
118144 **
118145 ** Uses the following ICU regexp APIs:
118146 **
118147 **     uregex_open()
118148 **     uregex_matches()
118149 **     uregex_close()
118150 */
118151 static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
118152   UErrorCode status = U_ZERO_ERROR;
118153   URegularExpression *pExpr;
118154   UBool res;
118155   const UChar *zString = sqlite3_value_text16(apArg[1]);
118156
118157   /* If the left hand side of the regexp operator is NULL, 
118158   ** then the result is also NULL. 
118159   */
118160   if( !zString ){
118161     return;
118162   }
118163
118164   pExpr = sqlite3_get_auxdata(p, 0);
118165   if( !pExpr ){
118166     const UChar *zPattern = sqlite3_value_text16(apArg[0]);
118167     if( !zPattern ){
118168       return;
118169     }
118170     pExpr = uregex_open(zPattern, -1, 0, 0, &status);
118171
118172     if( U_SUCCESS(status) ){
118173       sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
118174     }else{
118175       assert(!pExpr);
118176       icuFunctionError(p, "uregex_open", status);
118177       return;
118178     }
118179   }
118180
118181   /* Configure the text that the regular expression operates on. */
118182   uregex_setText(pExpr, zString, -1, &status);
118183   if( !U_SUCCESS(status) ){
118184     icuFunctionError(p, "uregex_setText", status);
118185     return;
118186   }
118187
118188   /* Attempt the match */
118189   res = uregex_matches(pExpr, 0, &status);
118190   if( !U_SUCCESS(status) ){
118191     icuFunctionError(p, "uregex_matches", status);
118192     return;
118193   }
118194
118195   /* Set the text that the regular expression operates on to a NULL
118196   ** pointer. This is not really necessary, but it is tidier than 
118197   ** leaving the regular expression object configured with an invalid
118198   ** pointer after this function returns.
118199   */
118200   uregex_setText(pExpr, 0, 0, &status);
118201
118202   /* Return 1 or 0. */
118203   sqlite3_result_int(p, res ? 1 : 0);
118204 }
118205
118206 /*
118207 ** Implementations of scalar functions for case mapping - upper() and 
118208 ** lower(). Function upper() converts its input to upper-case (ABC).
118209 ** Function lower() converts to lower-case (abc).
118210 **
118211 ** ICU provides two types of case mapping, "general" case mapping and
118212 ** "language specific". Refer to ICU documentation for the differences
118213 ** between the two.
118214 **
118215 ** To utilise "general" case mapping, the upper() or lower() scalar 
118216 ** functions are invoked with one argument:
118217 **
118218 **     upper('ABC') -> 'abc'
118219 **     lower('abc') -> 'ABC'
118220 **
118221 ** To access ICU "language specific" case mapping, upper() or lower()
118222 ** should be invoked with two arguments. The second argument is the name
118223 ** of the locale to use. Passing an empty string ("") or SQL NULL value
118224 ** as the second argument is the same as invoking the 1 argument version
118225 ** of upper() or lower().
118226 **
118227 **     lower('I', 'en_us') -> 'i'
118228 **     lower('I', 'tr_tr') -> 'ı' (small dotless i)
118229 **
118230 ** http://www.icu-project.org/userguide/posix.html#case_mappings
118231 */
118232 static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
118233   const UChar *zInput;
118234   UChar *zOutput;
118235   int nInput;
118236   int nOutput;
118237
118238   UErrorCode status = U_ZERO_ERROR;
118239   const char *zLocale = 0;
118240
118241   assert(nArg==1 || nArg==2);
118242   if( nArg==2 ){
118243     zLocale = (const char *)sqlite3_value_text(apArg[1]);
118244   }
118245
118246   zInput = sqlite3_value_text16(apArg[0]);
118247   if( !zInput ){
118248     return;
118249   }
118250   nInput = sqlite3_value_bytes16(apArg[0]);
118251
118252   nOutput = nInput * 2 + 2;
118253   zOutput = sqlite3_malloc(nOutput);
118254   if( !zOutput ){
118255     return;
118256   }
118257
118258   if( sqlite3_user_data(p) ){
118259     u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
118260   }else{
118261     u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
118262   }
118263
118264   if( !U_SUCCESS(status) ){
118265     icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
118266     return;
118267   }
118268
118269   sqlite3_result_text16(p, zOutput, -1, xFree);
118270 }
118271
118272 /*
118273 ** Collation sequence destructor function. The pCtx argument points to
118274 ** a UCollator structure previously allocated using ucol_open().
118275 */
118276 static void icuCollationDel(void *pCtx){
118277   UCollator *p = (UCollator *)pCtx;
118278   ucol_close(p);
118279 }
118280
118281 /*
118282 ** Collation sequence comparison function. The pCtx argument points to
118283 ** a UCollator structure previously allocated using ucol_open().
118284 */
118285 static int icuCollationColl(
118286   void *pCtx,
118287   int nLeft,
118288   const void *zLeft,
118289   int nRight,
118290   const void *zRight
118291 ){
118292   UCollationResult res;
118293   UCollator *p = (UCollator *)pCtx;
118294   res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
118295   switch( res ){
118296     case UCOL_LESS:    return -1;
118297     case UCOL_GREATER: return +1;
118298     case UCOL_EQUAL:   return 0;
118299   }
118300   assert(!"Unexpected return value from ucol_strcoll()");
118301   return 0;
118302 }
118303
118304 /*
118305 ** Implementation of the scalar function icu_load_collation().
118306 **
118307 ** This scalar function is used to add ICU collation based collation 
118308 ** types to an SQLite database connection. It is intended to be called
118309 ** as follows:
118310 **
118311 **     SELECT icu_load_collation(<locale>, <collation-name>);
118312 **
118313 ** Where <locale> is a string containing an ICU locale identifier (i.e.
118314 ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
118315 ** collation sequence to create.
118316 */
118317 static void icuLoadCollation(
118318   sqlite3_context *p, 
118319   int nArg, 
118320   sqlite3_value **apArg
118321 ){
118322   sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
118323   UErrorCode status = U_ZERO_ERROR;
118324   const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
118325   const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
118326   UCollator *pUCollator;    /* ICU library collation object */
118327   int rc;                   /* Return code from sqlite3_create_collation_x() */
118328
118329   assert(nArg==2);
118330   zLocale = (const char *)sqlite3_value_text(apArg[0]);
118331   zName = (const char *)sqlite3_value_text(apArg[1]);
118332
118333   if( !zLocale || !zName ){
118334     return;
118335   }
118336
118337   pUCollator = ucol_open(zLocale, &status);
118338   if( !U_SUCCESS(status) ){
118339     icuFunctionError(p, "ucol_open", status);
118340     return;
118341   }
118342   assert(p);
118343
118344   rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator, 
118345       icuCollationColl, icuCollationDel
118346   );
118347   if( rc!=SQLITE_OK ){
118348     ucol_close(pUCollator);
118349     sqlite3_result_error(p, "Error registering collation function", -1);
118350   }
118351 }
118352
118353 /*
118354 ** Register the ICU extension functions with database db.
118355 */
118356 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
118357   struct IcuScalar {
118358     const char *zName;                        /* Function name */
118359     int nArg;                                 /* Number of arguments */
118360     int enc;                                  /* Optimal text encoding */
118361     void *pContext;                           /* sqlite3_user_data() context */
118362     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
118363   } scalars[] = {
118364     {"regexp", 2, SQLITE_ANY,          0, icuRegexpFunc},
118365
118366     {"lower",  1, SQLITE_UTF16,        0, icuCaseFunc16},
118367     {"lower",  2, SQLITE_UTF16,        0, icuCaseFunc16},
118368     {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
118369     {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
118370
118371     {"lower",  1, SQLITE_UTF8,         0, icuCaseFunc16},
118372     {"lower",  2, SQLITE_UTF8,         0, icuCaseFunc16},
118373     {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
118374     {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
118375
118376     {"like",   2, SQLITE_UTF8,         0, icuLikeFunc},
118377     {"like",   3, SQLITE_UTF8,         0, icuLikeFunc},
118378
118379     {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
118380   };
118381
118382   int rc = SQLITE_OK;
118383   int i;
118384
118385   for(i=0; rc==SQLITE_OK && i<(sizeof(scalars)/sizeof(struct IcuScalar)); i++){
118386     struct IcuScalar *p = &scalars[i];
118387     rc = sqlite3_create_function(
118388         db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
118389     );
118390   }
118391
118392   return rc;
118393 }
118394
118395 #if !SQLITE_CORE
118396 SQLITE_API int sqlite3_extension_init(
118397   sqlite3 *db, 
118398   char **pzErrMsg,
118399   const sqlite3_api_routines *pApi
118400 ){
118401   SQLITE_EXTENSION_INIT2(pApi)
118402   return sqlite3IcuInit(db);
118403 }
118404 #endif
118405
118406 #endif
118407
118408 /************** End of icu.c *************************************************/
118409 /************** Begin file fts3_icu.c ****************************************/
118410 /*
118411 ** 2007 June 22
118412 **
118413 ** The author disclaims copyright to this source code.  In place of
118414 ** a legal notice, here is a blessing:
118415 **
118416 **    May you do good and not evil.
118417 **    May you find forgiveness for yourself and forgive others.
118418 **    May you share freely, never taking more than you give.
118419 **
118420 *************************************************************************
118421 ** This file implements a tokenizer for fts3 based on the ICU library.
118422 ** 
118423 ** $Id: fts3_icu.c,v 1.3 2008/09/01 18:34:20 danielk1977 Exp $
118424 */
118425
118426 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
118427 #ifdef SQLITE_ENABLE_ICU
118428
118429
118430 #include <unicode/ubrk.h>
118431 #include <unicode/utf16.h>
118432
118433 typedef struct IcuTokenizer IcuTokenizer;
118434 typedef struct IcuCursor IcuCursor;
118435
118436 struct IcuTokenizer {
118437   sqlite3_tokenizer base;
118438   char *zLocale;
118439 };
118440
118441 struct IcuCursor {
118442   sqlite3_tokenizer_cursor base;
118443
118444   UBreakIterator *pIter;      /* ICU break-iterator object */
118445   int nChar;                  /* Number of UChar elements in pInput */
118446   UChar *aChar;               /* Copy of input using utf-16 encoding */
118447   int *aOffset;               /* Offsets of each character in utf-8 input */
118448
118449   int nBuffer;
118450   char *zBuffer;
118451
118452   int iToken;
118453 };
118454
118455 /*
118456 ** Create a new tokenizer instance.
118457 */
118458 static int icuCreate(
118459   int argc,                            /* Number of entries in argv[] */
118460   const char * const *argv,            /* Tokenizer creation arguments */
118461   sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
118462 ){
118463   IcuTokenizer *p;
118464   int n = 0;
118465
118466   if( argc>0 ){
118467     n = strlen(argv[0])+1;
118468   }
118469   p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
118470   if( !p ){
118471     return SQLITE_NOMEM;
118472   }
118473   memset(p, 0, sizeof(IcuTokenizer));
118474
118475   if( n ){
118476     p->zLocale = (char *)&p[1];
118477     memcpy(p->zLocale, argv[0], n);
118478   }
118479
118480   *ppTokenizer = (sqlite3_tokenizer *)p;
118481
118482   return SQLITE_OK;
118483 }
118484
118485 /*
118486 ** Destroy a tokenizer
118487 */
118488 static int icuDestroy(sqlite3_tokenizer *pTokenizer){
118489   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
118490   sqlite3_free(p);
118491   return SQLITE_OK;
118492 }
118493
118494 /*
118495 ** Prepare to begin tokenizing a particular string.  The input
118496 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
118497 ** used to incrementally tokenize this string is returned in 
118498 ** *ppCursor.
118499 */
118500 static int icuOpen(
118501   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
118502   const char *zInput,                    /* Input string */
118503   int nInput,                            /* Length of zInput in bytes */
118504   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
118505 ){
118506   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
118507   IcuCursor *pCsr;
118508
118509   const int32_t opt = U_FOLD_CASE_DEFAULT;
118510   UErrorCode status = U_ZERO_ERROR;
118511   int nChar;
118512
118513   UChar32 c;
118514   int iInput = 0;
118515   int iOut = 0;
118516
118517   *ppCursor = 0;
118518
118519   if( nInput<0 ){
118520     nInput = strlen(zInput);
118521   }
118522   nChar = nInput+1;
118523   pCsr = (IcuCursor *)sqlite3_malloc(
118524       sizeof(IcuCursor) +                /* IcuCursor */
118525       nChar * sizeof(UChar) +            /* IcuCursor.aChar[] */
118526       (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
118527   );
118528   if( !pCsr ){
118529     return SQLITE_NOMEM;
118530   }
118531   memset(pCsr, 0, sizeof(IcuCursor));
118532   pCsr->aChar = (UChar *)&pCsr[1];
118533   pCsr->aOffset = (int *)&pCsr->aChar[nChar];
118534
118535   pCsr->aOffset[iOut] = iInput;
118536   U8_NEXT(zInput, iInput, nInput, c); 
118537   while( c>0 ){
118538     int isError = 0;
118539     c = u_foldCase(c, opt);
118540     U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
118541     if( isError ){
118542       sqlite3_free(pCsr);
118543       return SQLITE_ERROR;
118544     }
118545     pCsr->aOffset[iOut] = iInput;
118546
118547     if( iInput<nInput ){
118548       U8_NEXT(zInput, iInput, nInput, c);
118549     }else{
118550       c = 0;
118551     }
118552   }
118553
118554   pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
118555   if( !U_SUCCESS(status) ){
118556     sqlite3_free(pCsr);
118557     return SQLITE_ERROR;
118558   }
118559   pCsr->nChar = iOut;
118560
118561   ubrk_first(pCsr->pIter);
118562   *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
118563   return SQLITE_OK;
118564 }
118565
118566 /*
118567 ** Close a tokenization cursor previously opened by a call to icuOpen().
118568 */
118569 static int icuClose(sqlite3_tokenizer_cursor *pCursor){
118570   IcuCursor *pCsr = (IcuCursor *)pCursor;
118571   ubrk_close(pCsr->pIter);
118572   sqlite3_free(pCsr->zBuffer);
118573   sqlite3_free(pCsr);
118574   return SQLITE_OK;
118575 }
118576
118577 /*
118578 ** Extract the next token from a tokenization cursor.
118579 */
118580 static int icuNext(
118581   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
118582   const char **ppToken,               /* OUT: *ppToken is the token text */
118583   int *pnBytes,                       /* OUT: Number of bytes in token */
118584   int *piStartOffset,                 /* OUT: Starting offset of token */
118585   int *piEndOffset,                   /* OUT: Ending offset of token */
118586   int *piPosition                     /* OUT: Position integer of token */
118587 ){
118588   IcuCursor *pCsr = (IcuCursor *)pCursor;
118589
118590   int iStart = 0;
118591   int iEnd = 0;
118592   int nByte = 0;
118593
118594   while( iStart==iEnd ){
118595     UChar32 c;
118596
118597     iStart = ubrk_current(pCsr->pIter);
118598     iEnd = ubrk_next(pCsr->pIter);
118599     if( iEnd==UBRK_DONE ){
118600       return SQLITE_DONE;
118601     }
118602
118603     while( iStart<iEnd ){
118604       int iWhite = iStart;
118605       U8_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
118606       if( u_isspace(c) ){
118607         iStart = iWhite;
118608       }else{
118609         break;
118610       }
118611     }
118612     assert(iStart<=iEnd);
118613   }
118614
118615   do {
118616     UErrorCode status = U_ZERO_ERROR;
118617     if( nByte ){
118618       char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
118619       if( !zNew ){
118620         return SQLITE_NOMEM;
118621       }
118622       pCsr->zBuffer = zNew;
118623       pCsr->nBuffer = nByte;
118624     }
118625
118626     u_strToUTF8(
118627         pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
118628         &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
118629         &status                                  /* Output success/failure */
118630     );
118631   } while( nByte>pCsr->nBuffer );
118632
118633   *ppToken = pCsr->zBuffer;
118634   *pnBytes = nByte;
118635   *piStartOffset = pCsr->aOffset[iStart];
118636   *piEndOffset = pCsr->aOffset[iEnd];
118637   *piPosition = pCsr->iToken++;
118638
118639   return SQLITE_OK;
118640 }
118641
118642 /*
118643 ** The set of routines that implement the simple tokenizer
118644 */
118645 static const sqlite3_tokenizer_module icuTokenizerModule = {
118646   0,                           /* iVersion */
118647   icuCreate,                   /* xCreate  */
118648   icuDestroy,                  /* xCreate  */
118649   icuOpen,                     /* xOpen    */
118650   icuClose,                    /* xClose   */
118651   icuNext,                     /* xNext    */
118652 };
118653
118654 /*
118655 ** Set *ppModule to point at the implementation of the ICU tokenizer.
118656 */
118657 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
118658   sqlite3_tokenizer_module const**ppModule
118659 ){
118660   *ppModule = &icuTokenizerModule;
118661 }
118662
118663 #endif /* defined(SQLITE_ENABLE_ICU) */
118664 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
118665
118666 /************** End of fts3_icu.c ********************************************/